Skip to content

Commit 496b0d4

Browse files
committed
refactor: disambiguate abs/rel paths with types.
Signed-off-by: i4k <t.nateldemoura@gmail.com>
1 parent cf8c727 commit 496b0d4

File tree

125 files changed

+1374
-1296
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

125 files changed

+1374
-1296
lines changed

cmd/terramate/cli/cli.go

Lines changed: 78 additions & 78 deletions
Large diffs are not rendered by default.

cmd/terramate/cli/cliconfig/cliconfig_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ func TestLoad(t *testing.T) {
148148
homeEntry := s.DirEntry("home")
149149
file := homeEntry.CreateFile(cliconfig.Filename, tc.cfg)
150150

151-
cfg, err := cliconfig.LoadFrom(file.HostPath())
151+
cfg, err := cliconfig.LoadFrom(file.Path())
152152
errtest.Assert(t, err, tc.want.err)
153153
if err != nil {
154154
return

cmd/terramate/cli/cloud_sync_terraform_plan.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"bytes"
99
"context"
1010
"encoding/json"
11-
"os"
11+
stdos "os"
1212
"os/exec"
1313
"path/filepath"
1414
"time"
@@ -17,6 +17,7 @@ import (
1717
"github.com/terramate-io/terramate/cloud"
1818
"github.com/terramate-io/terramate/cmd/terramate/cli/clitest"
1919
"github.com/terramate-io/terramate/errors"
20+
"github.com/terramate-io/terramate/os"
2021
"github.com/terramate-io/tfjson"
2122
"github.com/terramate-io/tfjson/sanitize"
2223
)
@@ -45,11 +46,11 @@ func (c *cli) getTerraformChangeset(run stackCloudRun) (*cloud.ChangesetDetails,
4546
return nil, errors.E(clitest.ErrCloudInvalidTerraformPlanFilePath, "path must be relative to the running stack")
4647
}
4748

48-
absPlanFilePath := filepath.Join(run.Stack.HostDir(c.cfg()), planfile)
49+
absPlanFilePath := run.Stack.HostDir(c.cfg()).Join(planfile)
4950

5051
// Terragrunt writes the plan to a temporary directory, so we cannot check for its existence.
5152
if !run.Task.UseTerragrunt {
52-
_, err := os.Lstat(absPlanFilePath)
53+
_, err := stdos.Lstat(absPlanFilePath.String())
5354
if err != nil {
5455
return nil, errors.E(err, "checking plan file")
5556
}
@@ -137,7 +138,7 @@ func (c *cli) runTerraformShow(run stackCloudRun, flags ...string) (string, erro
137138
defer cancel()
138139

139140
cmd := exec.CommandContext(ctx, cmdName, args...)
140-
cmd.Dir = run.Stack.Dir.HostPath(c.rootdir())
141+
cmd.Dir = run.Stack.Dir.HostPath(c.rootdir()).String()
141142
cmd.Stdout = &stdout
142143
cmd.Stderr = &stderr
143144
cmd.Env = run.Env
@@ -162,15 +163,15 @@ func (c *cli) runTerraformShow(run stackCloudRun, flags ...string) (string, erro
162163
return stdout.String(), nil
163164
}
164165

165-
func extractTFStateSerial(planfile string) (int64, bool) {
166+
func extractTFStateSerial(planfile os.Path) (int64, bool) {
166167
logger := log.With().
167168
Str("action", "extractTFStateSerial").
168-
Str("planfile", planfile).
169+
Stringer("planfile", planfile).
169170
Logger()
170171

171-
planReader, err := zip.OpenReader(planfile)
172+
planReader, err := zip.OpenReader(planfile.String())
172173
if err != nil {
173-
if b, err := os.ReadFile(planfile); err == nil {
174+
if b, err := stdos.ReadFile(planfile.String()); err == nil {
174175
if bytes.HasPrefix(b, []byte("tfplan")) {
175176
logger.Debug().Msg("plan serial extraction failed: plan file was created with a pre 1.22 version of terraform")
176177
} else {

cmd/terramate/cli/github/event_test.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ package github_test
55

66
import (
77
"os"
8-
"path/filepath"
98
"testing"
109

1110
"github.com/madlambda/spells/assert"
@@ -29,7 +28,7 @@ func TestGetEventPR(t *testing.T) {
2928
draft bool
3029
}
3130

32-
nonExistentEventFile := filepath.Join(test.NonExistingDir(t), "event_pull_request.json")
31+
nonExistentEventFile := test.NonExistingDir(t).Join("event_pull_request.json")
3332

3433
type testcase struct {
3534
name string
@@ -56,7 +55,7 @@ func TestGetEventPR(t *testing.T) {
5655
{
5756
name: "non existent path",
5857
env: map[string]string{
59-
"GITHUB_EVENT_PATH": nonExistentEventFile,
58+
"GITHUB_EVENT_PATH": nonExistentEventFile.String(),
6059
},
6160
want: want{
6261
err: os.ErrNotExist,

cmd/terramate/cli/project.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ package cli
66
import (
77
"fmt"
88

9+
"github.com/terramate-io/terramate/os"
10+
911
"github.com/rs/zerolog/log"
1012
"github.com/terramate-io/terramate/config"
1113
"github.com/terramate-io/terramate/errors"
@@ -16,8 +18,8 @@ import (
1618
)
1719

1820
type project struct {
19-
rootdir string
20-
wd string
21+
rootdir os.Path
22+
wd os.Path
2123
isRepo bool
2224
root config.Root
2325
baseRef string
@@ -178,7 +180,7 @@ func (p project) defaultBranchRef() string {
178180
func (p *project) setDefaults() error {
179181
logger := log.With().
180182
Str("action", "setDefaults()").
181-
Str("workingDir", p.wd).
183+
Stringer("workingDir", p.wd).
182184
Logger()
183185

184186
logger.Debug().Msg("Set defaults.")

cmd/terramate/cli/run.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -487,7 +487,7 @@ func (c *cli) runAll(
487487
cmd := exec.Command(backend.Command[0], backend.Command[1:]...)
488488
cmd.Stdout = &stdout
489489
cmd.Stderr = &stderr
490-
cmd.Dir = otherStack.HostDir(c.cfg())
490+
cmd.Dir = otherStack.HostDir(c.cfg()).String()
491491
var inputVal cty.Value
492492
err := cmd.Run()
493493
if err != nil {
@@ -579,7 +579,7 @@ func (c *cli) runAll(
579579
}
580580

581581
cmd := exec.Command(cmdPath, task.Cmd[1:]...)
582-
cmd.Dir = run.Stack.HostDir(c.cfg())
582+
cmd.Dir = run.Stack.HostDir(c.cfg()).String()
583583
cmd.Env = environ
584584

585585
stdout := c.stdout

cmd/tgdeps/main.go

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@ import (
88
"encoding/json"
99
"flag"
1010
"fmt"
11-
"os"
11+
stdos "os"
1212

1313
"github.com/rs/zerolog"
14+
"github.com/terramate-io/terramate/os"
1415
"github.com/terramate-io/terramate/project"
1516
"github.com/terramate-io/terramate/tg"
1617
)
@@ -25,12 +26,15 @@ func main() {
2526
if *trace {
2627
zerolog.SetGlobalLevel(zerolog.TraceLevel)
2728
}
28-
rootdir, err := os.Getwd()
29+
rootdirStr, err := stdos.Getwd()
2930
abortOnErr(err)
3031

31-
var dir string
32+
// assume current dir is project root dir.
33+
rootdir := os.NewHostPath(rootdirStr)
34+
35+
var dir os.Path
3236
if len(flag.Args()) == 2 {
33-
dir = flag.Arg(1)
37+
dir = rootdir.Join(flag.Arg(1))
3438
} else {
3539
dir = rootdir
3640
}
@@ -56,7 +60,7 @@ func main() {
5660

5761
func abortOnErr(err error) {
5862
if err != nil {
59-
fmt.Fprintf(os.Stderr, "error: %s\n", err)
60-
os.Exit(1)
63+
fmt.Fprintf(stdos.Stderr, "error: %s\n", err)
64+
stdos.Exit(1)
6165
}
6266
}

config/config.go

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"bytes"
88
"fmt"
99
"io/fs"
10-
"os"
10+
stdos "os"
1111
"path"
1212
"path/filepath"
1313
"sort"
@@ -25,6 +25,7 @@ import (
2525
"github.com/terramate-io/terramate/hcl"
2626
"github.com/terramate-io/terramate/hcl/ast"
2727
"github.com/terramate-io/terramate/hcl/info"
28+
"github.com/terramate-io/terramate/os"
2829
"github.com/terramate-io/terramate/printer"
2930
"github.com/terramate-io/terramate/project"
3031
"github.com/zclconf/go-cty/cty"
@@ -72,7 +73,7 @@ type Tree struct {
7273
root *Root
7374
stack *Stack
7475

75-
dir string
76+
dir os.Path
7677
}
7778

7879
// DirElem represents a node which is represented by a directory.
@@ -89,7 +90,7 @@ type List[T DirElem] []T
8990
// the config in fromdir and all parent directories until / is reached.
9091
// If the configuration is found, it returns the whole configuration tree,
9192
// configpath != "" and found as true.
92-
func TryLoadConfig(fromdir string) (tree *Root, configpath string, found bool, err error) {
93+
func TryLoadConfig(fromdir os.Path) (tree *Root, configpath os.Path, found bool, err error) {
9394
for {
9495
ok, err := hcl.IsRootConfig(fromdir)
9596
if err != nil {
@@ -130,7 +131,7 @@ func NewRoot(tree *Tree) *Root {
130131
}
131132

132133
// LoadRoot loads the root configuration tree.
133-
func LoadRoot(rootdir string) (*Root, error) {
134+
func LoadRoot(rootdir os.Path) (*Root, error) {
134135
rootcfg, err := hcl.ParseDir(rootdir, rootdir)
135136
if err != nil {
136137
return nil, err
@@ -148,7 +149,7 @@ func LoadRoot(rootdir string) (*Root, error) {
148149
func (root *Root) Tree() *Tree { return &root.tree }
149150

150151
// HostDir returns the root directory.
151-
func (root *Root) HostDir() string { return root.tree.RootDir() }
152+
func (root *Root) Path() os.Path { return root.tree.Path() }
152153

153154
// Lookup a node from the root using a filesystem query path.
154155
func (root *Root) Lookup(path project.Path) (*Tree, bool) {
@@ -229,20 +230,20 @@ func (root *Root) LoadSubTree(cfgdir project.Path) error {
229230
parentNode = root.Tree()
230231
}
231232

232-
rootdir := root.HostDir()
233+
rootdir := root.Path()
233234

234235
relpath := strings.TrimPrefix(cfgdir.String(), parent.String())
235236
relpath = strings.TrimPrefix(relpath, "/")
236237
components := strings.Split(relpath, "/")
237238
nextComponent := components[0]
238-
subtreeDir := filepath.Join(rootdir, parent.String(), nextComponent)
239+
subtreeDir := rootdir.Join(parent.String(), nextComponent)
239240

240241
node, err := loadTree(root.Tree(), subtreeDir, nil)
241242
if err != nil {
242243
return errors.E(err, "failed to load config from %s", subtreeDir)
243244
}
244245

245-
if node.HostDir() == rootdir {
246+
if node.Path() == rootdir {
246247
// root configuration reloaded
247248
*root = *NewRoot(node)
248249
} else {
@@ -269,8 +270,8 @@ func (root *Root) Runtime() project.Runtime {
269270

270271
func (root *Root) initRuntime() {
271272
rootfs := cty.ObjectVal(map[string]cty.Value{
272-
"absolute": cty.StringVal(root.HostDir()),
273-
"basename": cty.StringVal(filepath.ToSlash(filepath.Base(root.HostDir()))),
273+
"absolute": cty.StringVal(root.Path().String()),
274+
"basename": cty.StringVal(filepath.ToSlash(filepath.Base(root.Path().String()))),
274275
})
275276
rootpath := cty.ObjectVal(map[string]cty.Value{
276277
"fs": rootfs,
@@ -288,8 +289,8 @@ func (root *Root) initRuntime() {
288289
}
289290
}
290291

291-
// HostDir is the node absolute directory in the host.
292-
func (tree *Tree) HostDir() string {
292+
// Path is the node absolute directory in the host.
293+
func (tree *Tree) Path() os.Path {
293294
return tree.dir
294295
}
295296

@@ -299,7 +300,7 @@ func (tree *Tree) Dir() project.Path {
299300
}
300301

301302
// RootDir returns the tree root directory..
302-
func (tree *Tree) RootDir() string {
303+
func (tree *Tree) RootDir() os.Path {
303304
if tree.Parent != nil {
304305
return tree.Parent.RootDir()
305306
}
@@ -422,13 +423,13 @@ func (l List[T]) Len() int { return len(l) }
422423
func (l List[T]) Less(i, j int) bool { return l[i].Dir().String() < l[j].Dir().String() }
423424
func (l List[T]) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
424425

425-
func loadTree(parentTree *Tree, cfgdir string, rootcfg *hcl.Config) (_ *Tree, err error) {
426+
func loadTree(parentTree *Tree, cfgdir os.Path, rootcfg *hcl.Config) (_ *Tree, err error) {
426427
logger := log.With().
427428
Str("action", "config.loadTree()").
428-
Str("dir", cfgdir).
429+
Stringer("dir", cfgdir).
429430
Logger()
430431

431-
f, err := os.Open(cfgdir)
432+
f, err := stdos.Open(cfgdir.String())
432433
if err != nil {
433434
return nil, errors.E(err, "failed to open cfg directory")
434435
}
@@ -469,7 +470,7 @@ func loadTree(parentTree *Tree, cfgdir string, rootcfg *hcl.Config) (_ *Tree, er
469470

470471
tree.Node = cfg
471472
tree.Parent = parentTree
472-
parentTree.Children[filepath.Base(cfgdir)] = tree
473+
parentTree.Children[cfgdir.Base()] = tree
473474

474475
parentTree = tree
475476
}
@@ -485,7 +486,7 @@ func loadTree(parentTree *Tree, cfgdir string, rootcfg *hcl.Config) (_ *Tree, er
485486
continue
486487
}
487488

488-
dir := filepath.Join(cfgdir, fname)
489+
dir := cfgdir.Join(fname)
489490
node, err := loadTree(parentTree, dir, rootcfg)
490491
if err != nil {
491492
return nil, errors.E(err, "loading from %s", dir)
@@ -497,7 +498,7 @@ func loadTree(parentTree *Tree, cfgdir string, rootcfg *hcl.Config) (_ *Tree, er
497498
return parentTree, nil
498499
}
499500

500-
func processTmGenFiles(rootTree *Tree, cfg *hcl.Config, cfgdir string, dirEntries []fs.DirEntry) error {
501+
func processTmGenFiles(rootTree *Tree, cfg *hcl.Config, cfgdir os.Path, dirEntries []fs.DirEntry) error {
501502
const tmgenSuffix = ".tmgen"
502503

503504
tmgenEnabled := rootTree.hasExperiment("tmgen")
@@ -509,7 +510,7 @@ func processTmGenFiles(rootTree *Tree, cfg *hcl.Config, cfgdir string, dirEntrie
509510
continue
510511
}
511512

512-
absFname := filepath.Join(cfgdir, fname)
513+
absFname := cfgdir.Join(fname)
513514

514515
if !tmgenEnabled {
515516
printer.Stderr.Warn(
@@ -520,7 +521,7 @@ func processTmGenFiles(rootTree *Tree, cfg *hcl.Config, cfgdir string, dirEntrie
520521
continue
521522
}
522523

523-
content, err := os.ReadFile(absFname)
524+
content, err := stdos.ReadFile(absFname.String())
524525
if err != nil {
525526
return errors.E(err, "failed to read .tmgen file")
526527
}
@@ -559,10 +560,10 @@ func processTmGenFiles(rootTree *Tree, cfg *hcl.Config, cfgdir string, dirEntrie
559560

560561
implicitGenBlock := hcl.GenHCLBlock{
561562
IsImplicitBlock: true,
562-
Dir: project.PrjAbsPath(rootTree.HostDir(), cfgdir),
563+
Dir: project.PrjAbsPath(rootTree.Path(), cfgdir),
563564
Inherit: inheritAttr,
564-
Range: info.NewRange(rootTree.HostDir(), hhcl.Range{
565-
Filename: absFname,
565+
Range: info.NewRange(rootTree.Path(), hhcl.Range{
566+
Filename: absFname.String(),
566567
Start: hhcl.InitialPos,
567568
End: hhcl.Pos{
568569
Line: nLines,
@@ -596,13 +597,13 @@ func (tree *Tree) NonEmptyGlobalsParent() *Tree {
596597
}
597598

598599
// IsStack returns true if the given directory is a stack, false otherwise.
599-
func IsStack(root *Root, dir string) bool {
600-
node, ok := root.Lookup(project.PrjAbsPath(root.HostDir(), dir))
600+
func IsStack(root *Root, dir os.Path) bool {
601+
node, ok := root.Lookup(project.PrjAbsPath(root.Path(), dir))
601602
return ok && node.IsStack()
602603
}
603604

604605
// NewTree creates a new tree node.
605-
func NewTree(cfgdir string) *Tree {
606+
func NewTree(cfgdir os.Path) *Tree {
606607
return &Tree{
607608
dir: cfgdir,
608609
Children: make(map[string]*Tree),
@@ -677,8 +678,8 @@ func Skip(name string) bool {
677678
return name[0] == '.'
678679
}
679680

680-
func parentDir(dir string) (string, bool) {
681-
parent := filepath.Dir(dir)
681+
func parentDir(dir os.Path) (os.Path, bool) {
682+
parent := dir.Dir()
682683
return parent, parent != dir
683684
}
684685

0 commit comments

Comments
 (0)