跳到主要内容

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

浏览文件

asif_darwin.go

145 行 · 5.1 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package asifutil
5
6import (
7 "bytes"
8 "context"
9 "encoding/xml"
10 "errors"
11 "fmt"
12 "os"
13 "os/exec"
14 "strconv"
15 "strings"
16
17 "github.com/lima-vm/lima/v2/pkg/plist"
18)
19
20// NewASIF creates a new ASIF image file at the specified path with the given size.
21func NewASIF(path string, size int64) error {
22 createArgs := []string{"image", "create", "blank", "--fs", "none", "--format", "ASIF", "--size", strconv.FormatInt(size, 10), path}
23 if err := exec.CommandContext(context.Background(), "diskutil", createArgs...).Run(); err != nil {
24 return fmt.Errorf("failed to create ASIF image %#q: %w", path, err)
25 }
26 if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
27 if _, err2 := os.Stat(path + ".asif"); !errors.Is(err2, os.ErrNotExist) {
28 // diskutil may create the file with .asif suffix
29 if err3 := os.Rename(path+".asif", path); err3 != nil {
30 return fmt.Errorf("failed to rename ASIF image from %#q to %#q: %w", path+".asif", path, err3)
31 }
32 }
33 }
34 return nil
35}
36
37// NewAttachedASIF creates a new ASIF image file at the specified path with the given size
38// and attaches it, returning the attached device path and an open file handle.
39// The caller is responsible for detaching the ASIF image device when done.
40func NewAttachedASIF(path string, size int64) (string, *os.File, error) {
41 if err := NewASIF(path, size); err != nil {
42 return "", nil, err
43 }
44 attachArgs := []string{"image", "attach", "--noMount", path}
45 out, err := exec.CommandContext(context.Background(), "diskutil", attachArgs...).Output()
46 if err != nil {
47 return "", nil, fmt.Errorf("failed to attach ASIF image %#q: %w", path, err)
48 }
49 devicePath := strings.TrimSpace(string(out))
50 f, err := os.OpenFile(devicePath, os.O_RDWR, 0o644)
51 if err != nil {
52 _ = DetachASIF(devicePath)
53 return "", nil, fmt.Errorf("failed to open ASIF device %#q: %w", devicePath, err)
54 }
55 return devicePath, f, err
56}
57
58// DetachASIF detaches the ASIF image device at the specified path.
59func DetachASIF(devicePath string) error {
60 if output, err := exec.CommandContext(context.Background(), "hdiutil", "detach", devicePath).CombinedOutput(); err != nil {
61 return fmt.Errorf("failed to detach ASIF image %#q: %w: %s", devicePath, err, output)
62 }
63 return nil
64}
65
66// ResizeASIF resizes the ASIF image at the specified path to the given size.
67func ResizeASIF(path string, size int64) error {
68 resizeArgs := []string{"image", "resize", "--size", fmt.Sprintf("%d", size), path}
69 if output, err := exec.CommandContext(context.Background(), "diskutil", resizeArgs...).CombinedOutput(); err != nil {
70 return fmt.Errorf("failed to resize ASIF image %#q: %w: %s", path, err, output)
71 }
72 return nil
73}
74
75type AttachedDisk struct {
76 Disk string // whole disk device, e.g. "disk4" (GUID_partition_scheme)
77 Container string // APFS container partition, e.g. "disk4s2" (Apple_APFS)
78 Data string // data volume device, e.g. "disk7s5"
79}
80
81// parseDiskutilImageAttachOutput parses the output of `diskutil image attach -plist -nomount <disk>`
82// and returns the attached disk information.
83func parseDiskutilImageAttachOutput(xmlStr string) (*AttachedDisk, error) {
84 var p plist.Plist
85 if err := xml.Unmarshal([]byte(xmlStr), &p); err != nil {
86 return nil, fmt.Errorf("failed to unmarshal xml: %w", err)
87 }
88
89 if p.Value.Dict == nil {
90 return nil, errors.New("unexpected plist format: missing root dict")
91 }
92
93 seVal, ok := p.Value.Dict["system-entities"]
94 if !ok || len(seVal.Array) == 0 {
95 return nil, errors.New("unexpected plist format: missing system-entities array")
96 }
97
98 result := &AttachedDisk{}
99 for _, devEnt := range seVal.Array {
100 devDict := devEnt.Dict
101 if devDict == nil {
102 continue
103 }
104 devEntry, hasDevEntry := devDict["dev-entry"]
105 if !hasDevEntry || devEntry.String == nil || *devEntry.String == "" {
106 continue
107 }
108 if hint, ok := devDict["content-hint"]; ok && hint.String != nil {
109 switch *hint.String {
110 case "GUID_partition_scheme":
111 result.Disk = *devEntry.String
112 case "Apple_APFS":
113 result.Container = *devEntry.String
114 }
115 }
116 if role, ok := devDict["role"]; ok && role.String != nil && *role.String == "Data" {
117 result.Data = *devEntry.String
118 }
119 }
120 if result.Data == "" {
121 return nil, errors.New("no data device found in diskutil output")
122 }
123
124 return result, nil
125}
126
127var ErrResourceTemporarilyUnavailable = errors.New("resource temporarily unavailable")
128
129// DiskutilImageAttachNoMount executes `diskutil image attach -plist -nomount <disk>`.
130func DiskutilImageAttachNoMount(ctx context.Context, disk string) (*AttachedDisk, error) {
131 cmd := exec.CommandContext(ctx, "diskutil", "image", "attach", "-plist", "-nomount", disk)
132 // Enforce English output for parsing stderr
133 cmd.Env = append(os.Environ(), "LANG=C", "LC_ALL=C")
134 var stdout, stderr bytes.Buffer
135 cmd.Stdout = &stdout
136 cmd.Stderr = &stderr
137 if err := cmd.Run(); err != nil {
138 errToWrap := err
139 if strings.Contains(stderr.String(), "Resource temporarily unavailable") {
140 errToWrap = ErrResourceTemporarilyUnavailable
141 }
142 return nil, fmt.Errorf("failed to execute %v: %w (stderr: %#q)", cmd.Args, errToWrap, stderr.String())
143 }
144 return parseDiskutilImageAttachOutput(stdout.String())
145}