Skip to content

Commit 40e05cb

Browse files
committed
chore: optimize fmt by using files from config tree.
Signed-off-by: i4k <[email protected]>
1 parent 23d377d commit 40e05cb

File tree

9 files changed

+321
-248
lines changed

9 files changed

+321
-248
lines changed

cmd/terramate/cli/cli.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,11 @@ import (
3737
"github.com/terramate-io/terramate/hcl/ast"
3838
"github.com/terramate-io/terramate/hcl/eval"
3939
"github.com/terramate-io/terramate/hcl/fmt"
40+
"github.com/terramate-io/terramate/hcl/fmt/fs"
4041
"github.com/terramate-io/terramate/hcl/info"
4142
"github.com/terramate-io/terramate/modvendor/download"
4243
"github.com/terramate-io/terramate/printer"
44+
4345
"github.com/terramate-io/terramate/safeguard"
4446
"github.com/terramate-io/terramate/tg"
4547
"github.com/terramate-io/terramate/versions"
@@ -1695,11 +1697,11 @@ func (c *cli) format() {
16951697
fatalWithDetailf(errors.E("--check conflicts with --detailed-exit-code"), "Invalid args")
16961698
}
16971699

1698-
var results []fmt.FormatResult
1700+
var results []fs.FormatResult
16991701
switch len(c.parsedArgs.Fmt.Files) {
17001702
case 0:
17011703
var err error
1702-
results, err = fmt.FormatTree(c.wd())
1704+
results, err = fs.FormatTree(c.cfg(), c.wd2())
17031705
if err != nil {
17041706
fatalWithDetailf(err, "formatting directory %s", c.wd())
17051707
}
@@ -1730,7 +1732,7 @@ func (c *cli) format() {
17301732
fallthrough
17311733
default:
17321734
var err error
1733-
results, err = fmt.FormatFiles(c.wd(), c.parsedArgs.Fmt.Files)
1735+
results, err = fs.FormatFiles(c.wd(), c.parsedArgs.Fmt.Files)
17341736
if err != nil {
17351737
fatalWithDetailf(err, "formatting files")
17361738
}
@@ -2404,6 +2406,7 @@ func (c *cli) gitSafeguardRemoteEnabled() bool {
24042406
}
24052407

24062408
func (c *cli) wd() string { return c.prj.wd }
2409+
func (c *cli) wd2() prj.Path { return prj.PrjAbsPath(c.rootdir(), c.wd()) }
24072410
func (c *cli) rootdir() string { return c.prj.rootdir }
24082411
func (c *cli) cfg() *config.Root { return c.prj.root }
24092412
func (c *cli) baseRef() string { return c.prj.baseRef }

config/config.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ type Tree struct {
6161
TerramateFiles []string
6262
OtherFiles []string
6363
TmGenFiles []string
64+
ChildrenDirs []string
6465

6566
// Children is a map of configuration dir names to tree nodes.
6667
Children map[string]*Tree
@@ -492,6 +493,7 @@ func loadTree(parentTree *Tree, cfgdir string, rootcfg *hcl.Config) (_ *Tree, er
492493
tree.TerramateFiles = filesResult.TmFiles
493494
tree.OtherFiles = filesResult.OtherFiles
494495
tree.TmGenFiles = filesResult.TmGenFiles
496+
tree.ChildrenDirs = filesResult.Dirs
495497
tree.Parent = parentTree
496498
parentTree.Children[filepath.Base(cfgdir)] = tree
497499

e2etests/core/fmt_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"github.com/madlambda/spells/assert"
1414
. "github.com/terramate-io/terramate/e2etests/internal/runner"
1515
"github.com/terramate-io/terramate/hcl/fmt"
16+
"github.com/terramate-io/terramate/hcl/fmt/fs"
1617
. "github.com/terramate-io/terramate/test/hclwrite/hclutils"
1718
"github.com/terramate-io/terramate/test/sandbox"
1819
)
@@ -258,7 +259,7 @@ func TestFmtFiles(t *testing.T) {
258259
files: []string{"non-existent.tm"},
259260
want: want{
260261
res: RunExpected{
261-
StderrRegex: string(fmt.ErrReadFile),
262+
StderrRegex: string(fs.ErrReadFile),
262263
Status: 1,
263264
},
264265
},

hcl/fmt/fmt.go

Lines changed: 0 additions & 139 deletions
Original file line numberDiff line numberDiff line change
@@ -6,30 +6,16 @@ package fmt
66

77
import (
88
"fmt"
9-
"os"
10-
"path/filepath"
11-
"sort"
129

13-
"github.com/rs/zerolog/log"
1410
"github.com/terramate-io/hcl/v2"
1511
"github.com/terramate-io/hcl/v2/hclsyntax"
1612
"github.com/terramate-io/hcl/v2/hclwrite"
1713
"github.com/terramate-io/terramate/errors"
18-
"github.com/terramate-io/terramate/fs"
1914
)
2015

2116
// ErrHCLSyntax is the error kind for syntax errors.
2217
const ErrHCLSyntax errors.Kind = "HCL syntax error"
2318

24-
// ErrReadFile is the error kind for any error related to reading the file content.
25-
const ErrReadFile errors.Kind = "failed to read file"
26-
27-
// FormatResult represents the result of a formatting operation.
28-
type FormatResult struct {
29-
path string
30-
formatted string
31-
}
32-
3319
// FormatMultiline will format the given source code.
3420
// It enforces lists to be formatted as multiline, where each
3521
// element on the list resides on its own line followed by a comma.
@@ -54,131 +40,6 @@ func Format(src, filename string) (string, error) {
5440
return string(hclwrite.Format(parsed.Bytes())), nil
5541
}
5642

57-
// FormatTree will format all Terramate configuration files
58-
// in the given tree starting at the given dir. It will recursively
59-
// navigate on sub directories. Directories starting with "." are ignored.
60-
//
61-
// Only Terramate configuration files will be formatted.
62-
//
63-
// Files that are already formatted are ignored. If all files are formatted
64-
// this function returns an empty result.
65-
//
66-
// All files will be left untouched. To save the formatted result on disk you
67-
// can use FormatResult.Save for each FormatResult.
68-
func FormatTree(dir string) ([]FormatResult, error) {
69-
logger := log.With().
70-
Str("action", "FormatTree").
71-
Str("dir", dir).
72-
Logger()
73-
74-
// TODO(i4k): use files from the config tree.
75-
res, err := fs.ListTerramateFiles(dir)
76-
if err != nil {
77-
return nil, errors.E(errFormatTree, err)
78-
}
79-
for _, fname := range res.OtherFiles {
80-
if fname == ".tmskip" {
81-
logger.Debug().Msg("skip file found: skipping whole subtree")
82-
return nil, nil
83-
}
84-
}
85-
86-
files := append([]string{}, res.TmFiles...)
87-
files = append(files, res.TmGenFiles...)
88-
89-
sort.Strings(files)
90-
91-
errs := errors.L()
92-
results, err := FormatFiles(dir, files)
93-
94-
errs.Append(err)
95-
96-
for _, d := range res.Dirs {
97-
subres, err := FormatTree(filepath.Join(dir, d))
98-
if err != nil {
99-
errs.Append(err)
100-
continue
101-
}
102-
results = append(results, subres...)
103-
}
104-
105-
if err := errs.AsError(); err != nil {
106-
return nil, err
107-
}
108-
sort.Slice(results, func(i, j int) bool {
109-
return results[i].path < results[j].path
110-
})
111-
return results, nil
112-
}
113-
114-
// FormatFiles will format all the provided Terramate paths.
115-
// Only Terramate configuration files can be reliably formatted with this function.
116-
// If HCL files for a different tool is provided, the result is unpredictable.
117-
//
118-
// Note: The provided file paths can be absolute or relative. If relative, ensure
119-
// working directory is corrected adjusted. The special `-` filename is treated as a
120-
// normal filename, then if it needs to be interpreted as `stdin` this needs to be
121-
// handled separately by the caller.
122-
//
123-
// Files that are already formatted are ignored. If all files are formatted
124-
// this function returns an empty result.
125-
//
126-
// All files will be left untouched. To save the formatted result on disk you
127-
// can use FormatResult.Save for each FormatResult.
128-
func FormatFiles(basedir string, files []string) ([]FormatResult, error) {
129-
results := []FormatResult{}
130-
errs := errors.L()
131-
132-
for _, file := range files {
133-
fname := file
134-
if !filepath.IsAbs(file) {
135-
fname = filepath.Join(basedir, file)
136-
}
137-
fileContents, err := os.ReadFile(fname)
138-
if err != nil {
139-
errs.Append(errors.E(ErrReadFile, err))
140-
continue
141-
}
142-
currentCode := string(fileContents)
143-
formatted, err := Format(currentCode, fname)
144-
if err != nil {
145-
errs.Append(err)
146-
continue
147-
}
148-
if currentCode == formatted {
149-
continue
150-
}
151-
results = append(results, FormatResult{
152-
path: fname,
153-
formatted: formatted,
154-
})
155-
}
156-
if err := errs.AsError(); err != nil {
157-
return nil, err
158-
}
159-
return results, nil
160-
}
161-
162-
// Save will save the formatted result on the original file, replacing
163-
// its original contents.
164-
func (f FormatResult) Save() error {
165-
return os.WriteFile(f.path, []byte(f.formatted), 0644)
166-
}
167-
168-
// Path is the absolute path of the original file.
169-
func (f FormatResult) Path() string {
170-
return f.path
171-
}
172-
173-
// Formatted is the contents of the original file after formatting.
174-
func (f FormatResult) Formatted() string {
175-
return f.formatted
176-
}
177-
178-
const (
179-
errFormatTree errors.Kind = "formatting tree"
180-
)
181-
18243
func fmtBody(body *hclwrite.Body) {
18344
attrs := body.Attributes()
18445
for name, attr := range attrs {

0 commit comments

Comments
 (0)