Skip to content

Commit 875ddf4

Browse files
committed
add limactl disk add command
Signed-off-by: Songpon Srisawai <songpon.ssw@gmail.com>
1 parent 6a2fd5a commit 875ddf4

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

cmd/limactl/disk.go

+64
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ import (
1010
"io/fs"
1111
"os"
1212
"text/tabwriter"
13+
"path/filepath"
1314

1415
"github.com/docker/go-units"
16+
"github.com/lima-vm/go-qcow2reader"
1517
"github.com/lima-vm/lima/pkg/nativeimgutil"
1618
"github.com/lima-vm/lima/pkg/qemu"
1719
"github.com/lima-vm/lima/pkg/store"
@@ -44,6 +46,7 @@ func newDiskCommand() *cobra.Command {
4446
newDiskDeleteCommand(),
4547
newDiskUnlockCommand(),
4648
newDiskResizeCommand(),
49+
newDiskAddCommand(),
4750
)
4851
return diskCommand
4952
}
@@ -418,3 +421,64 @@ func diskResizeAction(cmd *cobra.Command, args []string) error {
418421
func diskBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
419422
return bashCompleteDiskNames(cmd)
420423
}
424+
425+
// func newDiskRegisterCommand()
426+
func newDiskAddCommand() *cobra.Command {
427+
diskAddCommand := &cobra.Command{
428+
Use: "add existing DISK to Lima",
429+
Example: `
430+
Add a disk:
431+
$ limactl disk add DISK`,
432+
Short: "Add existing to Lima",
433+
Args: WrapArgsError(cobra.ExactArgs(1)),
434+
RunE: diskAddAction,
435+
ValidArgsFunction: diskBashComplete,
436+
}
437+
438+
diskAddCommand.Flags().String("filename", "", "Path to disk image")
439+
_ = diskAddCommand.MarkFlagRequired("filename")
440+
return diskAddCommand
441+
}
442+
443+
func diskAddAction(cmd *cobra.Command, args []string) error {
444+
fName, err := cmd.Flags().GetString("filename")
445+
if err != nil {
446+
return err
447+
}
448+
449+
f, err := os.Open(fName)
450+
defer f.Close()
451+
if err != nil {
452+
return err
453+
}
454+
455+
img, err := qcow2reader.Open(f)
456+
if err != nil {
457+
return err
458+
}
459+
460+
diskName := args[0]
461+
// diskName := filepath.Base(fName)
462+
// diskName = strings.TrimSuffix(diskName, filepath.Ext(diskName))
463+
diskSize := img.Size()
464+
format := img.Type()
465+
466+
switch format {
467+
case "qcow2", "raw":
468+
default:
469+
return fmt.Errorf(`disk format %q not supported, use "qcow2" or "raw" instead`, format)
470+
}
471+
472+
diskDir, err := store.DiskDir(diskName)
473+
if err := os.MkdirAll(diskDir, 0755); err != nil {
474+
return err
475+
}
476+
477+
if err := os.Symlink(fName, filepath.Join(diskDir, "datadisk")); err != nil {
478+
return err
479+
}
480+
481+
logrus.Infof("Add %s with size %s to Lima", diskName, units.BytesSize(float64(diskSize)))
482+
483+
return nil
484+
}

0 commit comments

Comments
 (0)