-
Notifications
You must be signed in to change notification settings - Fork 612
/
imgutil.go
61 lines (56 loc) · 1.47 KB
/
imgutil.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package imgutil
import (
"bytes"
"encoding/json"
"fmt"
"os/exec"
"path/filepath"
"strings"
)
// Info corresponds to the output of `qemu-img info --output=json FILE`
type Info struct {
Format string `json:"format,omitempty"` // since QEMU 1.3
VSize int64 `json:"virtual-size,omitempty"`
}
func QCOWToRaw(source string, dest string) error {
var stdout, stderr bytes.Buffer
cmd := exec.Command("qemu-img", "convert", source, dest)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to run %v: stdout=%q, stderr=%q: %w",
cmd.Args, stdout.String(), stderr.String(), err)
}
return nil
}
func GetInfo(f string) (*Info, error) {
var stdout, stderr bytes.Buffer
cmd := exec.Command("qemu-img", "info", "--output=json", "--force-share", f)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("failed to run %v: stdout=%q, stderr=%q: %w",
cmd.Args, stdout.String(), stderr.String(), err)
}
var imgInfo Info
if err := json.Unmarshal(stdout.Bytes(), &imgInfo); err != nil {
return nil, err
}
return &imgInfo, nil
}
func DetectFormat(f string) (string, error) {
switch ext := strings.ToLower(filepath.Ext(f)); ext {
case ".qcow2":
return "qcow2", nil
case ".raw":
return "raw", nil
}
imgInfo, err := GetInfo(f)
if err != nil {
return "", err
}
if imgInfo.Format == "" {
return "", fmt.Errorf("failed to detect format of %q", f)
}
return imgInfo.Format, nil
}