forked from buildpacks/pack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrebase.go
116 lines (96 loc) · 2.32 KB
/
rebase.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package pack
import (
"context"
"encoding/json"
"errors"
"github.com/buildpack/lifecycle/image"
"github.com/buildpack/pack/logging"
"github.com/buildpack/lifecycle"
"github.com/buildpack/pack/config"
)
const (
RunImageLabel = "io.buildpacks.run-image"
)
type RebaseConfig struct {
Image image.Image
NewBaseImage image.Image
}
type RebaseFactory struct {
Logger *logging.Logger
Config *config.Config
Fetcher Fetcher
}
type RebaseFlags struct {
RepoName string
Publish bool
NoPull bool
RunImage string
}
func (f *RebaseFactory) RebaseConfigFromFlags(ctx context.Context, flags RebaseFlags) (RebaseConfig, error) {
var newImageFn func(string) (image.Image, error)
if flags.Publish {
newImageFn = f.Fetcher.FetchRemoteImage
} else {
newImageFn = func(name string) (image.Image, error) {
if !flags.NoPull {
return f.Fetcher.FetchUpdatedLocalImage(ctx, name, f.Logger.RawVerboseWriter())
} else {
return f.Fetcher.FetchLocalImage(name)
}
}
}
appImage, err := newImageFn(flags.RepoName)
if err != nil {
return RebaseConfig{}, err
}
var runImageName string
if flags.RunImage != "" {
runImageName = flags.RunImage
} else {
runImageName, err = appImage.Label(RunImageLabel)
if err != nil {
return RebaseConfig{}, err
}
}
if runImageName == "" {
return RebaseConfig{}, errors.New("run image must be specified")
}
baseImage, err := newImageFn(runImageName)
if err != nil {
return RebaseConfig{}, err
}
return RebaseConfig{
Image: appImage,
NewBaseImage: baseImage,
}, nil
}
func (f *RebaseFactory) Rebase(cfg RebaseConfig) error {
label, err := cfg.Image.Label("io.buildpacks.lifecycle.metadata")
if err != nil {
return err
}
var metadata lifecycle.AppImageMetadata
if err := json.Unmarshal([]byte(label), &metadata); err != nil {
return err
}
if err := cfg.Image.Rebase(metadata.RunImage.TopLayer, cfg.NewBaseImage); err != nil {
return err
}
metadata.RunImage.SHA, err = cfg.NewBaseImage.Digest()
if err != nil {
return err
}
metadata.RunImage.TopLayer, err = cfg.NewBaseImage.TopLayer()
if err != nil {
return err
}
newLabel, err := json.Marshal(metadata)
if err := cfg.Image.SetLabel("io.buildpacks.lifecycle.metadata", string(newLabel)); err != nil {
return err
}
_, err = cfg.Image.Save()
if err != nil {
return err
}
return nil
}