跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

shell.go

958 行 · 30.8 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package main
5
6import (
7 "context"
8 "errors"
9 "fmt"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "regexp"
14 "runtime"
15 "strconv"
16 "strings"
17
18 "al.essio.dev/pkg/shellescape"
19 "github.com/coreos/go-semver/semver"
20 "github.com/lima-vm/sshocker/pkg/ssh"
21 "github.com/mattn/go-isatty"
22 "github.com/sirupsen/logrus"
23 "github.com/spf13/cobra"
24
25 "github.com/lima-vm/lima/v2/pkg/autostart"
26 "github.com/lima-vm/lima/v2/pkg/copytool"
27 "github.com/lima-vm/lima/v2/pkg/envutil"
28 "github.com/lima-vm/lima/v2/pkg/fsutil"
29 "github.com/lima-vm/lima/v2/pkg/instance"
30 "github.com/lima-vm/lima/v2/pkg/limatype"
31 "github.com/lima-vm/lima/v2/pkg/limayaml"
32 "github.com/lima-vm/lima/v2/pkg/localpathutil"
33 "github.com/lima-vm/lima/v2/pkg/networks/reconcile"
34 "github.com/lima-vm/lima/v2/pkg/sshutil"
35 "github.com/lima-vm/lima/v2/pkg/store"
36 "github.com/lima-vm/lima/v2/pkg/uiutil"
37)
38
39const shellHelp = `Execute shell in Lima
40
41lima command is provided as an alias for limactl shell $LIMA_INSTANCE. $LIMA_INSTANCE defaults to "` + DefaultInstanceName + `".
42
43By default, the first 'ssh' executable found in the host's PATH is used to connect to the Lima instance.
44A custom ssh alias can be used instead by setting the $` + sshutil.EnvShellSSH + ` environment variable.
45
46Environment Variables:
47 --preserve-env: Propagates host environment variables to the guest instance.
48 Use LIMA_SHELLENV_BLOCK to specify variables to block (prefix with + to extend the default blocklist).
49 Use LIMA_SHELLENV_ALLOW to exempt specific variables from the blocklist.
50
51Hint: try --debug to show the detailed logs, if it seems hanging (mostly due to some SSH issue).
52`
53
54func newShellCommand() *cobra.Command {
55 shellCmd := &cobra.Command{
56 Use: "shell [flags] INSTANCE [COMMAND...]",
57 SuggestFor: []string{"ssh"},
58 Short: "Execute shell in Lima",
59 Long: shellHelp,
60 Args: WrapArgsError(cobra.ArbitraryArgs),
61 RunE: shellAction,
62 ValidArgsFunction: shellBashComplete,
63 SilenceErrors: true,
64 GroupID: basicCommand,
65 }
66
67 shellCmd.Flags().SetInterspersed(false)
68
69 shellCmd.Flags().String("instance", "", "Instance name (used by the lima wrapper script)")
70 _ = shellCmd.Flags().MarkHidden("instance")
71 shellCmd.Flags().String("shell", "", "Shell interpreter, e.g. /bin/bash")
72 shellCmd.Flags().String("workdir", "", "Working directory")
73 shellCmd.Flags().Bool("reconnect", false, "Reconnect to the SSH session")
74 shellCmd.Flags().Bool("preserve-env", false, "Propagate environment variables to the shell")
75 shellCmd.Flags().Bool("start", false, "Start the instance if it is not already running")
76 shellCmd.Flags().String("sync", "", "Copy a host directory to the guest and vice-versa upon exit")
77
78 return shellCmd
79}
80
81const (
82 rsyncMinimumSrcDirDepth = 4 // Depth of "/Users/USER" is 3.
83 colorGray = "\033[0;90m"
84 colorNone = "\033[0m"
85)
86
87func shellAction(cmd *cobra.Command, args []string) error {
88 ctx := cmd.Context()
89 flags := cmd.Flags()
90 tty, err := flags.GetBool("tty")
91 if err != nil {
92 return err
93 }
94
95 // When --instance is specified, all positional args are treated as COMMAND.
96 // Otherwise, the first positional arg is the instance name (backward compatible).
97 instName, err := flags.GetString("instance")
98 if err != nil {
99 return err
100 }
101 if instName != "" {
102 // All args are COMMAND; prepend a placeholder instance name so the rest of the code works unchanged.
103 args = append([]string{instName}, args...)
104 } else {
105 if len(args) == 0 {
106 return errors.New("requires instance name as first argument")
107 }
108 // simulate the behavior of double dash
109 newArg := []string{}
110 if len(args) >= 2 && args[1] == "--" {
111 newArg = append(newArg, args[:1]...)
112 newArg = append(newArg, args[2:]...)
113 args = newArg
114 }
115 instName = args[0]
116 }
117
118 if len(args) >= 2 {
119 switch args[1] {
120 case "create", "start", "delete", "shell":
121 // `lima start` (alias of `limactl $LIMA_INSTANCE start`) is probably a typo of `limactl start`
122 logrus.Warnf("Perhaps you meant `limactl %s`?", strings.Join(args[1:], " "))
123 }
124 }
125
126 inst, err := store.Inspect(ctx, instName)
127 if err != nil {
128 if errors.Is(err, os.ErrNotExist) {
129 return fmt.Errorf("instance %#q does not exist, run `limactl create %s` to create a new instance", instName, instName)
130 }
131 return err
132 }
133 if len(inst.Errors) > 0 {
134 logrus.WithError(errors.Join(inst.Errors...)).Errorf("Instance %#q has configuration errors", instName)
135 }
136 if inst.Config == nil {
137 return fmt.Errorf("instance %#q has no configuration", instName)
138 }
139 if inst.Status == limatype.StatusStopped {
140 startNow, err := flags.GetBool("start")
141 if err != nil {
142 return err
143 }
144
145 if tty && !flags.Changed("start") {
146 startNow, err = askWhetherToStart(cmd)
147 if err != nil {
148 return err
149 }
150 }
151
152 if !startNow {
153 return fmt.Errorf("instance %#q is stopped, run `limactl start %s` to start the instance", instName, instName)
154 }
155
156 // Network reconciliation will be performed by the process launched by the autostart manager
157 if registered, err := autostart.IsRegistered(ctx, inst); err != nil && !errors.Is(err, autostart.ErrNotSupported) {
158 return fmt.Errorf("failed to check if the autostart entry for instance %#q is registered: %w", inst.Name, err)
159 } else if !registered {
160 err = reconcile.Reconcile(ctx, inst.Name)
161 if err != nil {
162 return err
163 }
164 }
165
166 err = instance.Start(instance.WithLaunchingShell(ctx), inst, false, false)
167 if err != nil {
168 return err
169 }
170
171 inst, err = store.Inspect(ctx, instName)
172 if err != nil {
173 return err
174 }
175 }
176
177 restart, err := cmd.Flags().GetBool("reconnect")
178 if err != nil {
179 return err
180 }
181 if restart && sshutil.IsControlMasterExisting(inst.Dir) {
182 logrus.Infof("Exiting ssh session for the instance %#q", instName)
183
184 sshConfig := &ssh.SSHConfig{
185 ConfigFile: inst.SSHConfigFile,
186 Persist: false,
187 AdditionalArgs: []string{},
188 }
189
190 if err := ssh.ExitMaster(inst.Hostname, inst.SSHLocalPort, sshConfig); err != nil {
191 // `ssh -O exit` fails when the control socket file exists but the
192 // master process is already dead (unclean hostagent exit: kill -9,
193 // OOM, host crash). That stale state is exactly what --reconnect is
194 // meant to recover from, so only surface the error when a master is
195 // still alive; otherwise drop the stale socket and continue so a
196 // fresh master can be established.
197 removed, rmErr := sshutil.RemoveStaleControlMaster(ctx, inst.Dir)
198 if rmErr != nil {
199 return rmErr
200 }
201 if !removed {
202 return err
203 }
204 logrus.WithError(err).Warnf("Removed stale ssh control socket for the instance %#q after the master had already exited", instName)
205 }
206 }
207
208 syncDirVal, err := flags.GetString("sync")
209 if err != nil {
210 return fmt.Errorf("failed to get sync flag: %w", err)
211 }
212 syncHostWorkdir := syncDirVal != ""
213 if syncHostWorkdir && len(inst.Config.Mounts) > 0 {
214 return errors.New("cannot use `--sync` when the instance has host mounts configured, start the instance with `--mount-none` to disable mounts")
215 }
216 // A wsl2 guest already reaches the host directory through the /mnt automount,
217 // so `--sync` cannot isolate it from host files the way it does elsewhere.
218 if syncHostWorkdir && inst.VMType == limatype.WSL2 {
219 return errors.New("cannot use `--sync` with a wsl2 instance, the host directory is already visible in the guest")
220 }
221
222 // When workDir is explicitly set, the shell MUST have workDir as the cwd, or exit with an error.
223 //
224 // changeDirCmd := "cd workDir || exit 1" if workDir != ""
225 // := "cd hostCurrentDir || cd hostHomeDir" if workDir == ""
226 var changeDirCmd string
227 // hostCurrentDirNative is the path as the host sees it. hostCurrentDir is the
228 // form the guest and the copy tool receive, which on Windows differs.
229 var hostCurrentDir, hostCurrentDirNative string
230 if syncDirVal != "" {
231 hostCurrentDirNative, err = filepath.Abs(syncDirVal)
232 } else {
233 hostCurrentDirNative, err = os.Getwd()
234 }
235 if err == nil {
236 hostCurrentDir = hostCurrentDirNative
237 if runtime.GOOS == "windows" {
238 hostCurrentDir, err = mountDirFromWindowsDir(ctx, inst, hostCurrentDirNative)
239 }
240 }
241
242 if err != nil {
243 // An empty hostCurrentDir would reach rsync as the toolchain root.
244 if syncHostWorkdir {
245 return fmt.Errorf("failed to determine the host directory to sync: %w", err)
246 }
247 changeDirCmd = "false"
248 logrus.WithError(err).Warn("failed to get the current directory")
249 }
250 if syncHostWorkdir {
251 if _, err := exec.LookPath(string(copytool.BackendRsync)); err != nil {
252 return fmt.Errorf("rsync is required for `--sync` but not found: %w", err)
253 }
254
255 // Measure the host's own path. The form hostCurrentDir carries on Windows
256 // adds one component (/c/...) or two (/cygdrive/c/...).
257 srcWdDepth := pathDepth(hostCurrentDirNative, runtime.GOOS == "windows")
258 if srcWdDepth < rsyncMinimumSrcDirDepth {
259 return fmt.Errorf("expected the depth of the host working directory (%#q) to be at least %d, only got %d (Hint: %s)",
260 hostCurrentDirNative, rsyncMinimumSrcDirDepth, srcWdDepth, "cd to a deeper directory")
261 }
262 // rsync acts on hostCurrentDir, so measure that too: cygpath can report
263 // success without writing a path, and an fstab can map a deep directory
264 // onto a shallow one. It is always POSIX form, even on Windows.
265 if dstWdDepth := pathDepth(hostCurrentDir, false); dstWdDepth < rsyncMinimumSrcDirDepth {
266 return fmt.Errorf("expected the depth of the converted host working directory (%#q) to be at least %d, only got %d",
267 hostCurrentDir, rsyncMinimumSrcDirDepth, dstWdDepth)
268 }
269 }
270
271 var destRsyncDir string
272 workDir, err := cmd.Flags().GetString("workdir")
273 if err != nil {
274 return err
275 }
276 if workDir != "" && syncHostWorkdir {
277 return errors.New("cannot use `--workdir` and `--sync` at the same time")
278 }
279 if syncHostWorkdir {
280 destRsyncDir = *inst.Config.User.Home + hostCurrentDir
281 }
282 hostHomeDir, err := os.UserHomeDir()
283 if err == nil && runtime.GOOS == "windows" {
284 hostHomeDir, err = mountDirFromWindowsDir(ctx, inst, hostHomeDir)
285 }
286 if err != nil {
287 logrus.WithError(err).Warn("failed to get the home directory")
288 hostHomeDir = ""
289 }
290
291 switch {
292 case workDir != "":
293 changeDirCmd = fmt.Sprintf("cd %s || exit 1", shellescape.Quote(workDir))
294 case mountsContainPath(inst.Config.Mounts, hostCurrentDir) || inst.VMType == limatype.WSL2:
295 changeDirCmd = fmt.Sprintf("cd %s", shellescape.Quote(hostCurrentDir))
296 if hostHomeDir != "" {
297 changeDirCmd = fmt.Sprintf("%s || cd %s", changeDirCmd, shellescape.Quote(hostHomeDir))
298 }
299 case syncHostWorkdir:
300 changeDirCmd = fmt.Sprintf("cd %s", shellescape.Quote(destRsyncDir))
301 case hostHomeDir != "" && mountsContainPath(inst.Config.Mounts, hostHomeDir):
302 changeDirCmd = fmt.Sprintf("cd %s", shellescape.Quote(hostHomeDir))
303 default:
304 logrus.Debug("the host home does not seem mounted, so the guest shell will have a different cwd")
305 }
306
307 if changeDirCmd == "" {
308 changeDirCmd = "false"
309 }
310 logrus.Debugf("changeDirCmd=%#q", changeDirCmd)
311
312 shell, err := cmd.Flags().GetString("shell")
313 if err != nil {
314 return err
315 }
316 if *inst.Config.OS == limatype.WINDOWS {
317 if shell == "" {
318 if inst.Config.User.Shell != nil {
319 shell = *inst.Config.User.Shell
320 } else {
321 shell = "cmd.exe"
322 }
323 }
324 if !limayaml.IsSupportedWindowsShell(shell) {
325 return fmt.Errorf("unsupported shell %#q for Windows guest, must be one of %v", shell, limayaml.SupportedWindowsShells)
326 }
327 } else if shell == "" {
328 if inst.Config.User.Shell != nil {
329 shell = shellescape.Quote(*inst.Config.User.Shell)
330 } else {
331 shell = `"$SHELL"`
332 }
333 } else {
334 shell = shellescape.Quote(shell)
335 }
336 // Handle environment variable propagation
337 var envPrefix string
338 preserveEnv, err := cmd.Flags().GetBool("preserve-env")
339 if err != nil {
340 return err
341 }
342 if preserveEnv {
343 filteredEnv := envutil.FilterEnvironment()
344 if len(filteredEnv) > 0 {
345 envPrefix = "env "
346 for _, envVar := range filteredEnv {
347 envPrefix += shellescape.Quote(envVar) + " "
348 }
349 }
350 }
351
352 // -l is known to be available in bash, zsh, and FreeBSD sh.
353 // Note that --login is not available in FreeBSD sh.
354 script := fmt.Sprintf("%s ; exec %s%s -l", changeDirCmd, envPrefix, shell)
355 if *inst.Config.OS == limatype.WINDOWS {
356 // TODO: When we implement a file mount for Windows guest, we should change directory here.
357 script = windowsQuoteShell(shell)
358 }
359 if len(args) > 1 {
360 quotedArgs := make([]string, len(args[1:]))
361 parsingEnv := true
362 for i, arg := range args[1:] {
363 if parsingEnv && isEnv(arg) {
364 quotedArgs[i] = quoteEnv(arg)
365 } else {
366 parsingEnv = false
367 quotedArgs[i] = shellescape.Quote(arg)
368 }
369 }
370 switch *inst.Config.OS {
371 case limatype.WINDOWS:
372 // cmd.exe uses "/c", while powershell.exe / pwsh.exe use "-Command".
373 flag := windowsShellCommandFlag(shell)
374 // On Windows, commands should be double-quoted.
375 script += fmt.Sprintf(` %s "%s"`, flag, strings.Join(quotedArgs, " "))
376 default:
377 script += fmt.Sprintf(
378 " -c %s",
379 shellescape.Quote(strings.Join(quotedArgs, " ")),
380 )
381 }
382 }
383
384 sshExe, err := sshutil.NewSSHExe()
385 if err != nil {
386 return err
387 }
388
389 sshOpts, err := sshutil.SSHOpts(
390 ctx,
391 sshExe,
392 inst.Dir,
393 *inst.Config.User.Name,
394 *inst.Config.SSH.LoadDotSSHPubKeys,
395 *inst.Config.SSH.ForwardAgent,
396 *inst.Config.SSH.ForwardX11,
397 *inst.Config.SSH.ForwardX11Trusted)
398 if err != nil {
399 return err
400 }
401 if runtime.GOOS == "windows" {
402 // Remove ControlMaster, ControlPath, and ControlPersist options,
403 // because Cygwin-based SSH clients do not support multiplexing when executing commands.
404 // References:
405 // https://inbox.sourceware.org/cygwin/[email protected]/T/
406 // https://stackoverflow.com/questions/20959792/is-ssh-controlmaster-with-cygwin-on-windows-actually-possible
407 // By removing these options:
408 // - Avoids execution failures when the control master is not yet available.
409 // - Prevents error messages such as:
410 // > mux_client_request_session: read from master failed: Connection reset by peer
411 // > ControlSocket ....sock already exists, disabling multiplexing
412 // Only remove these options when writing the SSH config file and executing `limactl shell`, since multiplexing seems to work with port forwarding.
413 sshOpts = sshutil.SSHOptsRemovingControlPath(sshOpts)
414 }
415 sshArgs := append([]string{}, sshExe.Args...)
416 sshArgs = append(sshArgs, sshutil.SSHArgsFromOpts(sshOpts)...)
417
418 var (
419 sshExecForRsync *exec.Cmd
420 rsync copytool.CopyTool
421 )
422 if syncHostWorkdir {
423 logrus.Infof("Syncing host current directory(%s) to guest instance...", hostCurrentDir)
424 sshExecForRsync = exec.CommandContext(ctx, sshExe.Exe, sshArgs...)
425
426 // Create the destination directory in the guest instance,
427 // we could have done this by using `--rsync-path` but it's more
428 // complex to quote properly.
429 if err := executeSSHForRsync(ctx, *sshExecForRsync, inst.SSHLocalPort, inst.SSHAddress, fmt.Sprintf("mkdir -p %s", shellescape.Quote(destRsyncDir))); err != nil {
430 return fmt.Errorf("failed to create the synced workdir in guest instance: %w", err)
431 }
432
433 // Quote the destination path for rsync versions before 3.2.4, where --protect-args is not the default
434 // and the remote shell would split paths containing spaces.
435 rsyncVer, err := rsyncVersion(ctx)
436 if err != nil {
437 return fmt.Errorf("failed to get rsync version: %w", err)
438 }
439 if rsyncVer.LessThan(*semver.New("3.2.4")) {
440 destRsyncDir = shellescape.Quote(destRsyncDir)
441 }
442
443 // The trailing slash makes rsync mirror the contents of the source directory into
444 // the destination directory, instead of copying the source directory into it like
445 // `limactl copy -r` does. Options.Recursive is deliberately left unset, so that
446 // the paths reach rsync as they are; `-a` already implies `-r`.
447 paths := []string{
448 hostCurrentDir + "/",
449 fmt.Sprintf("%s:%s/", inst.Name, destRsyncDir),
450 }
451 rsync, err = copytool.New(ctx, string(copytool.BackendRsync), paths, &copytool.Options{
452 Verbose: false,
453 AdditionalArgs: []string{
454 "--delete",
455 },
456 })
457 if err != nil {
458 return err
459 }
460 logrus.Debugf("using copy tool %#q", rsync.Name())
461
462 if err := rsyncDirectory(ctx, cmd, rsync, paths); err != nil {
463 return fmt.Errorf("failed to rsync to the guest %w", err)
464 }
465 logrus.Infof("Successfully synced host current directory to guest(%s) instance.", destRsyncDir)
466 }
467
468 if isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()) {
469 // required for showing the shell prompt: https://stackoverflow.com/a/626574
470 sshArgs = append(sshArgs, "-t")
471 }
472 if _, present := os.LookupEnv("COLORTERM"); present {
473 // SendEnv config is cumulative, with already existing options in ssh_config
474 sshArgs = append(sshArgs, "-o", "SendEnv=COLORTERM")
475 }
476 logLevel := "ERROR"
477 // For versions older than OpenSSH 8.9p, LogLevel=QUIET was needed to
478 // avoid the "Shared connection to 127.0.0.1 closed." message with -t.
479 olderSSH := sshutil.DetectOpenSSHVersion(ctx, sshExe).LessThan(*semver.New("8.9.0"))
480 if olderSSH {
481 logLevel = "QUIET"
482 }
483 sshArgs = append(sshArgs, []string{
484 "-o", fmt.Sprintf("LogLevel=%s", logLevel),
485 "-p", strconv.Itoa(inst.SSHLocalPort),
486 inst.SSHAddress,
487 "--",
488 script,
489 }...)
490 sshCmd := exec.CommandContext(ctx, sshExe.Exe, sshArgs...)
491 sshCmd.Stdin = os.Stdin
492 sshCmd.Stdout = os.Stdout
493 sshCmd.Stderr = os.Stderr
494 logrus.Debugf("executing ssh (may take a long)): %+v", sshCmd.Args)
495
496 // TODO: use syscall.Exec directly (results in losing tty?)
497 if err := sshCmd.Run(); err != nil {
498 return err
499 }
500
501 // Once the shell command finishes, rsync back the changes from guest workdir
502 // to the host and delete the guest synced workdir only if the user
503 // confirms the changes.
504 if syncHostWorkdir {
505 tty, err := flags.GetBool("tty")
506 if err != nil {
507 return err
508 }
509 return askUserForRsyncBack(ctx, cmd, inst, sshExecForRsync, hostCurrentDir, destRsyncDir, rsync, tty)
510 }
511 return nil
512}
513
514// windowsShellCommandFlag returns the flag used to pass a command string to the
515// given Windows shell. cmd.exe uses "/c", while powershell.exe and pwsh.exe use "-Command".
516// The shell may be an absolute path (e.g. `C:\Windows\System32\cmd.exe`);
517// only its basename is inspected.
518func windowsShellCommandFlag(shell string) string {
519 if i := strings.LastIndexAny(shell, `/\`); i >= 0 {
520 shell = shell[i+1:]
521 }
522 if strings.EqualFold(shell, "cmd.exe") {
523 return "/c"
524 }
525 return "-Command"
526}
527
528// windowsQuoteShell wraps an absolute Windows shell path in double quotes
529// when it contains whitespace, so the remote command line parses correctly.
530// Already-quoted values are returned unchanged.
531func windowsQuoteShell(shell string) string {
532 if strings.HasPrefix(shell, `"`) && strings.HasSuffix(shell, `"`) && len(shell) >= 2 {
533 return shell
534 }
535 if !strings.ContainsAny(shell, " \t") {
536 return shell
537 }
538 return `"` + shell + `"`
539}
540
541func askUserForRsyncBack(ctx context.Context, cmd *cobra.Command, inst *limatype.Instance, sshCmd *exec.Cmd, hostCurrentDir, destRsyncDir string, rsync copytool.CopyTool, tty bool) error {
542 remoteSource := fmt.Sprintf("%s:%s", inst.Name, destRsyncDir)
543 // See the comment on the trailing slash where the rsync tool is created.
544 remoteContents := remoteSource + "/"
545 clean := filepath.Clean(hostCurrentDir)
546 dirForCleanup := shellescape.Quote(filepath.Join(*inst.Config.User.Home, clean))
547 cleanupGuestWorkdir := false
548
549 rsyncBack := func() error {
550 paths := []string{
551 remoteContents,
552 hostCurrentDir,
553 }
554
555 if err := rsyncDirectory(ctx, cmd, rsync, paths); err != nil {
556 return fmt.Errorf("failed to sync back the changes from guest instance to host: %w", err)
557 }
558 logrus.Info("Successfully synced back the changes to host.")
559 cleanupGuestWorkdir = true
560 return nil
561 }
562
563 defer func() {
564 if !cleanupGuestWorkdir {
565 return
566 }
567 // Clean up the guest synced workdir
568 if err := executeSSHForRsync(ctx, *sshCmd, inst.SSHLocalPort, inst.SSHAddress, fmt.Sprintf("rm -rf %s", dirForCleanup)); err != nil {
569 logrus.WithError(err).Warn("Failed to clean up guest synced workdir")
570 }
571 }()
572
573 if !tty {
574 return rsyncBack()
575 }
576
577 rawOutput, stats, err := getRsyncStats(ctx, remoteSource, filepath.Dir(hostCurrentDir))
578 if err != nil {
579 logrus.WithError(err).Warn("failed to get rsync stats")
580 }
581 if stats != nil && stats.String() == "" {
582 logrus.Info("No changes detected")
583 cleanupGuestWorkdir = true
584 return nil
585 }
586 statsMsg := ""
587 if stats != nil {
588 if s := stats.String(); s != "" {
589 statsMsg = fmt.Sprintf(" (%s)", s)
590 }
591 }
592
593 message := fmt.Sprintf("⚠️ Accept the changes?%s", statsMsg)
594 options := []string{
595 "Yes",
596 "No",
597 "View the changed contents",
598 }
599
600 baseDir, err := os.MkdirTemp("", "lima-guest-synced-*")
601 if err != nil {
602 return fmt.Errorf("failed to create temporary directory: %w; preserving guest synced workdir at %s", err, destRsyncDir)
603 }
604 defer func() {
605 if err := os.RemoveAll(baseDir); err != nil {
606 logrus.WithError(err).Warnf("Failed to clean up temporary directory %s", baseDir)
607 }
608 }()
609 hostTmpDest := filepath.Join(baseDir, filepath.Base(hostCurrentDir))
610 err = os.MkdirAll(hostTmpDest, 0o755)
611 if err != nil {
612 return fmt.Errorf("failed to create temporary directory: %w; preserving guest synced workdir at %s", err, destRsyncDir)
613 }
614
615 rsyncToTempDir := false
616
617 for {
618 ans, err := uiutil.Select(message, options)
619 if err != nil {
620 return fmt.Errorf("failed to open TUI: %w; preserving guest synced workdir at %s", err, destRsyncDir)
621 }
622
623 switch ans {
624 case 0: // Yes
625 return rsyncBack()
626 case 1: // No
627 cleanupGuestWorkdir = true
628 logrus.Info("Skipping syncing back the changes to host.")
629 return nil
630 case 2: // View the changed contents
631 var diffCmd *exec.Cmd
632 if _, err := exec.LookPath("diff"); err != nil {
633 logrus.WithError(err).Warn("`diff` not found; showing rsync dry-run output only")
634 } else {
635 diffCmd = exec.CommandContext(ctx, "diff", "-ruN", "--color=always", hostCurrentDir, hostTmpDest)
636 if !rsyncToTempDir {
637 paths := []string{
638 remoteContents,
639 hostTmpDest,
640 }
641
642 if err := rsyncDirectory(ctx, cmd, rsync, paths); err != nil {
643 return fmt.Errorf("failed to sync back the changes from guest instance to host temporary directory: %w", err)
644 }
645 rsyncToTempDir = true
646 }
647 }
648
649 pagerArgs := pagerCommand()
650 lessCmd := exec.CommandContext(ctx, pagerArgs[0], pagerArgs[1:]...)
651
652 pipeIn, err := lessCmd.StdinPipe()
653 if err != nil {
654 return fmt.Errorf("failed to create pipe for less: %w", err)
655 }
656 if diffCmd != nil {
657 diffCmd.Stdout = pipeIn
658 }
659 lessCmd.Stdout = cmd.OutOrStdout()
660 lessCmd.Stderr = cmd.OutOrStderr()
661
662 if err := lessCmd.Start(); err != nil {
663 return fmt.Errorf("failed to start less: %w", err)
664 }
665
666 // Write rsync dry-run output first
667 if stats != nil {
668 rsyncHead := fmt.Sprintf("%s--- rsync dry-run statistics ---%s", colorGray, colorNone)
669 diffHead := fmt.Sprintf("%s--- detailed diff --- %s", colorGray, colorNone)
670 if diffCmd == nil {
671 diffHead = fmt.Sprintf("%s--- detailed diff unavailable (`diff` not found) --- %s", colorGray, colorNone)
672 }
673 combinedOutput := fmt.Sprintf(
674 "%s\n%s\n\n%s\n\n\n%s\n",
675 rsyncHead,
676 stats.String(),
677 rawOutput,
678 diffHead,
679 )
680
681 if _, err := fmt.Fprint(pipeIn, combinedOutput); err != nil {
682 _ = pipeIn.Close()
683 return fmt.Errorf("failed to write rsync stats to pager: %w", err)
684 }
685 }
686
687 if diffCmd != nil {
688 if err := diffCmd.Run(); err != nil {
689 // Command `diff` returns exit code 1 when files differ.
690 var exitErr *exec.ExitError
691 if errors.As(err, &exitErr) && exitErr.ExitCode() >= 2 {
692 _ = pipeIn.Close()
693 return fmt.Errorf("failed to run diff command: %w", err)
694 }
695 }
696 }
697
698 _ = pipeIn.Close()
699
700 if err := lessCmd.Wait(); err != nil {
701 return fmt.Errorf("failed to wait for less command: %w", err)
702 }
703 }
704 }
705}
706
707// pagerCommand returns the pager command and arguments to use for viewing colored diff output.
708func pagerCommand() []string {
709 pager := strings.TrimSpace(os.Getenv("PAGER"))
710 if pager == "" {
711 return []string{"less", "-R"}
712 }
713 args := strings.Fields(pager)
714 if filepath.Base(args[0]) != "less" {
715 return args
716 }
717 if lessHasRawColorFlag(args[1:]) {
718 return args
719 }
720 if lessHasRawColorFlag(strings.Fields(os.Getenv("LESS"))) {
721 return args
722 }
723 return append(args, "-R")
724}
725
726func lessHasRawColorFlag(flags []string) bool {
727 for _, f := range flags {
728 switch f {
729 case "-R", "-r", "--RAW-CONTROL-CHARS", "--raw-control-chars":
730 return true
731 }
732 if strings.HasPrefix(f, "-") && !strings.HasPrefix(f, "--") {
733 if strings.ContainsAny(f, "Rr") {
734 return true
735 }
736 }
737 }
738 return false
739}
740
741func mountsContainPath(mounts []limatype.Mount, path string) bool {
742 resolvedPath, err := filepath.EvalSymlinks(path)
743 if err != nil {
744 resolvedPath = path
745 }
746 for _, m := range mounts {
747 loc, err := localpathutil.Expand(m.Location)
748 if err != nil {
749 continue
750 }
751 resolvedLoc, err := filepath.EvalSymlinks(loc)
752 if err != nil {
753 resolvedLoc = loc
754 }
755 if resolvedPath == resolvedLoc ||
756 resolvedLoc == string(os.PathSeparator) || strings.HasPrefix(resolvedPath, resolvedLoc+string(os.PathSeparator)) {
757 return true
758 }
759 }
760 return false
761}
762
763func executeSSHForRsync(ctx context.Context, sshCmd exec.Cmd, sshLocalPort int, sshAddress, command string) error {
764 args := make([]string, len(sshCmd.Args), len(sshCmd.Args)+3)
765 copy(args, sshCmd.Args)
766 args = append(args, "-p", strconv.Itoa(sshLocalPort), sshAddress)
767
768 // Skip Args[0] (program name) to avoid duplication
769 sshRmCmd := exec.CommandContext(ctx, sshCmd.Path, append(args[1:], command)...)
770 if err := sshRmCmd.Run(); err != nil {
771 return err
772 }
773 return nil
774}
775
776// pathDepth counts the separator-delimited fields of an absolute path,
777// collapsing repeated separators. A trailing separator adds no field unless the
778// path is a bare root. Pass windows for a path in Windows form: elsewhere a
779// backslash is an ordinary filename character, and counting it as a separator
780// would score a directory just below the root deep enough to pass the guard.
781func pathDepth(path string, windows bool) int {
782 slashed := path
783 if windows {
784 slashed = strings.ReplaceAll(path, `\`, "/")
785 // An extended-length or device prefix spells a path the plain form also
786 // spells, so drop it before counting. The `UNC` token this leaves behind
787 // occupies the field the plain form's leading separator would.
788 if strings.HasPrefix(slashed, "//?/") || strings.HasPrefix(slashed, "//./") {
789 slashed = slashed[len("//?/"):]
790 }
791 }
792 // A separator run delimits one field. The two leading separators of a UNC
793 // path enclose one root, so counting both would clear the minimum depth for
794 // a share root.
795 for strings.Contains(slashed, "//") {
796 slashed = strings.ReplaceAll(slashed, "//", "/")
797 }
798 // filepath.Clean keeps the trailing separator of a root, so `\\server\share`
799 // and `\\server\share\` both reach here. Trim one that leaves a separator
800 // behind, which spares the bare roots "/" and `C:\`.
801 if trimmed := strings.TrimSuffix(slashed, "/"); strings.Contains(trimmed, "/") {
802 slashed = trimmed
803 }
804 return strings.Count(slashed, "/") + 1
805}
806
807func rsyncVersion(ctx context.Context) (*semver.Version, error) {
808 out, err := exec.CommandContext(ctx, string(copytool.BackendRsync), "--version").Output()
809 if err != nil {
810 return nil, err
811 }
812
813 // `rsync version 3.2.7 protocol version 31`
814 re := regexp.MustCompile(`version (\d+\.\d+\.\d+)`)
815 matches := re.FindSubmatch(out)
816 if len(matches) < 2 {
817 return nil, errors.New("failed to parse rsync version")
818 }
819 return semver.NewVersion(string(matches[1]))
820}
821
822// Syncs a directory from host to guest and vice-versa. It creates a directory in the guest's home directory and copies the contents of the host's
823// current working directory into it. The guest directory paths should be prefixed with `<InstanceName>:` followed by the path.
824func rsyncDirectory(ctx context.Context, cmd *cobra.Command, rsync copytool.CopyTool, paths []string) error {
825 rsyncCmd, err := rsync.Command(ctx, paths, nil)
826 if err != nil {
827 return err
828 }
829 rsyncCmd.Stdout = cmd.OutOrStdout()
830 rsyncCmd.Stderr = cmd.OutOrStderr()
831 logrus.Debugf("executing rsync: %+v", rsyncCmd.Args)
832 return rsyncCmd.Run()
833}
834
835func mountDirFromWindowsDir(ctx context.Context, inst *limatype.Instance, dir string) (string, error) {
836 if inst.VMType == limatype.WSL2 {
837 distroName := "lima-" + inst.Name
838 return fsutil.WindowsSubsystemPathForLinux(ctx, dir, distroName)
839 }
840 return fsutil.WindowsSubsystemPath(ctx, dir)
841}
842
843func shellBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
844 return bashCompleteInstanceNames(cmd)
845}
846
847func isEnv(arg string) bool {
848 return len(strings.Split(arg, "=")) > 1
849}
850
851func quoteEnv(arg string) string {
852 env := strings.SplitN(arg, "=", 2)
853 env[1] = shellescape.Quote(env[1])
854 return strings.Join(env, "=")
855}
856
857type rsyncStats struct {
858 Added int
859 Deleted int
860 Modified int
861 Metadata int
862}
863
864func (s *rsyncStats) String() string {
865 if s.Added == 0 && s.Deleted == 0 && s.Modified == 0 && s.Metadata == 0 {
866 return ""
867 }
868 return fmt.Sprintf("added: %d, deleted: %d, modified: %d, metadata: %d", s.Added, s.Deleted, s.Modified, s.Metadata)
869}
870
871func getRsyncStats(ctx context.Context, source, destination string) (string, *rsyncStats, error) {
872 paths := []string{source, destination}
873 rsync, err := copytool.New(ctx, string(copytool.BackendRsync), paths, &copytool.Options{
874 Verbose: true,
875 AdditionalArgs: []string{
876 "--dry-run",
877 "--itemize-changes",
878 "-ah",
879 "--delete",
880 },
881 })
882 if err != nil {
883 return "", nil, err
884 }
885
886 rsyncCmd, err := rsync.Command(ctx, paths, nil)
887 if err != nil {
888 return "", nil, err
889 }
890 logrus.Debugf("executing rsync for stats: %+v", rsyncCmd.Args)
891
892 out, err := rsyncCmd.Output()
893 if err != nil {
894 return "", nil, err
895 }
896 output := string(out)
897 return output, parseRsyncStats(output), nil
898}
899
900// parseRsyncStats parses the output of `rsync --itemize-changes` to extract file operation statistics.
901//
902// Rsync itemized format: YXcstpoguax path/to/file
903// Where Y=update type, X=file type, c=checksum status, and positions 3-10 are other attributes.
904//
905// Examples:
906//
907// >f+++++++++ file.txt → Added (new file received)
908// >f.st...... file.txt → Modified (existing file updated)
909// *deleting file.txt → Deleted
910//
911// Logic:
912//
913// - `*deleting`: Count as Deleted.
914// - Update type `<` (sent), `>` (received), or `c` (local change):
915// - If checksum is `+` (created): Count as Added.
916// - Otherwise: Count as Modified.
917//
918// - Update type `.` with non-`.` metadata attributes (positions 3-10):
919// - Count as Metadata.
920func parseRsyncStats(output string) *rsyncStats {
921 var s rsyncStats
922 for line := range strings.SplitSeq(output, "\n") {
923 if len(line) < 12 {
924 continue
925 }
926
927 if strings.HasPrefix(line, "*deleting") {
928 s.Deleted++
929 continue
930 }
931
932 updateType := line[0]
933 checksum := line[2]
934
935 if updateType == '<' || updateType == '>' || updateType == 'c' {
936 if checksum == '+' {
937 s.Added++
938 } else {
939 s.Modified++
940 }
941 continue
942 }
943
944 if updateType == '.' && hasMetadataDelta(line[2:11]) {
945 s.Metadata++
946 }
947 }
948 return &s
949}
950
951func hasMetadataDelta(attrs string) bool {
952 for _, ch := range attrs {
953 if ch != '.' {
954 return true
955 }
956 }
957 return false
958}