@@ -9,12 +9,16 @@ import (
9
9
"fmt"
10
10
"io/fs"
11
11
"os"
12
+ "path/filepath"
12
13
"text/tabwriter"
13
14
15
+ contfs "github.com/containerd/continuity/fs"
14
16
"github.com/docker/go-units"
17
+ "github.com/lima-vm/go-qcow2reader"
15
18
"github.com/lima-vm/lima/pkg/nativeimgutil"
16
19
"github.com/lima-vm/lima/pkg/qemu"
17
20
"github.com/lima-vm/lima/pkg/store"
21
+ "github.com/lima-vm/lima/pkg/store/filenames"
18
22
"github.com/sirupsen/logrus"
19
23
"github.com/spf13/cobra"
20
24
)
@@ -44,6 +48,7 @@ func newDiskCommand() *cobra.Command {
44
48
newDiskDeleteCommand (),
45
49
newDiskUnlockCommand (),
46
50
newDiskResizeCommand (),
51
+ newDiskImportCommand (),
47
52
)
48
53
return diskCommand
49
54
}
@@ -418,3 +423,64 @@ func diskResizeAction(cmd *cobra.Command, args []string) error {
418
423
func diskBashComplete (cmd * cobra.Command , _ []string , _ string ) ([]string , cobra.ShellCompDirective ) {
419
424
return bashCompleteDiskNames (cmd )
420
425
}
426
+
427
+ func newDiskImportCommand () * cobra.Command {
428
+ diskImportCommand := & cobra.Command {
429
+ Use : "import DISK FILE" ,
430
+ Example : `
431
+ Import a disk:
432
+ $ limactl disk import DISK DISKPATH
433
+ ` ,
434
+ Short : "Import an existing disk to Lima" ,
435
+ Args : WrapArgsError (cobra .ExactArgs (2 )),
436
+ RunE : diskImportAction ,
437
+ ValidArgsFunction : diskBashComplete ,
438
+ }
439
+ return diskImportCommand
440
+ }
441
+
442
+ func diskImportAction (_ * cobra.Command , args []string ) error {
443
+ diskName := args [0 ]
444
+ fName := args [1 ]
445
+
446
+ diskDir , err := store .DiskDir (diskName )
447
+ if err != nil {
448
+ return err
449
+ }
450
+
451
+ if _ , err := os .Stat (diskDir ); ! errors .Is (err , fs .ErrNotExist ) {
452
+ return fmt .Errorf ("disk %q already exists (%q)" , diskName , diskDir )
453
+ }
454
+
455
+ f , err := os .Open (fName )
456
+ if err != nil {
457
+ return err
458
+ }
459
+ defer f .Close ()
460
+
461
+ img , err := qcow2reader .Open (f )
462
+ if err != nil {
463
+ return err
464
+ }
465
+
466
+ diskSize := img .Size ()
467
+ format := img .Type ()
468
+
469
+ switch format {
470
+ case "qcow2" , "raw" :
471
+ default :
472
+ return fmt .Errorf (`disk format %q not supported, use "qcow2" or "raw" instead` , format )
473
+ }
474
+
475
+ if err := os .MkdirAll (diskDir , 0o755 ); err != nil {
476
+ return err
477
+ }
478
+
479
+ if err := contfs .CopyFile (filepath .Join (diskDir , filenames .DataDisk ), fName ); err != nil {
480
+ return nil
481
+ }
482
+
483
+ logrus .Infof ("Imported %s with size %s" , diskName , units .BytesSize (float64 (diskSize )))
484
+
485
+ return nil
486
+ }
0 commit comments