Skip to content

Commit 69bcf9b

Browse files
committed
pkg/qemu: detect basedisk format
Follow-up to PR 174 `qemu-img 6.1.0 no longer supports using -b without -F` Signed-off-by: Akihiro Suda <[email protected]>
1 parent a2045a1 commit 69bcf9b

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

pkg/qemu/imgutil/imgutil.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package imgutil
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"fmt"
7+
"os/exec"
8+
"path/filepath"
9+
"strings"
10+
)
11+
12+
// Info corresponds to the output of `qemu-img info --output=json FILE`
13+
type Info struct {
14+
Format string `json:"format,omitempty"` // since QEMU 1.3
15+
}
16+
17+
func GetInfo(f string) (*Info, error) {
18+
var stdout, stderr bytes.Buffer
19+
cmd := exec.Command("qemu-img", "info", "--output=json", f)
20+
cmd.Stdout = &stdout
21+
cmd.Stderr = &stderr
22+
if err := cmd.Run(); err != nil {
23+
return nil, fmt.Errorf("failed to run %v: stdout=%q, stderr=%q: %w",
24+
cmd.Args, stdout.String(), stderr.String(), err)
25+
}
26+
var imgInfo Info
27+
if err := json.Unmarshal(stdout.Bytes(), &imgInfo); err != nil {
28+
return nil, err
29+
}
30+
return &imgInfo, nil
31+
}
32+
33+
func DetectFormat(f string) (string, error) {
34+
switch ext := strings.ToLower(filepath.Ext(f)); ext {
35+
case ".qcow2":
36+
return "qcow2", nil
37+
case ".raw":
38+
return "raw", nil
39+
}
40+
imgInfo, err := GetInfo(f)
41+
if err != nil {
42+
return "", err
43+
}
44+
if imgInfo.Format == "" {
45+
return "", fmt.Errorf("failed to detect format of %q", f)
46+
}
47+
return imgInfo.Format, nil
48+
}

pkg/qemu/qemu.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"github.com/lima-vm/lima/pkg/downloader"
1515
"github.com/lima-vm/lima/pkg/iso9660util"
1616
"github.com/lima-vm/lima/pkg/limayaml"
17+
"github.com/lima-vm/lima/pkg/qemu/imgutil"
1718
"github.com/lima-vm/lima/pkg/qemu/qemuconst"
1819
"github.com/lima-vm/lima/pkg/store/filenames"
1920
"github.com/mattn/go-shellwords"
@@ -78,7 +79,11 @@ func EnsureDisk(cfg Config) error {
7879
}
7980
args := []string{"create", "-f", "qcow2"}
8081
if !isBaseDiskISO {
81-
args = append(args, "-F", "qcow2", "-b", baseDisk)
82+
baseDiskFormat, err := imgutil.DetectFormat(baseDisk)
83+
if err != nil {
84+
return err
85+
}
86+
args = append(args, "-F", baseDiskFormat, "-b", baseDisk)
8287
}
8388
args = append(args, diffDisk, strconv.Itoa(int(diskSize)))
8489
cmd := exec.Command("qemu-img", args...)

0 commit comments

Comments
 (0)