-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathbundle_lock.go
94 lines (75 loc) · 2.23 KB
/
bundle_lock.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
package lockconfig
import (
"fmt"
"io/ioutil"
regname "github.com/google/go-containerregistry/pkg/name"
"sigs.k8s.io/yaml"
)
const (
BundleLockKind = "BundleLock"
BundleLockAPIVersion = "imgpkg.carvel.dev/v1alpha1"
)
type BundleLock struct {
LockVersion
Bundle BundleRef `json:"bundle"` // This generated yaml, but due to lib we need to use `json`
}
type BundleRef struct {
Image string `json:"image,omitempty"` // This generated yaml, but due to lib we need to use `json`
Tag string `json:"tag,omitempty"` // This generated yaml, but due to lib we need to use `json`
OtherTags string `json:"otherTags,omitempty"`
}
func NewBundleLockFromPath(path string) (BundleLock, error) {
bs, err := ioutil.ReadFile(path)
if err != nil {
return BundleLock{}, fmt.Errorf("Reading path %s: %s", path, err)
}
return NewBundleLockFromBytes(bs)
}
func NewBundleLockFromBytes(data []byte) (BundleLock, error) {
var lock BundleLock
err := yaml.UnmarshalStrict(data, &lock)
if err != nil {
return lock, fmt.Errorf("Unmarshaling bundle lock: %s", err)
}
err = lock.Validate()
if err != nil {
return lock, fmt.Errorf("Validating bundle lock: %s", err)
}
return lock, nil
}
func (b BundleLock) Validate() error {
if b.APIVersion != BundleLockAPIVersion {
return fmt.Errorf("Validating apiVersion: Unknown version (known: %s)", BundleLockAPIVersion)
}
if b.Kind != BundleLockKind {
return fmt.Errorf("Validating kind: Unknown kind (known: %s)", BundleLockKind)
}
if _, err := regname.NewDigest(b.Bundle.Image); err != nil {
return fmt.Errorf("Expected ref to be in digest form, got '%s'", b.Bundle.Image)
}
return nil
}
func (b BundleLock) AsBytes() ([]byte, error) {
err := b.Validate()
if err != nil {
return nil, fmt.Errorf("Validating bundle lock: %s", err)
}
bs, err := yaml.Marshal(b)
if err != nil {
return nil, fmt.Errorf("Marshaling config: %s", err)
}
return []byte(fmt.Sprintf("---\n%s", bs)), nil
}
func (b BundleLock) WriteToPath(path string) error {
bs, err := b.AsBytes()
if err != nil {
return err
}
err = ioutil.WriteFile(path, bs, 0600)
if err != nil {
return fmt.Errorf("Writing bundle config: %s", err)
}
return nil
}