-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
357 lines (311 loc) · 8.95 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
package fab
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime/debug"
"strings"
"time"
"github.com/bobg/errors"
"github.com/bobg/go-generics/v2/slices"
"golang.org/x/tools/go/packages"
"github.com/bobg/fab/sqlite"
)
// Main is the structure whose Run methods implements the main logic of the fab command.
type Main struct {
// Fabdir is where to find the user's hash DB and compiled binaries, e.g. $HOME/.cache/fab.
Fabdir string
// Topdir is the directory containing a _fab subdir or top-level fab.yaml file.
// If this is not specified, it will be computed by traversing upward from the current directory.
Topdir string
// Verbose tells whether to run the driver in verbose mode
// (by supplying the -v command-line flag).
Verbose bool
// List tells whether to run the driver in list-targets mode
// (by supplying the -list command-line flag).
List bool
// Force tells whether to force recompilation of the driver before running it.
Force bool
// DryRun tells whether to run targets in "dry run" mode - i.e., with state-changing operations (like file creation and updating) suppressed.
DryRun bool
// Args contains the additional command-line arguments to pass to the driver, e.g. target names.
Args []string
}
// Run executes the main logic of the fab command.
// A driver binary with a name matching the Go package path of the _fab subdir
// is sought in m.Fabdir.
// If it does not exist,
// or if its corresponding dirhash is wrong
// (i.e., out of date with respect to the user's code),
// or if m.Force is true,
// it is created with Compile.
// It is then invoked with the command-line arguments indicated by the fields of m.
// Typically this will include one or more target names,
// in which case the driver will execute the associated rules
// as defined by the code in _fab
// and by any fab.yaml files.
//
// If there is no _fab directory,
// Run operates in "driverless" mode,
// in which target definitions are found in fab.yaml files only.
func (m *Main) Run(ctx context.Context) error {
if m.Topdir == "" {
var err error
m.Topdir, err = TopDir(".")
if err != nil {
return errors.Wrap(err, "finding project's top directory")
}
}
driver, err := m.getDriver(ctx, false)
if errors.Is(err, errNoDriver) {
return m.driverless(ctx)
}
if err != nil {
return errors.Wrap(err, "ensuring driver is up to date")
}
args := []string{"-fab", m.Fabdir, "-top", m.Topdir}
if m.Verbose {
args = append(args, "-v")
}
if m.List {
args = append(args, "-list")
}
if m.Force {
args = append(args, "-f")
}
if m.DryRun {
args = append(args, "-n")
}
args = append(args, m.Args...)
cmd := exec.CommandContext(ctx, driver, args...)
cmd.Dir = m.Topdir
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
err = cmd.Run()
return errors.Wrapf(err, "running %s %s", driver, strings.Join(args, " "))
}
var errNoDriver = errors.New("no driver")
func (m *Main) driverless(ctx context.Context) error {
if m.Verbose {
fmt.Println("Running in driverless mode")
}
con := NewController(m.Topdir)
if err := con.ReadYAMLFile(""); err != nil && !errors.Is(err, fs.ErrNotExist) {
return errors.Wrap(err, "reading YAML file")
}
if m.List {
con.ListTargets(os.Stdout)
return nil
}
ctx = WithVerbose(ctx, m.Verbose)
ctx = WithForce(ctx, m.Force)
ctx = WithDryRun(ctx, m.DryRun)
db, err := OpenHashDB(m.Fabdir)
if err != nil {
return errors.Wrap(err, "opening hash db")
}
defer db.Close()
ctx = WithHashDB(ctx, db)
targets, err := con.ParseArgs(m.Args)
if err != nil {
return errors.Wrap(err, "parsing args")
}
return con.Run(ctx, targets...)
}
var bolRegex = regexp.MustCompile("^")
// OpenHashDB ensures the given directory exists and opens (or creates) the hash DB there.
// Callers must make sure to call Close on the returned DB when finished with it.
func OpenHashDB(dir string) (*sqlite.DB, error) {
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, errors.Wrapf(err, "creating directory %s", dir)
}
dbfile := filepath.Join(dir, "hash.db")
db, err := sqlite.Open(dbfile, sqlite.Keep(30*24*time.Hour)) // keep db entries for 30 days
return db, errors.Wrapf(err, "opening file %s", dbfile)
}
const fabVersionBasename = "fab-version.json"
// TODO: Remove skipVersionCheck, which is here only to help an old test keep running.
// Update the test instead.
func (m *Main) getDriver(ctx context.Context, skipVersionCheck bool) (_ string, err error) {
pkgdir := filepath.Join(m.Topdir, "_fab")
_, err = os.Stat(pkgdir)
if errors.Is(err, fs.ErrNotExist) {
return "", errNoDriver
}
config := &packages.Config{
Mode: LoadMode,
Context: ctx,
Dir: pkgdir,
}
pkgs, err := packages.Load(config, ".")
if errors.Is(err, fs.ErrNotExist) {
return "", errNoDriver
}
if err != nil {
return "", errors.Wrapf(err, "loading %s", pkgdir)
}
if len(pkgs) == 0 {
return "", errNoDriver
}
if len(pkgs) != 1 {
return "", fmt.Errorf(
"loaded %d packages in %s, want 1 %v",
len(pkgs),
pkgdir,
slices.Map(pkgs, func(p *packages.Package) string { return p.PkgPath }),
)
}
pkg := pkgs[0]
if len(pkg.Errors) > 0 {
err = nil
for _, e := range pkg.Errors {
err = errors.Join(err, e)
}
return "", errors.Wrapf(err, "loading package %s", pkg.Name)
}
driverdir := filepath.Join(m.Fabdir, pkg.PkgPath)
if err = os.MkdirAll(driverdir, 0755); err != nil {
return "", errors.Wrapf(err, "ensuring directory %s/%s exists", m.Fabdir, pkg.PkgPath)
}
var (
hashfile = filepath.Join(driverdir, "hash")
driver = filepath.Join(driverdir, "fab.bin")
versionfile = filepath.Join(driverdir, fabVersionBasename)
compile bool
oldhash []byte
)
if m.Force {
compile = true
if m.Verbose {
fmt.Println("Forcing recompilation of driver")
}
} else {
_, err = os.Stat(driver)
if errors.Is(err, fs.ErrNotExist) {
compile = true
if m.Verbose {
fmt.Println("Compiling driver")
}
} else if err != nil {
return "", errors.Wrapf(err, "statting %s", driver)
}
}
var buildInfo *debug.BuildInfo
if !compile && !skipVersionCheck {
compile, buildInfo, err = m.checkVersion(versionfile)
if err != nil {
return "", errors.Wrap(err, "checking Fab version")
}
}
if !compile {
oldhash, err = os.ReadFile(hashfile)
if errors.Is(err, fs.ErrNotExist) {
compile = true
if m.Verbose {
fmt.Println("Compiling driver")
}
} else if err != nil {
return "", errors.Wrapf(err, "reading %s", hashfile)
}
}
dh := newDirHasher()
for _, filename := range pkg.GoFiles { // TODO: is this the right set of files?
if err = addFileToHash(dh, filename); err != nil {
return "", errors.Wrapf(err, "hashing file %s", filename)
}
}
newhash, err := dh.hash()
if err != nil {
return "", errors.Wrapf(err, "computing hash of directory %s", pkgdir)
}
if !compile {
if newhash == string(oldhash) {
if m.Verbose {
fmt.Println("Using existing driver")
}
} else {
compile = true
if m.Verbose {
fmt.Println("Recompiling driver")
}
}
}
if !compile {
return driver, nil
}
if err = CompilePackage(ctx, pkg, driver); err != nil {
return "", errors.Wrapf(err, "compiling driver %s", driver)
}
if err = os.WriteFile(hashfile, []byte(newhash), 0644); err != nil {
return "", errors.Wrapf(err, "writing %s", hashfile)
}
if buildInfo != nil {
v, err := os.OpenFile(versionfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return "", errors.Wrapf(err, "opening %s for writing", versionfile)
}
defer func() {
closeErr := v.Close()
if err == nil {
err = errors.Wrapf(closeErr, "closing %s", versionfile)
}
}()
enc := json.NewEncoder(v)
enc.SetIndent("", " ")
if err = enc.Encode(buildInfo); err != nil {
return "", errors.Wrap(err, "encoding build info")
}
}
return driver, nil
}
func (m *Main) checkVersion(versionfile string) (bool, *debug.BuildInfo, error) {
newInfo, ok := debug.ReadBuildInfo()
if !ok {
if m.Verbose {
fmt.Println("Could not read build info of running Fab process, will recompile driver")
}
_ = os.Remove(versionfile)
return true, nil, nil
}
f, err := os.Open(versionfile)
if errors.Is(err, fs.ErrNotExist) {
if m.Verbose {
fmt.Printf("No %s file, compiling driver\n", fabVersionBasename)
}
return true, newInfo, nil
}
if err != nil {
return false, nil, errors.Wrapf(err, "opening %s", versionfile)
}
defer f.Close()
var (
dec = json.NewDecoder(f)
oldInfo debug.BuildInfo
)
if err = dec.Decode(&oldInfo); err != nil {
if m.Verbose {
fmt.Printf("Error decoding %s, will recompile driver: %s\n", versionfile, err)
}
return true, newInfo, nil
}
if !reflect.DeepEqual(*newInfo, oldInfo) {
if m.Verbose {
fmt.Println("Fab build info changed, will recompile driver")
}
return true, newInfo, nil
}
return false, nil, nil
}
func addFileToHash(dh *dirHasher, filename string) error {
f, err := os.Open(filename)
if err != nil {
return errors.Wrapf(err, "opening %s", filename)
}
defer f.Close()
return dh.file(filename, f)
}