This repository has been archived by the owner on Mar 26, 2022. It is now read-only.
forked from gyepisam/redux
/
file.go
296 lines (237 loc) · 6.87 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
// 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"
"os"
"path/filepath"
"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
PathHash Hash // SHA1 hash of Path. Used as database key.
DoFile string // Do script used to generate target output.
Config Config
db DB
IsTaskFlag bool // If true, target is a task and run for side effects
}
// IsTask denotes when the current target is a task script, either
// implicitly (name begins with @) or explicitly (-task argument to redo).
func (f *File) IsTask() bool {
return f.IsTaskFlag || len(f.Name) > 0 && f.Name[0] == TASK_PREFIX
}
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.Debug("@Hash %s: %s -> %s\n", f.RootDir, f.Path, f.PathHash)
f.Dir, f.Name = splitpath(f.Fullpath())
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
}
} 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 == nil || !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)
}