diff options
author | Valery Piashchynski <[email protected]> | 2022-04-28 11:52:16 +0200 |
---|---|---|
committer | Valery Piashchynski <[email protected]> | 2022-04-28 12:16:41 +0200 |
commit | 62ca41aca6d5058da36088ee453f751c1c1bbf3d (patch) | |
tree | 6b9f0e8cc51772315d1a1354bdeeaa043a96a671 /internal/cli | |
parent | 71de185b717ec51dac9b6034f456a9fac6412d14 (diff) |
fix chdir routine
Signed-off-by: Valery Piashchynski <[email protected]>
Diffstat (limited to 'internal/cli')
-rw-r--r-- | internal/cli/root.go | 10 | ||||
-rw-r--r-- | internal/cli/root_test.go | 30 |
2 files changed, 37 insertions, 3 deletions
diff --git a/internal/cli/root.go b/internal/cli/root.go index 7e22124a..0df74be0 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -46,18 +46,22 @@ func NewCommand(cmdName string) *cobra.Command { //nolint:funlen return errors.Str("no configuration file provided") } + // if user set the wd, change the current wd if workDir != "" { if err := os.Chdir(workDir); err != nil { return err } } + // try to get the absolute path to the configuration if absPath, err := filepath.Abs(*cfgFile); err == nil { *cfgFile = absPath // switch config path to the absolute - // force working absPath related to config file - if err = os.Chdir(filepath.Dir(absPath)); err != nil { - return err + // if workDir is empty - force working absPath related to config file + if workDir == "" { + if err = os.Chdir(filepath.Dir(absPath)); err != nil { + return err + } } } diff --git a/internal/cli/root_test.go b/internal/cli/root_test.go index 602b9d3b..f77acec3 100644 --- a/internal/cli/root_test.go +++ b/internal/cli/root_test.go @@ -135,3 +135,33 @@ func TestCommandNoEnvFileNoError(t *testing.T) { _ = os.RemoveAll(path.Join(tmp, ".rr.yaml")) }) } + +func TestCommandWorkingDir(t *testing.T) { + tmp := os.TempDir() + + cmd := cli.NewCommand("serve") + cmd.SetArgs([]string{"-w", tmp}) + + var executed bool + + var wd string + + f2, err := os.Create(path.Join(tmp, ".rr.yaml")) + require.NoError(t, err) + + if cmd.Run == nil { // override "Run" property for test (if it was not set) + cmd.Run = func(cmd *cobra.Command, args []string) { + executed = true + wd, _ = os.Getwd() + } + } + + assert.NoError(t, cmd.Execute()) + assert.True(t, executed) + assert.Equal(t, "/tmp", wd) + + t.Cleanup(func() { + _ = f2.Close() + _ = os.RemoveAll(path.Join(tmp, ".rr.yaml")) + }) +} |