Format all HCL2 files in path and return the total bytes formatted. If any error is encountered, zero bytes will be returned. Path can be a directory or a file.
(paths []string)
| 56 | // |
| 57 | // Path can be a directory or a file. |
| 58 | func (f *HCL2Formatter) Format(paths []string) (int, hcl.Diagnostics) { |
| 59 | var diags hcl.Diagnostics |
| 60 | var bytesModified int |
| 61 | |
| 62 | if f.parser == nil { |
| 63 | f.parser = hclparse.NewParser() |
| 64 | } |
| 65 | |
| 66 | for _, path := range paths { |
| 67 | s, err := os.Stat(path) |
| 68 | |
| 69 | if err != nil || !s.IsDir() { |
| 70 | bytesModified, diags = f.formatFile(path, diags, bytesModified) |
| 71 | } else { |
| 72 | fileInfos, err := os.ReadDir(path) |
| 73 | if err != nil { |
| 74 | diag := &hcl.Diagnostic{ |
| 75 | Severity: hcl.DiagError, |
| 76 | Summary: "Cannot read hcl directory", |
| 77 | Detail: err.Error(), |
| 78 | } |
| 79 | diags = append(diags, diag) |
| 80 | return bytesModified, diags |
| 81 | } |
| 82 | |
| 83 | for _, fileInfo := range fileInfos { |
| 84 | name := fileInfo.Name() |
| 85 | if f.shouldIgnoreFile(name) { |
| 86 | continue |
| 87 | } |
| 88 | filename := filepath.Join(path, name) |
| 89 | if fileInfo.IsDir() { |
| 90 | if f.Recursive { |
| 91 | var tempDiags hcl.Diagnostics |
| 92 | var tempBytesModified int |
| 93 | var newPaths []string |
| 94 | newPaths = append(newPaths, filename) |
| 95 | tempBytesModified, tempDiags = f.Format(newPaths) |
| 96 | bytesModified += tempBytesModified |
| 97 | diags = diags.Extend(tempDiags) |
| 98 | } |
| 99 | continue |
| 100 | } |
| 101 | if isHcl2FileOrVarFile(filename) { |
| 102 | bytesModified, diags = f.formatFile(filename, diags, bytesModified) |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | return bytesModified, diags |
| 109 | } |
| 110 | |
| 111 | // processFile formats the source contents of filename and return the formatted data. |
| 112 | // overwriting the contents of the original when the f.Write is true; a diff of the changes |