/
file.go
369 lines (296 loc) · 8.51 KB
/
file.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
// Copyright 2014 Gyepi Sam. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package redux
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/gyepisam/fileutils"
)
// File represents a source or target file..
type File struct {
Target string // file name argument to redo, redo-ifchange, redo-ifcreate, etc
RootDir string // contains .redo directory
Path string // Relative to RootDir
Dir string
Name string
Ext string // File extension. Could be empty. Includes preceding dot.
PathHash Hash // SHA1 hash of Path. Used as database key.
FullPathHash Hash //SHA1 hash of RootDir/Path. Used for loop detection.
DoFile string // Do script used to generate target output.
Config Config
db DB
isTask bool // If true, target is a task and run for side effects
}
// IsTask denotes when the current target is a task script, either
// explicitly (-task argument to redo) or
// implicitly (name begins with @ or name is default task).
func (f *File) IsTask() bool {
return f.isTask
}
func (f *File) SetTaskFlag(isTask bool) {
if isTask {
f.isTask = isTask
} else {
base := filepath.Base(f.Name)
f.isTask = strings.HasPrefix(base, TASK_PREFIX) || DEFAULT_TARGET == base
}
}
func splitpath(path string) (string, string) {
return filepath.Dir(path), filepath.Base(path)
}
// NewFile creates and returns a File instance for the given path.
// If the path is not fully qualified, it is made relative to dir.
// The newly created instance is initialized with the database specified by
// the configuration file found in its root directory or the default database.
// If a file does not have a root directory, it is initialized with a NullDb
// and HasNullDb will return true.
func NewFile(dir, path string) (f *File, err error) {
if path == "" {
return nil, errors.New("target path cannot be empty")
}
var targetPath string
if filepath.IsAbs(path) {
targetPath = path
} else {
targetPath = filepath.Clean(filepath.Join(dir, path))
}
if isdir, err := fileutils.IsDir(targetPath); err != nil {
return nil, err
} else if isdir {
return nil, fmt.Errorf("target %s is a directory", targetPath)
}
f = new(File)
f.Target = path
rootDir, filename := splitpath(targetPath)
relPath := &RelPath{}
relPath.Add(filename)
hasRoot := false
for {
exists, err := fileutils.DirExists(filepath.Join(rootDir, REDO_DIR))
if err != nil {
return nil, err
}
if exists {
hasRoot = true
break
}
if rootDir == "/" || rootDir == "." {
break
}
rootDir, filename = splitpath(rootDir)
relPath.Add(filename)
}
f.RootDir = rootDir
f.Path = relPath.Join()
f.PathHash = MakeHash(f.Path)
f.FullPathHash = MakeHash(filepath.Join(f.RootDir, f.Path))
f.Debug("@Hash %s: %s -> %s\n", f.RootDir, f.Path, f.PathHash)
f.Dir, f.Name = splitpath(f.Fullpath())
f.Ext = filepath.Ext(f.Name)
if hasRoot {
// TODO(gsam): Read config file in rootDir to determine DB type, if any.
// Default to FileDB if not specified.
// f.Config = Config{DBType: "file"}
f.db, err = FileDbOpen(f.RootDir)
if err != nil {
return nil, err
}
err := os.Mkdir(f.tempDir(), 0755)
if err != nil && !os.IsExist(err) {
return nil, err
}
} else {
f.Config = Config{DBType: "null"}
f.db, err = NullDbOpen("")
if err != nil {
return nil, err
}
f.Debug("@NullDb\n")
}
return
}
// HasNullDb specifies whether the File receiver uses a NullDb.
func (f *File) HasNullDb() bool {
return f.db.IsNull()
}
// Fullpath returns the fully qualified path to the target file.
func (f *File) Fullpath() string {
return filepath.Join(f.RootDir, f.Path)
}
// Rel makes path relative to f.RootDir.
func (f *File) Rel(path string) string {
relpath, err := filepath.Rel(f.RootDir, path)
if err != nil {
panic(err)
}
return filepath.Clean(relpath)
}
// Abs returns a cleaned up fullpath by joining f.RootDir to path.
func (f *File) Abs(path string) string {
if filepath.IsAbs(path) {
return path
}
return filepath.Clean(filepath.Join(f.RootDir, path))
}
// Exist verifies that the file exists on disk.
func (f *File) Exists() (bool, error) {
return fileutils.FileExists(f.Fullpath())
}
// HasDoFile returns true if the receiver has been assigned a .do script.
func (f *File) HasDoFile() bool {
return len(f.DoFile) > 0
}
// IsCurrent returns a boolean denoting whether the target is up to date.
// A target is up to date if the following conditions hold:
// The file exists
// The file has not been flagged to be rebuilt
// The file has not changed since creation. That is; the file has a metadata record
// and that record matches the actual file metadata.
// All the file's prerequisites are also current.
func (f *File) IsCurrent() (bool, error) {
return f.isCurrent()
}
func (f *File) isCurrent() (bool, error) {
reason := func(msg string) (bool, error) {
f.Debug("@Outdated because %s\n", msg)
return false, nil
}
if f.MustRebuild() {
return reason("REBUILD")
}
storedMeta, found, err := f.GetMetadata()
if err != nil {
return false, err
} else if !found {
return reason("no record metadata")
}
fileMeta, err := f.NewMetadata()
if err != nil {
return false, err
} else if fileMeta == nil {
return reason("no file metadata")
}
if !storedMeta.Equal(fileMeta) {
return reason("record metadata != file metadata")
}
// redo-ifcreate dependencies
created, err := f.PrerequisiteFiles(IFCREATE, AUTO_IFCREATE)
if err != nil {
return false, err
}
for _, prerequisite := range created {
if exists, err := prerequisite.Exists(); err != nil {
return false, err
} else if exists {
return reason("ifcreate dependency target exists")
}
}
// redo-ifchange dependencies
changed, err := f.Prerequisites(IFCHANGE, AUTO_IFCHANGE)
if err != nil {
return false, err
}
for _, prerequisite := range changed {
if isCurrent, err := prerequisite.IsCurrent(f.RootDir); err != nil || !isCurrent {
return isCurrent, err
}
}
return true, nil
}
// NewMetadata computes and returns the file metadata.
func (f *File) NewMetadata() (m *Metadata, err error) {
m, err = NewMetadata(f.Fullpath(), f.Path)
if m == nil || err == nil {
return
}
if len(f.DoFile) > 0 {
if path, err := filepath.Rel(f.RootDir, f.DoFile); err != nil {
m.DoFile = f.DoFile
} else {
m.DoFile = path
}
}
return
}
// ContentHash returns a cryptographic hash of the file contents.
func (f *File) ContentHash() (Hash, error) {
return ContentHash(f.Fullpath())
}
// Log prints out messages to stderr when the verbosity is greater than N.
func (f *File) Log(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
}
// Debug prints out messages to stderr when the debug flag is enabled.
func (f *File) Debug(format string, args ...interface{}) {
if Debug {
for i, value := range args {
if value == nil {
args[i] = "<nil>"
}
}
fmt.Fprintf(os.Stderr, "%s %s: ", os.Args[0], f.Target)
fmt.Fprintf(os.Stderr, format, args...)
}
}
func (f *File) GenerateNotifications(oldMeta, newMeta *Metadata) error {
if oldMeta == nil {
if err := f.NotifyDependents(IFCREATE); err != nil {
return err
}
}
if !newMeta.Equal(oldMeta) {
if err := f.NotifyDependents(IFCHANGE); err != nil {
return err
}
}
return nil
}
// RedoDir returns the path to the .redo directory.
func (f *File) RedoDir() string {
return filepath.Join(f.RootDir, REDO_DIR)
}
func (f *File) tempDir() string {
if s := os.Getenv("REDO_TMP_DIR"); len(s) > 0 {
return s
}
return filepath.Join(f.RedoDir(), "tmp")
}
func (f *File) tempFile() (*os.File, error) {
return ioutil.TempFile(f.tempDir(), strings.Replace(f.Name, ".", "-", -1)+"-redo-tmp-")
}
// DoInfoCandidates generates a list of possible do filenames for this file
func (f *File) DoInfoCandidates() []*DoInfo {
const sep = `.`
parts := strings.Split(f.Name, sep)
n := len(parts)
if n == 0 {
return nil
}
// +1 for default.do
out := make([]*DoInfo, n+1)
add := func(index int, basename string, exts, arg2 []string) {
a := make([]string, len(exts)+2)
a[0] = basename
copy(a[1:], exts)
a[len(a)-1] = DO_EXT
out[index] = &DoInfo{Name: strings.Join(a, sep), Arg2: strings.Join(arg2, sep)}
}
add(0, parts[0], parts[1:n], parts[0:n]) // target.(ext\.)*do
for i := 1; i < len(out); i++ {
add(i, DO_BASENAME, parts[i:n], parts[0:i])
}
return out
}
// NewOutput returns an initialized Output
func (f *File) NewOutput() (*Output, error) {
tmp, err := f.tempFile()
if err != nil {
return nil, err
}
return NewOutput(tmp), nil
}