Path: blob/master/pkg/imgutil/nativeimgutil/asifutil/asif_darwin.go
2662 views
// SPDX-FileCopyrightText: Copyright The Lima Authors1// SPDX-License-Identifier: Apache-2.023package asifutil45import (6"context"7"fmt"8"os"9"os/exec"10"strings"11)1213// NewAttachedASIF creates a new ASIF image file at the specified path with the given size14// and attaches it, returning the attached device path and an open file handle.15// The caller is responsible for detaching the ASIF image device when done.16func NewAttachedASIF(path string, size int64) (string, *os.File, error) {17createArgs := []string{"image", "create", "blank", "--fs", "none", "--format", "ASIF", "--size", fmt.Sprintf("%d", size), path}18if err := exec.CommandContext(context.Background(), "diskutil", createArgs...).Run(); err != nil {19return "", nil, fmt.Errorf("failed to create ASIF image %q: %w", path, err)20}21attachArgs := []string{"image", "attach", "--noMount", path}22out, err := exec.CommandContext(context.Background(), "diskutil", attachArgs...).Output()23if err != nil {24return "", nil, fmt.Errorf("failed to attach ASIF image %q: %w", path, err)25}26devicePath := strings.TrimSpace(string(out))27f, err := os.OpenFile(devicePath, os.O_RDWR, 0o644)28if err != nil {29_ = DetachASIF(devicePath)30return "", nil, fmt.Errorf("failed to open ASIF device %q: %w", devicePath, err)31}32return devicePath, f, err33}3435// DetachASIF detaches the ASIF image device at the specified path.36func DetachASIF(devicePath string) error {37if output, err := exec.CommandContext(context.Background(), "hdiutil", "detach", devicePath).CombinedOutput(); err != nil {38return fmt.Errorf("failed to detach ASIF image %q: %w: %s", devicePath, err, output)39}40return nil41}4243// ResizeASIF resizes the ASIF image at the specified path to the given size.44func ResizeASIF(path string, size int64) error {45resizeArgs := []string{"image", "resize", "--size", fmt.Sprintf("%d", size), path}46if output, err := exec.CommandContext(context.Background(), "diskutil", resizeArgs...).CombinedOutput(); err != nil {47return fmt.Errorf("failed to resize ASIF image %q: %w: %s", path, err, output)48}49return nil50}515253