跳到主要内容

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

浏览文件

rsync.go

292 行 · 8.8 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package copytool
5
6import (
7 "context"
8 "errors"
9 "fmt"
10 "os"
11 "os/exec"
12 "regexp"
13 "strings"
14
15 "al.essio.dev/pkg/shellescape"
16 "github.com/sirupsen/logrus"
17
18 "github.com/lima-vm/lima/v2/pkg/limatype"
19 "github.com/lima-vm/lima/v2/pkg/sshutil"
20)
21
22type rsyncTool struct {
23 toolPath string
24 Options *Options
25}
26
27func newRsyncTool(opts *Options) (*rsyncTool, error) {
28 toolPath, err := exec.LookPath("rsync")
29 if err != nil {
30 return nil, fmt.Errorf("rsync not found on host: %w", err)
31 }
32 return &rsyncTool{toolPath: toolPath, Options: opts}, nil
33}
34
35func (t *rsyncTool) Name() string {
36 return t.toolPath
37}
38
39func (t *rsyncTool) IsAvailableOnGuest(ctx context.Context, paths []string) bool {
40 copyPaths, err := parseCopyPaths(ctx, paths)
41 if err != nil {
42 // New() has already reported this to the user.
43 logrus.Debugf("failed to parse copy paths for rsync availability check: %v", err)
44 return false
45 }
46 instances := make(map[string]*limatype.Instance)
47
48 for _, cp := range copyPaths {
49 if cp.IsRemote {
50 instances[cp.InstanceName] = cp.Instance
51 }
52 }
53
54 for instName, inst := range instances {
55 if !checkRsyncOnGuest(ctx, inst) {
56 logrus.Debugf("rsync not available on instance %#q", instName)
57 return false
58 }
59 }
60
61 return true
62}
63
64func checkRsyncOnGuest(ctx context.Context, inst *limatype.Instance) bool {
65 checkCmd, err := sshCommandOnGuest(ctx, inst, "command -v rsync >/dev/null 2>&1")
66 if err != nil {
67 logrus.Debugf("failed to prepare the SSH command for the rsync check: %v", err)
68 return false
69 }
70 return checkCmd.Run() == nil
71}
72
73// sshCommandOnGuest returns a command that executes script with the shell of the guest.
74func sshCommandOnGuest(ctx context.Context, inst *limatype.Instance, script string) (*exec.Cmd, error) {
75 sshExe, err := sshutil.NewSSHExe()
76 if err != nil {
77 return nil, err
78 }
79 sshOpts, err := sshutil.SSHOpts(ctx, sshExe, inst.Dir, *inst.Config.User.Name, false, false, false, false)
80 if err != nil {
81 return nil, err
82 }
83
84 sshArgs := append([]string{}, sshExe.Args...)
85 sshArgs = append(sshArgs, sshutil.SSHArgsFromOpts(sshOpts)...)
86 sshArgs = append(sshArgs,
87 "-p", fmt.Sprintf("%d", inst.SSHLocalPort),
88 *inst.Config.User.Name+"@"+inst.SSHAddress,
89 script,
90 )
91 return exec.CommandContext(ctx, sshExe.Exe, sshArgs...), nil
92}
93
94func (t *rsyncTool) Command(ctx context.Context, paths []string, opts *Options) (*exec.Cmd, error) {
95 copyPaths, err := parseCopyPaths(ctx, paths)
96 if err != nil {
97 return nil, err
98 }
99
100 effectiveOpts := t.Options
101 if opts != nil {
102 effectiveOpts = opts
103 }
104
105 rsyncFlags := []string{"-a"}
106
107 if effectiveOpts.Verbose {
108 rsyncFlags = append(rsyncFlags, "-v", "--progress")
109 } else {
110 rsyncFlags = append(rsyncFlags, "-q")
111 }
112
113 if effectiveOpts.Recursive {
114 rsyncFlags = append(rsyncFlags, "-r")
115 }
116
117 if effectiveOpts.AdditionalArgs != nil {
118 rsyncFlags = append(rsyncFlags, effectiveOpts.AdditionalArgs...)
119 }
120
121 rsyncArgs := make([]string, 0, len(rsyncFlags)+len(copyPaths))
122 rsyncArgs = append(rsyncArgs, rsyncFlags...)
123
124 var sshCmd string
125 var remoteInstance *limatype.Instance
126
127 for _, cp := range copyPaths {
128 if cp.IsRemote {
129 if remoteInstance == nil {
130 remoteInstance = cp.Instance
131 sshExe, err := sshutil.NewSSHExe()
132 if err != nil {
133 return nil, err
134 }
135 sshOpts, err := sshutil.SSHOpts(ctx, sshExe, cp.Instance.Dir, *cp.Instance.Config.User.Name, false, false, false, false)
136 if err != nil {
137 return nil, err
138 }
139
140 sshArgs := []string{sshExe.Exe}
141 sshArgs = append(sshArgs, sshExe.Args...)
142 sshArgs = append(sshArgs, sshutil.SSHArgsFromOpts(sshOpts)...)
143 sshArgs = append(sshArgs, "-p", fmt.Sprintf("%d", cp.Instance.SSHLocalPort))
144
145 quotedSSHArgs := make([]string, len(sshArgs))
146 for i, arg := range sshArgs {
147 quotedSSHArgs[i] = shellescape.Quote(arg)
148 }
149 sshCmd = strings.Join(quotedSSHArgs, " ")
150 }
151 }
152 }
153
154 if sshCmd != "" {
155 rsyncArgs = append(rsyncArgs, "-e", sshCmd)
156 }
157
158 // Adjust the trailing slashes of the paths so that a recursive copy behaves like
159 // `cp -r` and `scp -r`, which was the original implementation of `limactl copy -r`.
160 // https://github.com/lima-vm/lima/issues/4468
161 // https://github.com/lima-vm/lima/issues/5500
162 if effectiveOpts.Recursive && len(copyPaths) > 1 {
163 if err := adjustTrailingSlashes(ctx, paths, copyPaths); err != nil {
164 return nil, err
165 }
166 }
167
168 // End option parsing so a path starting with a dash is treated as a path,
169 // not as an rsync option. scp.go does the same.
170 rsyncArgs = append(rsyncArgs, "--")
171
172 for _, cp := range copyPaths {
173 if cp.IsRemote {
174 rsyncArgs = append(rsyncArgs, fmt.Sprintf("%s:%s", *cp.Instance.Config.User.Name+"@"+cp.Instance.SSHAddress, cp.Path))
175 } else {
176 rsyncArgs = append(rsyncArgs, cp.Path)
177 }
178 }
179
180 return exec.CommandContext(ctx, t.toolPath, rsyncArgs...), nil
181}
182
183// adjustTrailingSlashes rewrites the source paths of a recursive copy so that rsync
184// behaves like `cp -r` and `scp -r`: the source directory is copied into the destination
185// when the destination is an existing directory (DST/SRC), and becomes the destination
186// when it does not exist yet. rsync decides this from a trailing slash on the source
187// instead: "SRC/" copies the *contents* of SRC, while "SRC" always creates DST/SRC.
188//
189// paths are the original command line arguments, corresponding to copyPaths by index.
190// The last one is the destination; the preceding ones are the sources.
191func adjustTrailingSlashes(ctx context.Context, paths []string, copyPaths []*Path) error {
192 last := len(copyPaths) - 1
193 srcs, dst := copyPaths[:last], copyPaths[last]
194
195 // A trailing slash on a source is not significant for `limactl copy`.
196 for _, src := range srcs {
197 src.Path = trimTrailingSlashes(src.Path)
198 }
199
200 // Multiple sources always require the destination to be a directory.
201 if len(srcs) != 1 {
202 return nil
203 }
204 // Otherwise rsync has to be told to copy the contents of the source when the
205 // destination is not an existing directory, so that the destination becomes a copy of
206 // the source directory rather than its parent.
207 dstIsDir, err := isDir(ctx, paths[last], dst)
208 if err != nil || dstIsDir {
209 return err
210 }
211 // A source that is not a directory is already copied by name, and a trailing slash
212 // would just make rsync fail on it.
213 srcIsDir, err := isDir(ctx, paths[0], srcs[0])
214 if err != nil {
215 return err
216 }
217 if srcIsDir {
218 srcs[0].Path += "/"
219 }
220 return nil
221}
222
223// trimTrailingSlashes removes the trailing slashes from path, unless the path is made of
224// slashes only (e.g. "/"), as trimming those would turn it into an empty path.
225func trimTrailingSlashes(path string) string {
226 if trimmed := strings.TrimRight(path, "/"); trimmed != "" {
227 return trimmed
228 }
229 return path
230}
231
232// isDir reports whether the path of cp is an existing directory. A path that does not
233// exist is not an error, but failing to determine the answer is: guessing it would copy
234// the files to the wrong place.
235//
236// rawPath is the corresponding command line argument. It is used instead of cp.Path for
237// local paths, because cp.Path may have been rewritten to a subsystem path (e.g.
238// "/cygdrive/c/...") that only the SSH executable understands on Windows hosts.
239func isDir(ctx context.Context, rawPath string, cp *Path) (bool, error) {
240 if !cp.IsRemote {
241 st, err := os.Stat(rawPath)
242 if errors.Is(err, os.ErrNotExist) {
243 return false, nil
244 }
245 if err != nil {
246 return false, err
247 }
248 return st.IsDir(), nil
249 }
250 path := cp.Path
251 if path == "" {
252 // `limactl copy foo inst:` copies into the login directory of the guest.
253 path = "."
254 }
255 cmd, err := sshCommandOnGuest(ctx, cp.Instance, "test -d "+quoteRemotePath(path))
256 if err != nil {
257 return false, err
258 }
259 // `test` writes nothing, so Output() only serves to capture the stderr of SSH.
260 if _, err = cmd.Output(); err == nil {
261 return true, nil
262 }
263 // `test` exits with 1 when the path is not a directory. Any other status means that
264 // the answer is unknown; SSH itself exits with 255 when it fails to connect.
265 if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {
266 if exitErr.ExitCode() == 1 {
267 return false, nil
268 }
269 if stderr := strings.TrimSpace(string(exitErr.Stderr)); stderr != "" {
270 err = fmt.Errorf("%w (%s)", err, stderr)
271 }
272 }
273 return false, fmt.Errorf("failed to check whether %#q is a directory on instance %#q: %w",
274 path, cp.InstanceName, err)
275}
276
277// tildePrefixRegexp matches a "~" or "~user" prefix that the shell of the guest expands.
278var tildePrefixRegexp = regexp.MustCompile(`^~[A-Za-z0-9._-]*$`)
279
280// quoteRemotePath quotes path for the shell of the guest, keeping a leading "~" or
281// "~user" unquoted so that the shell still expands it, like it does for the paths that
282// rsync passes to the guest.
283func quoteRemotePath(path string) string {
284 prefix, rest, found := strings.Cut(path, "/")
285 if !tildePrefixRegexp.MatchString(prefix) {
286 return shellescape.Quote(path)
287 }
288 if !found {
289 return prefix
290 }
291 return prefix + "/" + shellescape.Quote(rest)
292}