This repository has been archived by the owner on Aug 31, 2020. It is now read-only.
/
cab.go
353 lines (305 loc) · 9.25 KB
/
cab.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
// Copyright 2013 Google 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.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/gob"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"time"
"kylelemons.net/go/rx/graph"
)
var cabCmd = &Command{
Name: "cabinet",
Usage: "<repo> [<id>]",
Summary: "Save, list, or restore dependency snapshots.",
Help: `The cabinet command saves dependency information for the given
repository in a file within it. The <repo> can be any piece of the
repository root path, as long as it is unique. The <tag> is anything
understood by the underlying version control system as a commit, usually a
tag, branch, or commit. When saving, the <id> will override the default
(based on the date) and when opening the <id> is the ID (or a unique
substring) of the cabinet to open.
Cabinets are currently stored in the repository itself named as follows:
.rx/cabinet-YYYYMMDD-HHMMSS
If the <id> is specified for --build, it will override the date-based portion
of the cabinet name. If a cabinet already exists with the name (even if it is
a date-based name) it will not be overwritten.
Unless --test=false is specified, the packages in the repository will be tested
before a cabinet is created and after a cabinet is restored. If the test
before creation fails, the cabinet will not be created. If the test after
restoration fails, the repositories will be reverted to their original
revisions.
The cabinet format is still in flux.`,
}
const cabIDFormat = "20060102-150405"
var (
cabTest = cabCmd.Flag.Bool("test", true, "test package before saving and after loading cabinet")
cabList = cabCmd.Flag.Bool("list", true, "list matching cabinet files (the default)")
cabBuild = cabCmd.Flag.Bool("build", false, "create a new cabinet")
cabOpen = cabCmd.Flag.Bool("open", false, "open the specified cabinet")
cabDump = cabCmd.Flag.Bool("dump", false, "list the contents of the specified cabinet")
)
func cabFunc(cmd *Command, args ...string) {
if len(args) < 1 || len(args) > 2 {
cmd.BadArgs("requires two arguments")
}
path := args[0]
repo, err := Deps.FindRepo(path)
if err != nil {
cmd.Fatalf("<repo>: %s", err)
}
var id string
if len(args) > 1 {
id = args[1]
}
switch {
case *cabBuild:
if id == "" {
id = time.Now().Format(cabIDFormat)
}
err = buildCabinet(repo, id)
case *cabOpen:
err = openCabinet(cmd, repo, id)
case *cabDump:
if id == "" {
cmd.BadArgs("must specify <id> to dump")
}
err = dumpCabinet(repo, id)
case *cabList:
err = listCabinets(repo, id)
default:
cmd.BadArgs("no mode specified")
}
if err != nil {
cmd.Fatalf("%s", err)
}
}
// A CabFile is the data structure stored in a cabinet file.
type CabFile struct {
Repo string // The import path prefix covered by this cabinet (usually import/path/...)
Created time.Time // The time the cabinet was created
Head string // The hash of the repository at which this cabinet was created
Deps []*RepoVersion // The dependencies of this package
}
// A RepoVersion stores information about a dependency of a repository.
type RepoVersion struct {
Pattern string // The pattern required to scan for updates
Packages []string // Try `go get -d` on these in order until one succeeds
Head string // The hash of the repository to use after installation
}
// NewRepoVersion creates a repo version object suitable for storing into cabinets, etc.
func NewRepoVersion(repo *graph.Repository) (*RepoVersion, error) {
head, err := repo.Head()
if err != nil {
return nil, fmt.Errorf("get %s head: %s", repo, err)
}
return &RepoVersion{
Pattern: repo.String(),
Packages: repo.Packages,
Head: head,
}, nil
}
// Apply attempts to locate the repository and pin it to the head version.
func (dep *RepoVersion) Apply() error {
// Find the repository
var repo *graph.Repository
for _, pkg := range dep.Packages {
// Make sure the package is installed and up-to-date
get := exec.Command("go", "get", "-d", pkg)
get.Dir = os.TempDir()
get.Stdout = os.Stdout
get.Stderr = os.Stderr
if err := get.Run(); err != nil {
continue
}
// Scan for new packages
if err := Deps.Scan(dep.Pattern); err != nil {
continue
}
// See if we found the package we wanted
p, ok := Deps.Package[pkg]
if !ok {
continue
}
// Get the repository
r, ok := Deps.Repository[p.RepoRoot]
if !ok {
continue
}
repo = r
break
}
if repo == nil {
return fmt.Errorf("apply(%q@%q): unable to locate repository", dep.Pattern, dep.Head)
}
// Get fallback in case the update fails
fallback, err := repo.Head()
if err != nil {
return fmt.Errorf("apply(%q@%q): unable to determine fallback version", dep.Pattern, dep.Head)
}
// Pin the version
if err := repo.ToRev(dep.Head); err != nil {
if ferr := repo.ToRev(fallback); ferr != nil {
return fmt.Errorf("apply(%q): pin(%q) [%s] and fallback(%q) [%s] failed",
dep.Pattern, dep.Head, err, fallback, ferr)
}
return fmt.Errorf("apply(%q@%q): pin failed: %s", dep.Pattern, dep.Head, err)
}
log.Printf("Pinned %s @ %s", dep.Pattern, dep.Head)
return nil
}
func buildCabinet(repo *graph.Repository, id string) error {
// Build the cabinet data
head, err := repo.Head()
if err != nil {
return fmt.Errorf("build: get repo head: %s", err)
}
data := &CabFile{
Repo: repo.String(),
Created: time.Now(),
Head: head,
}
deps, err := Deps.RepoDeps(repo)
if err != nil {
return fmt.Errorf("build: scan dependencies: %s", err)
}
for _, dep := range deps {
rv, err := NewRepoVersion(dep)
if err != nil {
return fmt.Errorf("build: %s", err)
}
data.Deps = append(data.Deps, rv)
}
if *cabTest {
// Test the packages in the repository
test := exec.Command("go", "test", repo.String())
test.Dir = os.TempDir()
test.Stdout = os.Stdout
test.Stderr = os.Stderr
if err := test.Run(); err != nil {
return fmt.Errorf("build: `go test` failed: %s", err)
}
}
// Make the $REPO/.rx directory
repoRx := filepath.Join(repo.Root, ".rx")
if err := os.MkdirAll(repoRx, 0755); err != nil {
return fmt.Errorf("build: create .rx: %s", err)
}
filename := filepath.Join(repoRx, "cabinet-"+id)
// Open the file, but fail if it already exists
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
if err != nil {
return fmt.Errorf("build: open cabinet: %s", err)
}
defer file.Close()
if err := gob.NewEncoder(file).Encode(data); err != nil {
return fmt.Errorf("build: encoding cabinet: %s", err)
}
log.Printf("Cabinet written to %q", filename)
return nil
}
func listCabinetFiles(repo *graph.Repository, filter string) ([]string, error) {
pattern := filepath.Join(repo.Root, ".rx", "cabinet-*")
all, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
if filter == "" {
return all, nil
}
re, err := regexp.Compile(filter)
if err != nil {
return nil, err
}
var matches []string
for _, filename := range all {
if !re.MatchString(filename) {
continue
}
matches = append(matches, filename)
}
return matches, nil
}
func loadCabinet(repo *graph.Repository, id string) (string, *CabFile, error) {
files, err := listCabinetFiles(repo, id)
if err != nil {
return "", nil, fmt.Errorf("list: %s", err)
}
switch cnt := len(files); {
case cnt == 0:
return "", nil, fmt.Errorf("no matching cabinet files found")
case cnt > 1:
return "", nil, fmt.Errorf("non-unique id pattern %q (matched %d cabinets)", id, cnt)
}
filename := files[0]
file, err := os.Open(filename)
if err != nil {
return filename, nil, fmt.Errorf("open cabinet: %s", err)
}
data := new(CabFile)
if err := gob.NewDecoder(file).Decode(data); err != nil {
return filename, nil, fmt.Errorf("decode cabinet: %s", err)
}
return filename, data, nil
}
func openCabinet(cmd *Command, repo *graph.Repository, id string) error {
filename, data, err := loadCabinet(repo, id)
if err != nil {
return fmt.Errorf("open: %s", err)
}
var errors int
for _, dep := range data.Deps {
if err := dep.Apply(); err != nil {
errors++
cmd.Errorf("open: %s", err)
}
}
if errors > 0 {
return fmt.Errorf("open: %d repositories could not be pinned", errors)
}
log.Printf("Opened cabinet %q", filename)
return nil
}
func listCabinets(repo *graph.Repository, id string) error {
files, err := listCabinetFiles(repo, id)
if err != nil {
return fmt.Errorf("dump: list: %s", err)
}
for _, file := range files {
fmt.Println(file)
}
return nil
}
func dumpCabinet(repo *graph.Repository, id string) error {
_, data, err := loadCabinet(repo, id)
if err != nil {
return fmt.Errorf("dump: %s", err)
}
render(stdout, cabDumpTemplate, data)
return nil
}
var (
cabDumpTemplate = `Repository: {{.Repo}}
Created: {{.Created}} @ {{.Head}}
Dependencies:{{range .Deps}}
{{.Head}} {{.Pattern}}{{end}}
`
)
func init() {
cabCmd.Run = cabFunc
}