Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/imgutil/nativeimgutil/asifutil/asif_darwin.go
2662 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
package asifutil
5
6
import (
7
"context"
8
"fmt"
9
"os"
10
"os/exec"
11
"strings"
12
)
13
14
// NewAttachedASIF creates a new ASIF image file at the specified path with the given size
15
// and attaches it, returning the attached device path and an open file handle.
16
// The caller is responsible for detaching the ASIF image device when done.
17
func NewAttachedASIF(path string, size int64) (string, *os.File, error) {
18
createArgs := []string{"image", "create", "blank", "--fs", "none", "--format", "ASIF", "--size", fmt.Sprintf("%d", size), path}
19
if err := exec.CommandContext(context.Background(), "diskutil", createArgs...).Run(); err != nil {
20
return "", nil, fmt.Errorf("failed to create ASIF image %q: %w", path, err)
21
}
22
attachArgs := []string{"image", "attach", "--noMount", path}
23
out, err := exec.CommandContext(context.Background(), "diskutil", attachArgs...).Output()
24
if err != nil {
25
return "", nil, fmt.Errorf("failed to attach ASIF image %q: %w", path, err)
26
}
27
devicePath := strings.TrimSpace(string(out))
28
f, err := os.OpenFile(devicePath, os.O_RDWR, 0o644)
29
if err != nil {
30
_ = DetachASIF(devicePath)
31
return "", nil, fmt.Errorf("failed to open ASIF device %q: %w", devicePath, err)
32
}
33
return devicePath, f, err
34
}
35
36
// DetachASIF detaches the ASIF image device at the specified path.
37
func DetachASIF(devicePath string) error {
38
if output, err := exec.CommandContext(context.Background(), "hdiutil", "detach", devicePath).CombinedOutput(); err != nil {
39
return fmt.Errorf("failed to detach ASIF image %q: %w: %s", devicePath, err, output)
40
}
41
return nil
42
}
43
44
// ResizeASIF resizes the ASIF image at the specified path to the given size.
45
func ResizeASIF(path string, size int64) error {
46
resizeArgs := []string{"image", "resize", "--size", fmt.Sprintf("%d", size), path}
47
if output, err := exec.CommandContext(context.Background(), "diskutil", resizeArgs...).CombinedOutput(); err != nil {
48
return fmt.Errorf("failed to resize ASIF image %q: %w: %s", path, err, output)
49
}
50
return nil
51
}
52
53