Skip to content

Commit

Permalink
fix can't save image by image id
Browse files Browse the repository at this point in the history
Signed-off-by: ningmingxiao <[email protected]>
  • Loading branch information
ningmingxiao committed Dec 16, 2021
1 parent b72b5ca commit da0cb95
Showing 1 changed file with 48 additions and 5 deletions.
53 changes: 48 additions & 5 deletions cmd/nerdctl/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@
package main

import (
"context"
"fmt"
"io"
"os"

"github.com/containerd/containerd/images/archive"
"github.com/containerd/nerdctl/pkg/idutil/imagewalker"
"github.com/containerd/nerdctl/pkg/platformutil"
"github.com/containerd/nerdctl/pkg/referenceutil"
"github.com/mattn/go-isatty"

"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -105,17 +105,60 @@ func saveImage(images []string, out io.Writer, saveOpts []archive.ExportOpt, cmd
saveOpts = append(saveOpts, archive.WithPlatform(platMC))

imageStore := client.ImageService()
var foundImageNames []string
var foundId []string
walker := &imagewalker.ImageWalker{
Client: client,
OnFound: func(ctx context.Context, found imagewalker.Found) error {
if found.Image.Name != "" {
foundImageNames = append(foundImageNames, found.Image.Name)
if found.Image.Target.Digest.String() != "" {
foundId = append(foundId, found.Image.Target.Digest.String())
}
}
return nil
},
}
for _, img := range images {
named, err := referenceutil.ParseAny(img)
var empty []string
foundImageNames = empty
foundId = empty
_, err = walker.Walk(ctx, img)
if err != nil {
return err
}
saveOpts = append(saveOpts, archive.WithImage(imageStore, named.String()))
if err = checkRepeatId(foundId); err != nil {
return err
}
for _, localName := range foundImageNames {
saveOpts = append(saveOpts, archive.WithImage(imageStore, localName))
}
}

return client.Export(ctx, out, saveOpts...)
}

func checkRepeatId(stringSlice []string) error {
uniqueSlice := uniqueSlice(stringSlice)
if len(uniqueSlice) > 1 {
return fmt.Errorf("ambiguous digest id")
} else if len(uniqueSlice) == 0 {
return fmt.Errorf("reference does not exist")
}
return nil
}

func uniqueSlice(Slice []string) []string {
keys := make(map[string]bool)
uniq := []string{}
for _, entry := range Slice {
if _, value := keys[entry]; !value {
keys[entry] = true
uniq = append(uniq, entry)
}
}
return uniq
}

func saveShellComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
// show image names
return shellCompleteImageNames(cmd)
Expand Down

0 comments on commit da0cb95

Please sign in to comment.