Skip to content

Commit 14df36b

Browse files
committed
support: limactl disk add command
Signed-off-by: Songpon Srisawai <[email protected]>
1 parent 6a2fd5a commit 14df36b

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

cmd/limactl/disk.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,12 @@ import (
99
"fmt"
1010
"io/fs"
1111
"os"
12+
"path/filepath"
1213
"text/tabwriter"
1314

15+
contfs "github.com/containerd/continuity/fs"
1416
"github.com/docker/go-units"
17+
"github.com/lima-vm/go-qcow2reader"
1518
"github.com/lima-vm/lima/pkg/nativeimgutil"
1619
"github.com/lima-vm/lima/pkg/qemu"
1720
"github.com/lima-vm/lima/pkg/store"
@@ -44,6 +47,7 @@ func newDiskCommand() *cobra.Command {
4447
newDiskDeleteCommand(),
4548
newDiskUnlockCommand(),
4649
newDiskResizeCommand(),
50+
newDiskAddCommand(),
4751
)
4852
return diskCommand
4953
}
@@ -418,3 +422,64 @@ func diskResizeAction(cmd *cobra.Command, args []string) error {
418422
func diskBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
419423
return bashCompleteDiskNames(cmd)
420424
}
425+
426+
func newDiskAddCommand() *cobra.Command {
427+
diskAddCommand := &cobra.Command{
428+
Use: "add DISK DISKPATH",
429+
Example: `
430+
Add a disk:
431+
$ limactl disk add DISK DISKPATH
432+
`,
433+
Short: "Add an existing disk to Lima",
434+
Aliases: []string{"import"},
435+
Args: WrapArgsError(cobra.ExactArgs(2)),
436+
RunE: diskAddAction,
437+
}
438+
return diskAddCommand
439+
}
440+
441+
func diskAddAction(_ *cobra.Command, args []string) error {
442+
diskName := args[0]
443+
fName := args[1]
444+
445+
diskDir, err := store.DiskDir(diskName)
446+
if err != nil {
447+
return err
448+
}
449+
450+
if _, err := os.Stat(diskDir); !errors.Is(err, fs.ErrNotExist) {
451+
return fmt.Errorf("disk %q already exists (%q)", diskName, diskDir)
452+
}
453+
454+
f, err := os.Open(fName)
455+
if err != nil {
456+
return err
457+
}
458+
defer f.Close()
459+
460+
img, err := qcow2reader.Open(f)
461+
if err != nil {
462+
return err
463+
}
464+
465+
diskSize := img.Size()
466+
format := img.Type()
467+
468+
switch format {
469+
case "qcow2", "raw":
470+
default:
471+
return fmt.Errorf(`disk format %q not supported, use "qcow2" or "raw" instead`, format)
472+
}
473+
474+
if err := os.MkdirAll(diskDir, 0o755); err != nil {
475+
return err
476+
}
477+
478+
if err := contfs.CopyFile(filepath.Join(diskDir, "datadisk"), fName); err != nil {
479+
return nil
480+
}
481+
482+
logrus.Infof("Added %s with size %s", diskName, units.BytesSize(float64(diskSize)))
483+
484+
return nil
485+
}

0 commit comments

Comments
 (0)