Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/cmd/internal/flowmode/cmd_fmt.go
4094 views
1
package flowmode
2
3
import (
4
"bytes"
5
"errors"
6
"fmt"
7
"io"
8
"os"
9
10
"github.com/spf13/cobra"
11
12
"github.com/grafana/agent/pkg/river/diag"
13
"github.com/grafana/agent/pkg/river/parser"
14
"github.com/grafana/agent/pkg/river/printer"
15
)
16
17
func fmtCommand() *cobra.Command {
18
f := &flowFmt{
19
write: false,
20
}
21
22
cmd := &cobra.Command{
23
Use: "fmt [flags] file",
24
Short: "Format a River file",
25
Long: `The fmt subcommand applies standard formatting rules to the specified
26
River configuration file.
27
28
If the file argument is not supplied or if the file argument is "-", then fmt will read from stdin.
29
30
The -w flag can be used to write the formatted file back to disk. -w can not be provided when fmt is reading from stdin. When -w is not provided, fmt will write the result to stdout.`,
31
Args: cobra.RangeArgs(0, 1),
32
SilenceUsage: true,
33
Aliases: []string{"format"},
34
35
RunE: func(_ *cobra.Command, args []string) error {
36
var err error
37
38
if len(args) == 0 {
39
// Read from stdin when there are no args provided.
40
err = f.Run("-")
41
} else {
42
err = f.Run(args[0])
43
}
44
45
var diags diag.Diagnostics
46
if errors.As(err, &diags) {
47
for _, diag := range diags {
48
fmt.Fprintln(os.Stderr, diag)
49
}
50
return fmt.Errorf("encountered errors during formatting")
51
}
52
53
return err
54
},
55
}
56
57
cmd.Flags().BoolVarP(&f.write, "write", "w", f.write, "write result to (source) file instead of stdout")
58
return cmd
59
}
60
61
type flowFmt struct {
62
write bool
63
}
64
65
func (ff *flowFmt) Run(configFile string) error {
66
switch configFile {
67
case "-":
68
if ff.write {
69
return fmt.Errorf("cannot use -w with standard input")
70
}
71
return format("<stdin>", nil, os.Stdin, false)
72
73
default:
74
fi, err := os.Stat(configFile)
75
if err != nil {
76
return err
77
}
78
if fi.IsDir() {
79
return fmt.Errorf("cannot format a directory")
80
}
81
82
f, err := os.Open(configFile)
83
if err != nil {
84
return err
85
}
86
defer f.Close()
87
return format(configFile, fi, f, ff.write)
88
}
89
}
90
91
func format(filename string, fi os.FileInfo, r io.Reader, write bool) error {
92
bb, err := io.ReadAll(r)
93
if err != nil {
94
return err
95
}
96
97
f, err := parser.ParseFile(filename, bb)
98
if err != nil {
99
return err
100
}
101
102
var buf bytes.Buffer
103
if err := printer.Fprint(&buf, f); err != nil {
104
return err
105
}
106
107
// Add a newline at the end of the file.
108
_, _ = buf.Write([]byte{'\n'})
109
110
if !write {
111
_, err := io.Copy(os.Stdout, &buf)
112
return err
113
}
114
115
wf, err := os.OpenFile(filename, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, fi.Mode().Perm())
116
if err != nil {
117
return err
118
}
119
defer wf.Close()
120
121
_, err = io.Copy(wf, &buf)
122
return err
123
}
124
125