-
Notifications
You must be signed in to change notification settings - Fork 9
/
imageid.go
71 lines (58 loc) · 1.54 KB
/
imageid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package oci
import (
"context"
"fmt"
"strings"
"github.com/google/go-containerregistry/pkg/name"
"namespacelabs.dev/foundation/schema"
)
type ImageID struct {
Repository string `json:"repository"`
Tag string `json:"tag"`
Digest string `json:"digest"`
}
func (i ImageID) ImageRef() string {
r := i.Repository
if i.Tag != "" {
r += ":" + i.Tag
}
if i.Digest != "" {
r += "@" + i.Digest
}
return r
}
func (i ImageID) String() string {
return i.ImageRef()
}
func (i ImageID) RepoAndDigest() string {
if i.Digest != "" {
// XXX security: consider enforcing the use of digests
return i.Repository + "@" + i.Digest
}
return i.ImageRef()
}
func (i ImageID) WithDigest(d fmt.Stringer) ImageID {
return ImageID{Repository: i.Repository, Tag: i.Tag, Digest: d.String()}
}
func (i ImageID) ComputeDigest(ctx context.Context) (schema.Digest, error) {
return schema.DigestOf("repository", i.Repository, "tag", i.Tag, "digest", i.Digest)
}
func ParseImageID(ref string) (ImageID, error) {
parts := strings.SplitN(ref, "@", 2)
t, err := name.NewTag(parts[0], name.WithDefaultTag(""))
if err != nil {
return ImageID{}, err
}
i := ImageID{Repository: t.Repository.Name(), Tag: t.TagStr()}
if len(parts) == 2 {
d, err := name.NewDigest(ref)
if err != nil {
return ImageID{}, err
}
i.Digest = d.DigestStr()
}
return i, nil
}