Skip to content

Commit 64d4b1e

Browse files
committed
shell: fail if workDir is explicitly set but not accessible
Signed-off-by: Akihiro Suda <[email protected]>
1 parent 4aa6303 commit 64d4b1e

File tree

1 file changed

+21
-13
lines changed

1 file changed

+21
-13
lines changed

cmd/limactl/shell.go

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -55,30 +55,38 @@ func shellAction(clicontext *cli.Context) error {
5555
return err
5656
}
5757

58-
// Buildup changeDirCmd to "cd workDir || cd currentDir || cd homeDir"
58+
// When workDir is explicitly set, the shell MUST have workDir as the cwd, or exit with an error.
59+
//
60+
// changeDirCmd := "cd workDir || exit 1" if workDir != ""
61+
// := "cd hostCurrentDir || cd hostHomeDir" if workDir == ""
5962
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()
63+
if workDir := clicontext.String("workdir"); workDir != "" {
64+
changeDirCmd = fmt.Sprintf("cd %q || exit 1", workDir)
65+
// FIXME: check whether y.Mounts contains the home, not just len > 0
66+
} else if len(y.Mounts) > 0 {
67+
hostCurrentDir, err := os.Getwd()
6868
if err == nil {
69-
changeDirCmd = fmt.Sprintf("%s || cd %q", changeDirCmd, currentDir)
69+
changeDirCmd = fmt.Sprintf("cd %q", hostCurrentDir)
7070
} else {
71+
changeDirCmd = "false"
7172
logrus.WithError(err).Warn("failed to get the current directory")
7273
}
73-
homeDir, err := os.UserHomeDir()
74+
hostHomeDir, err := os.UserHomeDir()
7475
if err == nil {
75-
changeDirCmd = fmt.Sprintf("%s || cd %q", changeDirCmd, homeDir)
76+
changeDirCmd = fmt.Sprintf("%s || cd %q", changeDirCmd, hostHomeDir)
7677
} else {
7778
logrus.WithError(err).Warn("failed to get the home directory")
7879
}
80+
} else {
81+
logrus.Debug("the host home does not seem mounted, so the guest shell will have a different cwd")
82+
}
83+
84+
if changeDirCmd == "" {
85+
changeDirCmd = "false"
7986
}
87+
logrus.Debugf("changeDirCmd=%q", changeDirCmd)
8088

81-
script := fmt.Sprintf(" %s ; exec bash --login", changeDirCmd)
89+
script := fmt.Sprintf("%s ; exec bash --login", changeDirCmd)
8290
if clicontext.NArg() > 1 {
8391
script += fmt.Sprintf(" -c %q", shellescape.QuoteCommand(clicontext.Args().Tail()))
8492
}

0 commit comments

Comments
 (0)