@@ -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+ newDiskImportCommand (),
4751 )
4852 return diskCommand
4953}
@@ -418,3 +422,63 @@ func diskResizeAction(cmd *cobra.Command, args []string) error {
418422func diskBashComplete (cmd * cobra.Command , _ []string , _ string ) ([]string , cobra.ShellCompDirective ) {
419423 return bashCompleteDiskNames (cmd )
420424}
425+
426+ func newDiskImportCommand () * cobra.Command {
427+ diskImportCommand := & cobra.Command {
428+ Use : "import DISK FILE" ,
429+ Example : `
430+ Import a disk:
431+ $ limactl disk import DISK DISKPATH
432+ ` ,
433+ Short : "Import an existing disk to Lima" ,
434+ Args : WrapArgsError (cobra .ExactArgs (2 )),
435+ RunE : diskImportAction ,
436+ }
437+ return diskImportCommand
438+ }
439+
440+ func diskImportAction (_ * cobra.Command , args []string ) error {
441+ diskName := args [0 ]
442+ fName := args [1 ]
443+
444+ diskDir , err := store .DiskDir (diskName )
445+ if err != nil {
446+ return err
447+ }
448+
449+ if _ , err := os .Stat (diskDir ); ! errors .Is (err , fs .ErrNotExist ) {
450+ return fmt .Errorf ("disk %q already exists (%q)" , diskName , diskDir )
451+ }
452+
453+ f , err := os .Open (fName )
454+ if err != nil {
455+ return err
456+ }
457+ defer f .Close ()
458+
459+ img , err := qcow2reader .Open (f )
460+ if err != nil {
461+ return err
462+ }
463+
464+ diskSize := img .Size ()
465+ format := img .Type ()
466+
467+ switch format {
468+ case "qcow2" , "raw" :
469+ default :
470+ return fmt .Errorf (`disk format %q not supported, use "qcow2" or "raw" instead` , format )
471+ }
472+
473+ if err := os .MkdirAll (diskDir , 0o755 ); err != nil {
474+ return err
475+ }
476+
477+ if err := contfs .CopyFile (filepath .Join (diskDir , "datadisk" ), fName ); err != nil {
478+ return nil
479+ }
480+
481+ logrus .Infof ("Imported %s with size %s" , diskName , units .BytesSize (float64 (diskSize )))
482+
483+ return nil
484+ }
0 commit comments