-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
329 lines (299 loc) · 8.04 KB
/
main.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/binxio/cru/ref"
"github.com/docopt/docopt-go"
"gopkg.in/src-d/go-billy.v4"
"gopkg.in/src-d/go-billy.v4/osfs"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
)
type Cru struct {
Path []string
List bool
Update bool
Serve bool
Port string
Bump bool
NoFilename bool
DryRun bool
Verbose bool
ResolveDigest bool
ResolveTag bool
All bool
ImageReference []string
Level string
Url string `docopt:"--repository"`
CommitMsg string `docopt:"--commit"`
Branch string `docopt:"--branch"`
Username string
Email string
MatchingTag bool
imageRefs ref.ContainerImageReferences
updatedFiles []string
committedFiles []string
repository *git.Repository
workTree *git.Worktree
filesystem *billy.Filesystem
cwd string
}
func (c *Cru) AssertPathsExists() {
if len(c.Path) == 0 {
c.Path = append(c.Path, ".")
}
for _, path := range c.Path {
if _, err := (*c.filesystem).Stat(c.AbsPath(path)); os.IsNotExist(err) {
log.Fatalf("ERROR: %s is not a file or directory\n", path)
}
}
}
func CollectReferences(c *Cru, filename string) error {
content, err := c.ReadFile(filename)
if err != nil {
return fmt.Errorf("could not read %s, %s", filename, err)
}
c.imageRefs = append(c.imageRefs, ref.FindAllContainerImageReference(content)...)
return nil
}
func (c *Cru) ReadFile(filename string) (content []byte, err error) {
var file billy.File
file, err = (*c.filesystem).Open(filename)
if err != nil {
return
}
defer file.Close()
return ioutil.ReadAll(file)
}
func (c *Cru) WriteFile(filename string, content []byte, perm os.FileMode) error {
file, err := (*c.filesystem).OpenFile(filename, os.O_WRONLY|os.O_TRUNC, perm)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(content)
return err
}
func List(c *Cru, filename string) error {
content, err := c.ReadFile(filename)
if err != nil {
return fmt.Errorf("could not read %s, %s", filename, err)
}
for _, ref := range ref.FindAllContainerImageReference(content) {
if c.NoFilename {
fmt.Printf("%s\n", ref.String())
} else {
if relative, err := filepath.Rel(c.cwd, filename); err == nil {
filename = relative
}
fmt.Printf("%s:%s\n", filename, ref.String())
}
}
return nil
}
func Update(c *Cru, filename string) error {
content, err := c.ReadFile(filename)
if err != nil {
return fmt.Errorf("could not read %s, %s", c.RelPath(filename), err)
}
content, updated := ref.UpdateReferences(content, c.imageRefs, c.RelPath(filename), c.MatchingTag, c.Verbose)
if updated {
if !c.DryRun {
err := c.WriteFile(filename, content, 0o644)
if err != nil {
return fmt.Errorf("failed to overwrite %s with updated references, %s", c.RelPath(filename), err)
}
}
c.updatedFiles = append(c.updatedFiles, filename)
}
return nil
}
func (c *Cru) ReadOnly() bool {
return c.List || c.DryRun
}
func (c *Cru) ConnectToRepository() error {
if c.Url != "" {
var progressReporter io.Writer = os.Stderr
if !c.Verbose {
progressReporter = &bytes.Buffer{}
}
repository, err := Clone(c.Url, progressReporter, c.ReadOnly())
if err != nil {
return err
}
c.repository = repository
wt, err := repository.Worktree()
if err != nil {
return err
}
c.workTree = wt
if c.Branch != "" {
var branch *plumbing.Reference
if branches, err := repository.Branches(); err == nil {
branches.ForEach(func(ref *plumbing.Reference) error {
if ref.Name().Short() == c.Branch {
branch = ref
}
return nil
})
}
if err != nil {
return err
}
if branch == nil {
return fmt.Errorf("ERROR: branch %s not found", c.Branch)
}
err = wt.Checkout(&git.CheckoutOptions{Branch: branch.Name()})
if err != nil {
return err
}
}
c.filesystem = &wt.Filesystem
c.cwd = "/"
} else {
cwd, err := filepath.Abs(".")
if err != nil {
return err
}
c.cwd = cwd
fs := osfs.New("/")
c.filesystem = &fs
}
return nil
}
func (c *Cru) ApplyDefaults() {
if c.Username == "" {
c.Username = "cru"
}
if c.Email == "" {
c.Email = "[email protected]"
}
}
func main() {
usage := `cru - container image reference updater
Usage:
cru list [--verbose] [--no-filename] [--repository=URL [--branch=BRANCH] [(--username=USERNAME --email=EMAIL)] ] [PATH] ...
cru update [--verbose] [--dry-run] [(--resolve-digest|--resolve-tag)] [--repository=URL [--branch=BRANCH] [(--username=USERNAME --email=EMAIL)] [--commit=MESSAGE]] (--all | --image-reference=REFERENCE ...) [--matching-tag] [PATH] ...
cru serve [--verbose] [--dry-run] [--port=PORT] --repository=URL --branch=BRANCH [(--username=USERNAME --email=EMAIL)] [PATH] ...
Options:
--no-filename do not print the filename.
--resolve-digest change the image reference tag to a reference of the digest of the image.
--resolve-tag change the image reference tag to the first alternate tag of the reference.
--image-reference=REFERENCE to update.
--dry-run pretend to run the update, make no changes.
--all replace all container image reference tags with "latest"
--matching-tag replace only image references with matching tags.
--verbose show more output.
--commit=MESSAGE commit the changes with the specified message.
--repository=URL to read and/or update.
--branch=BRANCH to update.
--username=USERNAME to use for the commit [default: cru].
--email=EMAIL to use for the commit [default: [email protected]].
--port=PORT to listen on, defaults to 8080 or PORT environment variable.
`
cru := Cru{}
args, err := docopt.ParseDoc(usage)
if err != nil {
log.Fatal(err)
}
if err = args.Bind(&cru); err != nil {
log.Fatal(err)
}
if cru.Url == "" {
if cru.CommitMsg != "" {
fmt.Fprint(os.Stderr, "ERROR: --repository option is required when specifying a commit message")
os.Exit(1)
}
if cru.Username != "" {
fmt.Fprint(os.Stderr, "ERROR: --repository option is required when specifying a git username")
os.Exit(1)
}
if cru.Email != "" {
fmt.Fprint(os.Stderr, "ERROR: --repository option is required when specifying a git email")
os.Exit(1)
}
}
cru.ApplyDefaults()
if err = cru.ConnectToRepository(); err != nil {
log.Fatal(err)
}
cru.AssertPathsExists()
cru.imageRefs = make(ref.ContainerImageReferences, 0)
if cru.Serve {
if cru.Url == "" {
log.Fatalf("cru as a service requires an git url.")
}
cru.ListenAndServe()
}
if cru.All {
if cru.Verbose {
log.Println("INFO: collecting all container references")
}
err = cru.Walk(CollectReferences)
if err != nil {
log.Fatalf("%s\n", err)
}
if !cru.MatchingTag {
for i := range cru.imageRefs {
cru.imageRefs[i].SetTag("latest")
}
}
cru.imageRefs = cru.imageRefs.RemoveDuplicates()
log.Printf("INFO: %d image references found\n", len(cru.imageRefs))
if len(cru.imageRefs) == 0 {
os.Exit(0)
}
}
for _, r := range cru.ImageReference {
r, err := ref.NewContainerImageReference(r)
if err != nil {
log.Fatalf("ERROR: %s", err)
}
cru.imageRefs = append(cru.imageRefs, *r)
}
if cru.ResolveDigest {
var err error
cru.imageRefs, err = cru.imageRefs.ResolveDigest()
if err != nil {
log.Fatal(err)
}
}
if cru.ResolveTag {
var err error
cru.imageRefs, err = cru.imageRefs.ResolveTag()
if err != nil {
log.Fatal(err)
}
}
if cru.List {
if err = cru.Walk(List); err != nil {
log.Fatal(err)
}
} else if cru.Update {
if err = cru.Walk(Update); err != nil {
log.Fatal(err)
}
if len(cru.updatedFiles) > 0 {
log.Printf("INFO: updated a total of %d files", len(cru.updatedFiles))
if cru.CommitMsg != "" {
if _, err = cru.Commit(); err != nil {
log.Fatal(err)
}
if !IsLocalEndpoint(cru.Url) {
if err = cru.Push(); err != nil {
log.Fatal(err)
}
}
} else {
log.Println("INFO: no commit message, skipping commit and push")
}
} else {
log.Println("INFO: no files were updated by cru")
}
}
}