-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
454 lines (396 loc) · 11.1 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package main
import (
"bytes"
"fmt"
"github.com/binxio/fromage/tag"
"github.com/docopt/docopt-go"
"github.com/google/go-containerregistry/pkg/name"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/plumbing/storer"
"io"
"io/ioutil"
"log"
"os"
"path"
"strings"
"time"
)
type Fromage struct {
Check bool
List bool
Bump bool
Move bool
Format string
OnlyReferences bool
NoHeader bool
Branch []string
Url string
DryRun bool
Verbose bool
Pin string
Latest bool
From, To string
repository *git.Repository
workTree *git.Worktree
currentBranch *plumbing.Reference
dockerfile string
references DockerfileFromReferences
pin *tag.Level
updated bool
}
func (f *Fromage) IsLocalRepository() bool {
return !MatchesScheme(f.Url) && !MatchesScpLike(f.Url)
}
func FindDockerfiles(wt *git.Worktree, filename string, ref *plumbing.Reference) ([]string, error) {
result := make([]string, 0)
file, err := wt.Filesystem.Stat(filename)
if err != nil {
return nil, err
}
if file.IsDir() {
dir, err := wt.Filesystem.ReadDir(filename)
if err != nil {
return nil, err
}
for _, file = range dir {
fullPath := path.Join(filename, file.Name())
if filename == "/" {
fullPath = file.Name()
}
found, err := FindDockerfiles(wt, fullPath, ref)
if err == nil {
result = append(result, found...)
} else {
return nil, err
}
}
} else {
if path.Base(file.Name()) == "Dockerfile" {
result = append(result, filename)
}
}
return result, nil
}
func ReadFile(wt *git.Worktree, filename string) ([]byte, error) {
file, err := wt.Filesystem.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
content, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
return content, nil
}
func WriteFile(wt *git.Worktree, filename string, content []byte) error {
file, err := wt.Filesystem.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(content)
if err != nil {
return err
}
_, err = wt.Add(filename)
return err
}
func ReadFromStatements(wt *git.Worktree, filename string) ([]string, error) {
content, err := ReadFile(wt, filename)
if err != nil {
return nil, err
}
return ExtractFromStatements(content), nil
}
func DesiredBranch(reference *plumbing.Reference, branches []string) bool {
if !reference.Name().IsBranch() {
return false
}
for _, branch := range branches {
if branch == reference.Name().Short() || branch == reference.Name().String() {
return true
}
}
return len(branches) == 0
}
func (f *Fromage) ReadOnly() bool {
return f.Check || f.List || f.DryRun
}
func (f *Fromage) OpenRepository() {
var err error
if f.Verbose {
f.repository, err = Clone(f.Url, os.Stderr, f.ReadOnly())
} else {
f.repository, err = Clone(f.Url, &bytes.Buffer{}, f.ReadOnly())
}
if err != nil {
log.Printf("ERROR: failed to clone repository %s, %s", f.Url, err)
os.Exit(1)
}
f.workTree, err = f.repository.Worktree()
if err != nil {
log.Printf("ERROR: failed to get repository worktree of %s, %s", f.Url, err)
os.Exit(1)
}
f.references = make(DockerfileFromReferences, 0)
for _, branch := range f.Branch {
found := false
_ = f.Branches().ForEach(func(reference *plumbing.Reference) error {
found = found || (branch == reference.Name().Short() || branch == reference.Name().String())
return nil
})
if !found {
log.Printf("ERROR: branch %s does not exist", branch)
os.Exit(1)
}
}
}
func (f Fromage) Branches() storer.ReferenceIter {
branches, err := f.repository.Branches()
if err != nil {
log.Printf("failed retrieve branches of repository %s, %s", f.Url, err)
os.Exit(1)
}
return branches
}
func (f *Fromage) ForEachDockerfile(m func(f *Fromage) error) error {
return f.Branches().ForEach(func(ref *plumbing.Reference) error {
f.currentBranch = ref
if !DesiredBranch(ref, f.Branch) {
return nil
}
if f.Verbose {
log.Printf("checking out %s\n", ref.Name().Short())
}
err := f.workTree.Checkout(&git.CheckoutOptions{
Branch: ref.Name(),
Force: false,
})
if err != nil {
return fmt.Errorf("ERROR: checkout of %s failed, %s", ref.Name().Short(), err)
}
dockerfiles, err := FindDockerfiles(f.workTree, "/", ref)
if err != nil {
return err
}
for _, f.dockerfile = range dockerfiles {
if err = m(f); err != nil {
return err
}
}
return nil
})
}
func ListAllReferences(f *Fromage) error {
references, err := ReadFromStatements(f.workTree, f.dockerfile)
if err != nil {
return err
}
for _, reference := range references {
var newer []string
if successors, err := tag.GetAllSuccessorsByString(reference, f.pin); err == nil {
newer = make([]string, 0, len(successors))
for _, v := range successors {
newer = append(newer, v.String())
}
}
froms := DockerfileFromReference{
Branch: f.currentBranch.Name().Short(),
Path: f.dockerfile,
Reference: reference,
Newer: newer,
}
f.references = append(f.references, &froms)
}
return nil
}
func BumpReferences(f *Fromage) error {
content, err := ReadFile(f.workTree, f.dockerfile)
if err != nil {
return err
}
content, updated := UpdateAllFromStatements(content, f.dockerfile, f.pin, f.Latest, f.Verbose)
if updated {
f.updated = true
if !f.DryRun {
return WriteFile(f.workTree, f.dockerfile, content)
}
}
return nil
}
func moveImageReferences(content []byte, filename string, verbose bool, from, to string) ([]byte, bool, error) {
updated := false
refs := ExtractFromStatements(content)
for _, refString := range refs {
ref, err := name.ParseReference(refString)
fullRef := ref.Name()
if err != nil {
return nil, false, err
}
if !strings.HasPrefix(fullRef, from) && len(fullRef) > len(from) {
continue
}
if delimiter := fullRef[len(from)]; delimiter != ':' && delimiter != '/' && delimiter != '@' {
continue
}
newRefString := to + fullRef[len(from):]
if to == "index.docker.io/library" {
newRefString = fullRef[len(from)+1:]
}
newRef, err := name.ParseReference(newRefString)
if err != nil {
return nil, false, err
}
if !RepositoryExists(newRef, verbose) {
return nil, false, fmt.Errorf("ERROR: %s is not a valid image reference", newRef)
}
ok := false
if content, ok = UpdateFromStatements(content, ref, newRef, filename, verbose); ok {
updated = true
}
}
return content, updated, nil
}
func MoveImageReferences(f *Fromage) error {
content, err := ReadFile(f.workTree, f.dockerfile)
if err != nil {
return err
}
content, f.updated, err = moveImageReferences(content, f.dockerfile, f.Verbose, f.From, f.To)
if err != nil {
log.Fatalf("%s", err)
}
if f.updated {
if !f.DryRun {
return WriteFile(f.workTree, f.dockerfile, content)
}
}
return nil
}
func main() {
usage := `fromage - checks, list and bumps all container references in Dockerfiles in a git repository
Usage:
fromage list [--verbose] [--format=FORMAT] [--no-header] [--only-references] [--branch=BRANCH ...] URL
fromage check [--verbose] [--format=FORMAT] [--no-header] [--only-references] [--branch=BRANCH ...] [--pin=LEVEL] URL
fromage bump [--verbose] [--dry-run] [--pin=LEVEL] [--latest] --branch=BRANCH URL
fromage move [--verbose] [--dry-run] --from=FROM_REPOSITORY --to=TO_REPOSITORY --branch=BRANCH URL
Options:
--branch=BRANCH to inspect, defaults to all branches.
--format=FORMAT to print: text, json or yaml [default: text].
--no-header do not print header if output type is text.
--only-references output only container image references.
--pin=LEVEL pins the MAJOR or MINOR version level
--latest bump to the latest version available
--from=FROM_REPOSITORY from repository context
--to=TO_REPOSITORY to repository context
Description:
list will iterate over all dockerfiles in all branches in the repository and print out all container
image references and list newer versions if available.
check will do the same, and if there are newer versions available print the out of date container
image references and exit with 1.
bump will update the container images references on the specified branch and commit/push the changes
back to the repository.
move will move the container image reference on the specified branch from one registry to another. The
changes are committed/pushed back to the git repository.
`
var fromage Fromage
if opts, err := docopt.ParseDoc(usage); err == nil {
if err = opts.Bind(&fromage); err != nil {
log.Fatal(err)
}
if fromage.Pin != "" {
if limit, err := tag.MakeLevelFromString(fromage.Pin); err != nil {
log.Fatal(err)
} else {
fromage.pin = &limit
}
}
} else {
log.Fatal(err)
}
fromage.OpenRepository()
if fromage.List || fromage.Check {
if err := fromage.ForEachDockerfile(ListAllReferences); err != nil {
log.Fatal(err)
}
if fromage.Check {
fromage.references = fromage.references.FilterOutOfDate()
}
if fromage.OnlyReferences {
fromage.references.OutputOnlyReferences(fromage.Format, fromage.NoHeader)
} else {
fromage.references.Output(fromage.Format, fromage.NoHeader)
}
if fromage.Check && len(fromage.references) > 0 {
os.Exit(1)
}
} else if fromage.Bump {
if err := fromage.ForEachDockerfile(BumpReferences); err != nil {
log.Fatal(err)
}
msg := "container image references bumped"
if fromage.pin != nil {
msg = msg + " pinned on " + strings.ToLower(fromage.pin.String()) + " level"
}
if err := fromage.CommitAndPush(msg); err != nil {
log.Fatal(err)
}
} else if fromage.Move {
if fromage.From == "" || fromage.To == "" {
log.Fatal("both --from and --to are required to move an image reference")
}
if strings.ContainsAny(fromage.From, "@:") || strings.ContainsAny(fromage.To, "@:") {
log.Fatal("the --from and --to image references should not contain an tag or digest")
}
if err := fromage.ForEachDockerfile(MoveImageReferences); err != nil {
log.Fatal(err)
}
if err := fromage.CommitAndPush(fmt.Sprintf("moved references from %s to %s", fromage.From, fromage.To)); err != nil {
log.Fatal(err)
}
} else {
log.Fatalf("I don't know what to do")
}
}
func (f *Fromage) CommitAndPush(msg string) error {
if !f.updated {
return nil
}
log.Printf("INFO: %s", msg)
if !f.DryRun {
hash, err := f.workTree.Commit(msg, &git.CommitOptions{
Author: &object.Signature{
Name: "fromage",
Email: "[email protected]",
When: time.Now(),
},
})
if err != nil {
return err
}
log.Printf("INFO: changes committed with %s", hash.String()[0:7])
} else {
log.Printf("INFO: changes would be committed")
}
if f.IsLocalRepository() {
return nil
}
if !f.DryRun {
var progress io.Writer = os.Stderr
if !f.Verbose {
progress = &bytes.Buffer{}
}
log.Printf("INFO: pushing changes to %s", f.Url)
auth, _, err := GetAuth(f.Url)
if err != nil {
return err
}
return f.repository.Push(&git.PushOptions{Auth: auth, Progress: progress})
} else {
log.Printf("INFO: changes would be pushed to %s", f.Url)
}
return nil
}