@@ -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,63 @@ 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
+ }
438
+ return diskImportCommand
439
+ }
440
+
441
+ func diskImportAction (_ * 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 , filenames .DataDisk ), fName ); err != nil {
479
+ return nil
480
+ }
481
+
482
+ logrus .Infof ("Imported %s with size %s" , diskName , units .BytesSize (float64 (diskSize )))
483
+
484
+ return nil
485
+ }
0 commit comments