-
Notifications
You must be signed in to change notification settings - Fork 3
/
files.go
427 lines (365 loc) · 9.72 KB
/
files.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
package sync
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/crowdmob/goamz/s3"
"github.com/jessfraz/junk/budf/prompt"
diff "github.com/sergi/go-diff/diffmatchpatch"
)
type file struct {
Path string
LongPath string
Modtime time.Time
Shasum string
Content []byte
Mode os.FileMode
}
func (f *file) compare(bucket *s3.Bucket, remoteFile file) (err error) {
// if modtime is equal exit
if f.Modtime.Equal(remoteFile.Modtime) {
logrus.Debugf("Remote and local modtime for %s are the same.", f.Path)
return nil
}
// if shasums are equal exit
if f.sumsEqual(remoteFile.Shasum) {
logrus.Debugf("Remote and local shasums for %s are the same.", f.Path)
return nil
}
var (
recentString string
dfault string
after = f.Modtime.After(remoteFile.Modtime)
before = f.Modtime.Before(remoteFile.Modtime)
base = filepath.Base(f.Path)
isBashHistory = (base == ".bash_history")
)
// just concatenate bash history, if thats the file
if isBashHistory {
logrus.Debug("File is .bash_history so we are concatenating it.")
if err = f.showDiff(bucket, remoteFile, base, true); err != nil {
return fmt.Errorf("Show diff failed: %v", err)
}
return nil
}
if after {
recentString = fmt.Sprintf("Local %s is more recent than remote.", f.Path)
dfault = "l"
} else if before {
recentString = fmt.Sprintf("Remote %s is more recent than local.", f.Path)
dfault = "r"
}
// ask what they want to do
askString := recentString + `
Keep local (l)
Keep remote (r)
View and edit diff (d)
`
answer, err := prompt.Ask(askString, dfault)
if err != nil {
return fmt.Errorf("Ask prompt failed: %v", err)
}
switch answer {
case "l":
// keep the localfile
// get the contents of the localfile
f.Content, err = ioutil.ReadFile(f.LongPath)
if err != nil {
return fmt.Errorf("Error reading local file %q: %v", f.LongPath, err)
}
// push to s3
if err := f.uploadToS3(bucket, remoteFile.LongPath, f.Content); err != nil {
return err
}
case "r":
// keep the remote file
// get the contents of the remote file
remoteFile.Content, err = bucket.Get(remoteFile.LongPath)
if err != nil {
return fmt.Errorf("Error getting %q from s3: %v", remoteFile.LongPath, err)
}
// write it to the localfile
if err := ioutil.WriteFile(f.LongPath, remoteFile.Content, f.Mode); err != nil {
return err
}
logrus.Infof("Updated %s locally", f.Path)
case "d":
// show the diff
err = f.showDiff(bucket, remoteFile, base, false)
if err != nil {
return fmt.Errorf("Show diff failed: %v", err)
}
default:
return fmt.Errorf("what da fuck: %q is an invalid answer", answer)
}
return nil
}
func getIgnoredFiles() (patterns []string, err error) {
ignorePath := path.Join(home, ".s3ignore")
if _, err := os.Stat(ignorePath); os.IsNotExist(err) {
return patterns, nil
}
file, err := ioutil.ReadFile(ignorePath)
if err != nil {
return patterns, err
}
dirtyFiles := strings.Split(string(file), "\n")
// clean patterns
for _, pattern := range dirtyFiles {
pattern = strings.TrimRight(strings.TrimSpace(pattern), "/*")
if pattern == "" {
continue
}
pattern = filepath.Clean(pattern)
patterns = append(patterns, pattern)
}
return patterns, nil
}
func walkLocalFilesFn(filePath string, info os.FileInfo, err error) error {
relFilePath, err := filepath.Rel(home, filePath)
if err != nil || (filePath == home && info.IsDir()) {
// Error getting relative path OR we are looking
// at the root path. Skip in both situations.
return nil
}
if !strings.HasPrefix(relFilePath, ".") {
return nil
}
// see if matches ignored files
skip, err := matches(relFilePath, ignore)
if err != nil {
logrus.Warnf("Error matching %s: %v", relFilePath, err)
return err
}
if skip {
// only skip dir if it is not also a symlink
if info.IsDir() && info.Mode()&os.ModeSymlink == 0 {
return filepath.SkipDir
}
return nil
}
// get if it is NOT a symlink
if info.Mode()&os.ModeSymlink == 0 {
if info.IsDir() {
return nil
}
localFiles = append(localFiles, file{
Path: relFilePath,
LongPath: filePath,
Modtime: info.ModTime(),
Mode: info.Mode(),
})
return nil
}
// handle the case where we have a symlink
// get the real file path
var linkPath string
if linkPath, err = os.Readlink(filePath); err != nil {
logrus.Errorf("Getting symlinked file for %s failed: %v", relFilePath, err)
return err
}
// get the real stat of the symlink
if info, err = os.Lstat(linkPath); err != nil {
return err
}
if !info.IsDir() {
// add file symlink to array
localFiles = append(localFiles, file{
Path: relFilePath,
LongPath: linkPath,
Modtime: info.ModTime(),
Mode: info.Mode(),
})
return nil
}
// if symlink is a dir follow it recursively
// get the home relative to the link dir
linkhome, _ := filepath.Split(linkPath)
// create recursive walk function
walkRecursiveFn := func(rPath string, i os.FileInfo, err error) error {
// get the relative filepath
relFilePath, err := filepath.Rel(linkhome, rPath)
if err != nil || (rPath == linkPath && i.IsDir()) {
// Error getting relative path OR we are looking
// at the root path. Skip in both situations.
return nil
}
// see if matches ignored files
skip, err := matches(relFilePath, ignore)
if err != nil {
logrus.Warnf("Error matching %s: %v", relFilePath, err)
return err
}
if skip {
// only skip dir if it is not also a symlink
if i.IsDir() && i.Mode()&os.ModeSymlink == 0 {
return filepath.SkipDir
}
return nil
}
if i.IsDir() {
return nil
}
localFiles = append(localFiles, file{
Path: relFilePath,
LongPath: rPath,
Modtime: i.ModTime(),
Mode: i.Mode(),
})
return nil
}
// walk the symlink path
if err := filepath.Walk(linkPath, walkRecursiveFn); err != nil {
return fmt.Errorf("Recursive walkLocalFiles failed on path %s for link %s: %v", filePath, linkPath, err)
}
return nil
}
func getRemoteFiles(bucket *s3.Bucket, bucketpath, marker string, ignore []string) (files []file, err error) {
resp, err := bucket.List(bucketpath, "\n", marker, 1000)
if err != nil {
return files, err
}
// clean files
for _, f := range resp.Contents {
if strings.HasSuffix(f.Key, "/") {
continue
}
relFilePath, err := filepath.Rel(bucketpath, f.Key)
if err != nil {
return files, nil
}
if !strings.HasPrefix(relFilePath, ".") {
continue
}
skip, err := matches(relFilePath, ignore)
if err != nil {
logrus.Warnf("Error matching %s: %v", relFilePath, err)
continue
}
if skip {
continue
}
// parse time
modtime, err := time.Parse("2006-01-02T15:04:05.000Z", f.LastModified)
if err != nil {
logrus.Warnf("Error parsing time string %q: %v", f.LastModified, err)
continue
}
files = append(files, file{
Path: relFilePath,
LongPath: f.Key,
Modtime: modtime,
Shasum: strings.Trim(f.ETag, `"`),
})
}
// recursively get more files
if resp.IsTruncated {
morefiles, err := getRemoteFiles(bucket, bucketpath, resp.NextMarker, ignore)
if err != nil {
return files, err
}
files = append(files, morefiles...)
}
return files, nil
}
func (f *file) sumsEqual(shasum string) bool {
// get the shasum of the file
var err error
f.Shasum, err = hexMd5Sum(f.LongPath)
if err != nil {
logrus.Warnf("Error getting shasum of %s: %v", f.Path, err)
// return true because we won't want to sync a file with an error
// and its most likely a directory
return true
}
// compare shasum to remotefile
if f.Shasum != shasum {
logrus.Debugf("Local sum is %s and remote sum is %s for %s", f.Shasum, shasum, f.Path)
return false
}
logrus.Debugf("Shasums match for %s", f.Path)
return true
}
func (f file) showDiff(bucket *s3.Bucket, remoteFile file, base string, concat bool) (err error) {
// get the contents of the remote file
remoteFile.Content, err = bucket.Get(remoteFile.LongPath)
if err != nil {
return fmt.Errorf("Error getting %q from s3: %v", remoteFile.LongPath, err)
}
// get the contents of the localfile
f.Content, err = ioutil.ReadFile(f.LongPath)
if err != nil {
return fmt.Errorf("Error reading local file %q: %v", f.LongPath, err)
}
tmp, err := ioutil.TempFile("", "tempfile-"+base)
if err != nil {
return err
}
defer os.Remove(tmp.Name())
// get the diff
diffPatch := diff.New()
diffs := diffPatch.DiffMain(string(remoteFile.Content), string(f.Content), false)
for _, d := range diffs {
var c string
switch d.Type {
case diff.DiffEqual:
c = ""
case diff.DiffInsert:
c = ">>> + "
case diff.DiffDelete:
c = ">>> - "
}
// if its bash history we just want to add everything
if concat {
c = ""
}
if _, err := io.WriteString(tmp, fmt.Sprintf("%s%s", c, d.Text)); err != nil {
return err
}
}
if !concat {
// open the editor
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "nano"
}
cmd := exec.Command(editor, tmp.Name())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
}
if _, err := tmp.Seek(0, 0); err != nil {
return err
}
// get the changes
contents, err := ioutil.ReadAll(tmp)
if err != nil {
return err
}
// save the file locally
if err := ioutil.WriteFile(f.LongPath, contents, f.Mode); err != nil {
return err
}
logrus.Infof("Updated %s locally", f.Path)
// upload to s3
err = f.uploadToS3(bucket, remoteFile.LongPath, contents)
return err
}
func (f file) uploadToS3(bucket *s3.Bucket, s3Filepath string, contents []byte) error {
// push the file to s3
if err := bucket.Put(s3Filepath, contents, "", "private", s3.Options{}); err != nil {
return err
}
logrus.Infof("Pushed %s to s3", f.Path)
return nil
}