Skip to content

Commit e048992

Browse files
authored
Merge pull request #40 from rancher-sandbox/workdir
Update logic for shell workdir
2 parents 329665d + c5fa84c commit e048992

File tree

1 file changed

+28
-23
lines changed

1 file changed

+28
-23
lines changed

cmd/limactl/shell.go

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -26,19 +26,6 @@ var shellCommand = &cli.Command{
2626
&cli.StringFlag{
2727
Name: "workdir",
2828
Usage: "working directory",
29-
Value: func() string {
30-
wd, err := os.Getwd()
31-
if err != nil {
32-
logrus.WithError(err).Warn("failed to get the current directory")
33-
home, err := os.UserHomeDir()
34-
if err != nil {
35-
logrus.WithError(err).Warn("failed to get the home directory")
36-
return "/"
37-
}
38-
return home
39-
}
40-
return wd
41-
}(),
4229
},
4330
},
4431
Action: shellAction,
@@ -60,16 +47,6 @@ func shellAction(clicontext *cli.Context) error {
6047
strings.Join(clicontext.Args().Slice()[2:], " "))
6148
}
6249

63-
hostHome, err := os.UserHomeDir()
64-
if err != nil {
65-
return err
66-
}
67-
68-
script := fmt.Sprintf(" cd %q || cd %q ; exec bash --login", clicontext.String("workdir"), hostHome)
69-
if clicontext.NArg() > 1 {
70-
script += fmt.Sprintf(" -c %q", shellescape.QuoteCommand(clicontext.Args().Tail()))
71-
}
72-
7350
y, instDir, err := store.LoadYAMLByInstanceName(instName)
7451
if err != nil {
7552
if errors.Is(err, os.ErrNotExist) {
@@ -78,6 +55,34 @@ func shellAction(clicontext *cli.Context) error {
7855
return err
7956
}
8057

58+
// Buildup changeDirCmd to "cd workDir || cd currentDir || cd homeDir"
59+
var changeDirCmd string
60+
workDir := clicontext.String("workdir")
61+
if workDir == "" {
62+
changeDirCmd = "false"
63+
} else {
64+
changeDirCmd = fmt.Sprintf("cd %q", workDir)
65+
}
66+
if len(y.Mounts) > 0 {
67+
currentDir, err := os.Getwd()
68+
if err == nil {
69+
changeDirCmd = fmt.Sprintf("%s || cd %q", changeDirCmd, currentDir)
70+
} else {
71+
logrus.WithError(err).Warn("failed to get the current directory")
72+
}
73+
homeDir, err := os.UserHomeDir()
74+
if err == nil {
75+
changeDirCmd = fmt.Sprintf("%s || cd %q", changeDirCmd, homeDir)
76+
} else {
77+
logrus.WithError(err).Warn("failed to get the home directory")
78+
}
79+
}
80+
81+
script := fmt.Sprintf(" %s ; exec bash --login", changeDirCmd)
82+
if clicontext.NArg() > 1 {
83+
script += fmt.Sprintf(" -c %q", shellescape.QuoteCommand(clicontext.Args().Tail()))
84+
}
85+
8186
arg0, err := exec.LookPath("ssh")
8287
if err != nil {
8388
return err

0 commit comments

Comments
 (0)