-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathfmt.go
85 lines (72 loc) · 1.59 KB
/
fmt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package cmd
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"github.com/spf13/cobra"
"github.com/gitpod-io/leeway/pkg/leeway"
)
// fmtCmd represents the version command
var fmtCmd = &cobra.Command{
Use: "fmt [files...]",
Short: "Formats BUILD.yaml files",
RunE: func(cmd *cobra.Command, args []string) error {
fns := args
if len(fns) == 0 {
ws, err := getWorkspace()
if err != nil {
return err
}
for _, comp := range ws.Components {
fns = append(fns, filepath.Join(comp.Origin, "BUILD.yaml"))
}
}
var (
inPlace, _ = cmd.Flags().GetBool("in-place")
fix, _ = cmd.Flags().GetBool("fix")
)
for _, fn := range fns {
err := formatBuildYaml(fn, inPlace, fix)
if err != nil {
return err
}
}
return nil
},
}
func formatBuildYaml(fn string, inPlace, fix bool) error {
f, err := os.OpenFile(fn, os.O_RDWR, 0644)
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
fmt.Fprintf(os.Stderr, "warning: failed to close file: %v\n", err)
}
}()
var out io.Writer = os.Stdout
if inPlace {
buf := bytes.NewBuffer(nil)
out = buf
//nolint:errcheck
defer func() {
f.Seek(0, 0)
f.Truncate(0)
io.Copy(f, buf)
}()
} else {
fmt.Printf("---\n# %s\n", fn)
}
err = leeway.FormatBUILDyaml(out, f, fix)
if err != nil {
return err
}
return nil
}
func init() {
rootCmd.AddCommand(fmtCmd)
fmtCmd.Flags().BoolP("in-place", "i", false, "format file in place rather than printing it to stdout")
fmtCmd.Flags().BoolP("fix", "f", false, "fix issues other than formatting (e.g. deprecated package types)")
}