github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/image/save.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package image 18 19 import ( 20 "context" 21 "fmt" 22 23 "github.com/containerd/containerd" 24 "github.com/containerd/containerd/images/archive" 25 "github.com/containerd/nerdctl/v2/pkg/api/types" 26 "github.com/containerd/nerdctl/v2/pkg/idutil/imagewalker" 27 "github.com/containerd/nerdctl/v2/pkg/platformutil" 28 "github.com/containerd/nerdctl/v2/pkg/strutil" 29 ) 30 31 // Save exports `images` to a `io.Writer` (e.g., a file writer, or os.Stdout) specified by `options.Stdout`. 32 func Save(ctx context.Context, client *containerd.Client, images []string, options types.ImageSaveOptions, exportOpts ...archive.ExportOpt) error { 33 images = strutil.DedupeStrSlice(images) 34 35 platMC, err := platformutil.NewMatchComparer(options.AllPlatforms, options.Platform) 36 if err != nil { 37 return err 38 } 39 40 exportOpts = append(exportOpts, archive.WithPlatform(platMC)) 41 imageStore := client.ImageService() 42 43 savedImages := make(map[string]struct{}) 44 walker := &imagewalker.ImageWalker{ 45 Client: client, 46 OnFound: func(ctx context.Context, found imagewalker.Found) error { 47 if found.UniqueImages > 1 { 48 return fmt.Errorf("ambiguous digest ID: multiple IDs found with provided prefix %s", found.Req) 49 } 50 imgName := found.Image.Name 51 imgDigest := found.Image.Target.Digest.String() 52 if _, ok := savedImages[imgDigest]; !ok { 53 savedImages[imgDigest] = struct{}{} 54 exportOpts = append(exportOpts, archive.WithImage(imageStore, imgName)) 55 } 56 return nil 57 }, 58 } 59 60 // check if all images exist 61 if err := walker.WalkAll(ctx, images, false); err != nil { 62 return err 63 } 64 65 return client.Export(ctx, options.Stdout, exportOpts...) 66 }