github.com/sudo-bmitch/version-bump@v0.0.0-20240503123857-70b0e3f646dd/internal/source/registry.go (about) 1 package source 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/regclient/regclient" 8 "github.com/regclient/regclient/types/ref" 9 "github.com/sudo-bmitch/version-bump/internal/config" 10 ) 11 12 const () 13 14 type registry struct { 15 conf config.Source 16 rc *regclient.RegClient 17 } 18 19 func newRegistry(conf config.Source) Source { 20 rc := regclient.New( 21 regclient.WithDockerCreds(), 22 ) 23 return registry{conf: conf, rc: rc} 24 } 25 26 func (r registry) Get(data config.SourceTmplData) (string, error) { 27 confExp, err := r.conf.ExpandTemplate(data) 28 if err != nil { 29 return "", fmt.Errorf("failed to expand template: %w", err) 30 } 31 if confExp.Args["type"] == "tag" { 32 return r.getTag(confExp) 33 } 34 // default request is for a digest 35 return r.getDigest(confExp) 36 } 37 38 func (r registry) getTag(confExp config.Source) (string, error) { 39 repo, ok := confExp.Args["repo"] 40 if !ok { 41 return "", fmt.Errorf("repo not defined") 42 } 43 repoRef, err := ref.New(repo) 44 if err != nil { 45 return "", fmt.Errorf("failed to parse repo: %w", err) 46 } 47 tags, err := r.rc.TagList(context.Background(), repoRef) 48 if err != nil { 49 return "", fmt.Errorf("failed to list tags: %w", err) 50 } 51 verData := VersionTmplData{ 52 VerMap: map[string]string{}, 53 } 54 for _, tag := range tags.Tags { 55 verData.VerMap[tag] = tag 56 } 57 if len(verData.VerMap) == 0 { 58 return "", fmt.Errorf("no matching tags found") 59 } 60 return procResult(confExp, verData) 61 } 62 63 func (r registry) getDigest(confExp config.Source) (string, error) { 64 image, ok := confExp.Args["image"] 65 if !ok { 66 return "", fmt.Errorf("image not defined") 67 } 68 imageRef, err := ref.New(image) 69 if err != nil { 70 return "", fmt.Errorf("failed to parse image: %w", err) 71 } 72 m, err := r.rc.ManifestHead(context.Background(), imageRef) 73 if err != nil { 74 return "", fmt.Errorf("failed to query image: %w", err) 75 } 76 verData := VersionTmplData{ 77 Version: m.GetDescriptor().Digest.String(), 78 } 79 return procResult(confExp, verData) 80 } 81 82 func (r registry) Key(data config.SourceTmplData) (string, error) { 83 confExp, err := r.conf.ExpandTemplate(data) 84 if err != nil { 85 return "", fmt.Errorf("failed to expand template: %w", err) 86 } 87 return confExp.Key, nil 88 }