1 // Derivative work from:
2 // - https://golang.org/src/cmd/gofmt/gofmt.go
3 // - https://github.com/fatih/hclfmt
18 "github.com/hashicorp/hcl/hcl/printer"
22 ErrWriteStdin = errors.New("cannot use write option with standard input")
26 List bool // list files whose formatting differs
27 Write bool // write result to (source) file instead of stdout
28 Diff bool // display diffs of formatting changes
31 func isValidFile(f os.FileInfo, extensions []string) bool {
32 if !f.IsDir() && !strings.HasPrefix(f.Name(), ".") {
33 for _, ext := range extensions {
34 if strings.HasSuffix(f.Name(), "."+ext) {
43 // If in == nil, the source is the contents of the file with the given filename.
44 func processFile(filename string, in io.Reader, out io.Writer, stdin bool, opts Options) error {
46 f, err := os.Open(filename)
54 src, err := ioutil.ReadAll(in)
59 res, err := printer.Format(src)
61 return fmt.Errorf("In %s: %s", filename, err)
64 if !bytes.Equal(src, res) {
65 // formatting has changed
67 fmt.Fprintln(out, filename)
70 err = ioutil.WriteFile(filename, res, 0644)
76 data, err := diff(src, res)
78 return fmt.Errorf("computing diff: %s", err)
80 fmt.Fprintf(out, "diff a/%s b/%s\n", filename, filename)
85 if !opts.List && !opts.Write && !opts.Diff {
86 _, err = out.Write(res)
92 func walkDir(path string, extensions []string, stdout io.Writer, opts Options) error {
93 visitFile := func(path string, f os.FileInfo, err error) error {
94 if err == nil && isValidFile(f, extensions) {
95 err = processFile(path, nil, stdout, false, opts)
100 return filepath.Walk(path, visitFile)
104 paths, extensions []string,
113 if err := processFile("<standard input>", stdin, stdout, true, opts); err != nil {
119 for _, path := range paths {
120 switch dir, err := os.Stat(path); {
124 if err := walkDir(path, extensions, stdout, opts); err != nil {
128 if err := processFile(path, nil, stdout, false, opts); err != nil {
137 func diff(b1, b2 []byte) (data []byte, err error) {
138 f1, err := ioutil.TempFile("", "")
142 defer os.Remove(f1.Name())
145 f2, err := ioutil.TempFile("", "")
149 defer os.Remove(f2.Name())
155 data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
157 // diff exits with a non-zero status when the files don't match.
158 // Ignore that failure as long as we get output.