github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/image/tag.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/errdefs" 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/referenceutil" 28 ) 29 30 func Tag(ctx context.Context, client *containerd.Client, options types.ImageTagOptions) error { 31 imageService := client.ImageService() 32 var srcName string 33 imagewalker := &imagewalker.ImageWalker{ 34 Client: client, 35 OnFound: func(ctx context.Context, found imagewalker.Found) error { 36 if srcName == "" { 37 srcName = found.Image.Name 38 } 39 return nil 40 }, 41 } 42 matchCount, err := imagewalker.Walk(ctx, options.Source) 43 if err != nil { 44 return err 45 } 46 if matchCount < 1 { 47 return fmt.Errorf("%s: not found", options.Source) 48 } 49 50 target, err := referenceutil.ParseDockerRef(options.Target) 51 if err != nil { 52 return err 53 } 54 55 ctx, done, err := client.WithLease(ctx) 56 if err != nil { 57 return err 58 } 59 defer done(ctx) 60 61 image, err := imageService.Get(ctx, srcName) 62 if err != nil { 63 return err 64 } 65 image.Name = target.String() 66 if _, err = imageService.Create(ctx, image); err != nil { 67 if errdefs.IsAlreadyExists(err) { 68 if err = imageService.Delete(ctx, image.Name); err != nil { 69 return err 70 } 71 if _, err = imageService.Create(ctx, image); err != nil { 72 return err 73 } 74 } else { 75 return err 76 } 77 } 78 return nil 79 }