跳到主要内容

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

浏览文件

bashref.go

272 行 · 7.3 KB历史下载
1// Package bashref gives the results of the bash implementation (0.2's
2// agent-vm.sh and lib/), for tests that compare the Go code with it. They
3// were recorded, before the bash version was removed, in each calling
4// package's testdata/bashref: a test's calls must stay the ones recorded.
5package bashref
6
7import (
8 "encoding/json"
9 "fmt"
10 "os"
11 "path/filepath"
12 "reflect"
13 "regexp"
14 "runtime"
15 "slices"
16 "strings"
17 "sync"
18 "testing"
19)
20
21// Root is the repository's root, where agent-vm.sh was.
22func Root() string {
23 _, file, _, _ := runtime.Caller(0)
24 return filepath.Join(filepath.Dir(file), "..", "..")
25}
26
27// Result of a bash function. Files holds the content of each file asked
28// for that exists afterwards.
29type Result struct {
30 Stdout, Stderr string
31 Code int
32 Files map[string]string `json:",omitempty"`
33}
34
35// Cmd is a bash snippet, run after agent-vm.sh is sourced, with Args as
36// "$@", from Dir (the repository's root when empty), with HOME in a
37// temporary folder and Env added. Files are read once it has run.
38type Cmd struct {
39 Dir string `json:",omitempty"`
40 Env []string `json:",omitempty"`
41 Stdin string `json:",omitempty"`
42 Snippet string
43 Args []string `json:",omitempty"`
44 Files []string `json:",omitempty"`
45}
46
47// Run runs fn with args (see Cmd).
48func Run(t testing.TB, dir string, env []string, fn string, args ...string) Result {
49 t.Helper()
50 return Exec(t, Cmd{Dir: dir, Env: env, Snippet: `"$@"`, Args: append([]string{fn}, args...)})
51}
52
53// Script runs snippet with args (see Cmd).
54func Script(t testing.TB, dir string, env []string, snippet string, args ...string) Result {
55 t.Helper()
56 return Exec(t, Cmd{Dir: dir, Env: env, Snippet: snippet, Args: args})
57}
58
59// Exec gives c's result as recorded. Skipped on Windows, never compared
60// there.
61func Exec(t testing.TB, c Cmd) Result {
62 t.Helper()
63 if runtime.GOOS == "windows" {
64 t.Skip("the bash reference is not compared on Windows")
65 }
66 if c.Dir == "" {
67 c.Dir = Root()
68 }
69 // Resolved, as the tests' own folders are: on macOS /var is a link to
70 // /private/var, and a second spelling of the same folder gets its
71 // recorded paths read back under the wrong one (see paths).
72 c.Env = append([]string{"HOME=" + evalOr(t.TempDir())}, c.Env...)
73 return replay(t, c)
74}
75
76// A recorded call, its paths made portable (see paths).
77type entry struct {
78 Cmd Cmd
79 Result Result
80}
81
82// The JSON of an entry: strings that are not UTF-8 (JSON would replace
83// their bytes) in base64.
84type entryJSON struct {
85 Dir, Stdin, Snippet str
86 Env, Args, Files []str
87 Stdout, Stderr str
88 Code int
89 Out map[string]str `json:",omitempty"`
90}
91
92type str string
93
94func (s *str) UnmarshalJSON(b []byte) error {
95 var raw map[string][]byte
96 if json.Unmarshal(b, &raw) == nil {
97 *s = str(raw["base64"])
98 return nil
99 }
100 return json.Unmarshal(b, (*string)(s))
101}
102
103func strs(in []str) []string {
104 var out []string
105 for _, s := range in {
106 out = append(out, string(s))
107 }
108 return out
109}
110
111func (e *entry) UnmarshalJSON(b []byte) error {
112 var j entryJSON
113 if err := json.Unmarshal(b, &j); err != nil {
114 return err
115 }
116 *e = entry{Cmd: Cmd{Dir: string(j.Dir), Stdin: string(j.Stdin), Snippet: string(j.Snippet),
117 Env: strs(j.Env), Args: strs(j.Args), Files: strs(j.Files)},
118 Result: Result{Stdout: string(j.Stdout), Stderr: string(j.Stderr), Code: j.Code}}
119 for k, v := range j.Out {
120 if e.Result.Files == nil {
121 e.Result.Files = map[string]string{}
122 }
123 e.Result.Files[k] = string(v)
124 }
125 return nil
126}
127
128var (
129 mu sync.Mutex
130 files = map[string]map[string][]entry{} // file, test name: calls
131 calls = map[testing.TB]int{}
132 // The package's folder: tests change theirs.
133 pkgDir, _ = os.Getwd()
134)
135
136// fileOf is where t's calls are kept: one file per top-level test.
137func fileOf(t testing.TB) string {
138 top, _, _ := strings.Cut(t.Name(), "/")
139 return filepath.Join(pkgDir, "testdata", "bashref", top+".json")
140}
141
142func load(path string) map[string][]entry {
143 if m, ok := files[path]; ok {
144 return m
145 }
146 m := map[string][]entry{}
147 if b, err := os.ReadFile(path); err == nil {
148 if err := json.Unmarshal(b, &m); err != nil {
149 panic(fmt.Sprintf("%s: %v", path, err))
150 }
151 }
152 files[path] = m
153 return m
154}
155
156func replay(t testing.TB, c Cmd) Result {
157 t.Helper()
158 mu.Lock()
159 path := fileOf(t)
160 recorded := load(path)[t.Name()]
161 n, seen := calls[t]
162 if !seen {
163 t.Cleanup(func() {
164 mu.Lock()
165 delete(calls, t)
166 mu.Unlock()
167 })
168 }
169 calls[t] = n + 1
170 mu.Unlock()
171 if n >= len(recorded) {
172 t.Fatalf("%s: no bash result recorded for call %d of %s", path, n+1, t.Name())
173 }
174 p := newPaths()
175 if now := p.cmd(c); !reflect.DeepEqual(now, recorded[n].Cmd) {
176 t.Fatalf("%s: call %d of %s is not the recorded one:\n now: %+v\n recorded: %+v", path, n+1, t.Name(), now, recorded[n].Cmd)
177 }
178 return p.result(recorded[n].Result)
179}
180
181// paths makes a call's paths portable: the repository is {ROOT}, a test's
182// temporary folder {Ti}, i in order of appearance in the call, read back as
183// the call spells it (macOS's /var or /private/var). The machine's PATH is
184// left out. The output was recorded with the call's folders only: others
185// under /tmp are not the test's (the guest's /tmp/...).
186type paths struct {
187 re *regexp.Regexp
188 dirs []string // the folder's name under the temporary root
189 spell []string // the root it has in the call
190}
191
192func newPaths() *paths {
193 p := &paths{}
194 var alts []string
195 for _, r := range []string{os.TempDir(), evalOr(os.TempDir())} {
196 if r = strings.TrimSuffix(r, "/"); !slices.Contains(alts, r) {
197 alts = append(alts, r)
198 }
199 }
200 slices.SortFunc(alts, func(a, b string) int { return len(b) - len(a) })
201 for i := range alts {
202 alts[i] = regexp.QuoteMeta(alts[i])
203 }
204 p.re = regexp.MustCompile(`(` + strings.Join(alts, "|") + `)/([^/\s'"=:,;\]\[{}]+)`)
205 return p
206}
207
208func evalOr(p string) string {
209 if r, err := filepath.EvalSymlinks(p); err == nil {
210 return r
211 }
212 return p
213}
214
215// out makes s portable.
216func (p *paths) out(s string) string {
217 s = strings.ReplaceAll(s, Root(), "{ROOT}")
218 return p.re.ReplaceAllStringFunc(s, func(m string) string {
219 sub := p.re.FindStringSubmatch(m)
220 i := slices.Index(p.dirs, sub[2])
221 if i < 0 {
222 i = len(p.dirs)
223 p.dirs = append(p.dirs, sub[2])
224 p.spell = append(p.spell, sub[1])
225 }
226 return fmt.Sprintf("{T%d}", i)
227 })
228}
229
230var placeholder = regexp.MustCompile(`\{T\d+\}`)
231
232// in is out undone, for this call's folders.
233func (p *paths) in(s string) string {
234 s = placeholder.ReplaceAllStringFunc(s, func(m string) string {
235 var i int
236 fmt.Sscanf(m, "{T%d}", &i)
237 if i >= len(p.dirs) {
238 return m
239 }
240 return p.spell[i] + "/" + p.dirs[i]
241 })
242 return strings.ReplaceAll(s, "{ROOT}", Root())
243}
244
245func (p *paths) cmd(c Cmd) Cmd {
246 o := Cmd{Dir: p.out(c.Dir), Stdin: p.out(c.Stdin), Snippet: p.out(c.Snippet)}
247 for _, e := range c.Env {
248 if k, v, ok := strings.Cut(e, "="); ok && k == "PATH" {
249 e = "PATH=" + strings.TrimSuffix(strings.TrimSuffix(v, os.Getenv("PATH")), ":")
250 }
251 o.Env = append(o.Env, p.out(e))
252 }
253 for _, a := range c.Args {
254 o.Args = append(o.Args, p.out(a))
255 }
256 for _, f := range c.Files {
257 o.Files = append(o.Files, p.out(f))
258 }
259 return o
260}
261
262// result is a recorded result, with this call's paths.
263func (p *paths) result(r Result) Result {
264 o := Result{Stdout: p.in(r.Stdout), Stderr: p.in(r.Stderr), Code: r.Code}
265 for k, v := range r.Files {
266 if o.Files == nil {
267 o.Files = map[string]string{}
268 }
269 o.Files[p.in(k)] = p.in(v)
270 }
271 return o
272}