forked from prasmussen/gdrive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_download.go
328 lines (264 loc) · 8.62 KB
/
sync_download.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
package drive
import (
"bytes"
"fmt"
"google.golang.org/api/drive/v3"
"google.golang.org/api/googleapi"
"io"
"os"
"path/filepath"
"sort"
"time"
)
type DownloadSyncArgs struct {
Out io.Writer
Progress io.Writer
RootId string
Path string
DryRun bool
DeleteExtraneous bool
Timeout time.Duration
Resolution ConflictResolution
Comparer FileComparer
}
func (self *Drive) DownloadSync(args DownloadSyncArgs) error {
fmt.Fprintln(args.Out, "Starting sync...")
started := time.Now()
// Get remote root dir
rootDir, err := self.getSyncRoot(args.RootId)
if err != nil {
return err
}
fmt.Fprintln(args.Out, "Collecting file information...")
files, err := self.prepareSyncFiles(args.Path, rootDir, args.Comparer)
if err != nil {
return err
}
// Find changed files
changedFiles := files.filterChangedRemoteFiles()
fmt.Fprintf(args.Out, "Found %d local files and %d remote files\n", len(files.local), len(files.remote))
// Ensure that we don't overwrite any local changes
if args.Resolution == NoResolution {
err = ensureNoLocalModifications(changedFiles)
if err != nil {
return fmt.Errorf("Conflict detected!\nThe following files have changed and the local file are newer than it's remote counterpart:\n\n%s\nNo conflict resolution was given, aborting...", err)
}
}
// Create missing directories
err = self.createMissingLocalDirs(files, args)
if err != nil {
return err
}
// Download missing files
err = self.downloadMissingFiles(files, args)
if err != nil {
return err
}
// Download files that has changed
err = self.downloadChangedFiles(changedFiles, args)
if err != nil {
return err
}
// Delete extraneous local files
if args.DeleteExtraneous {
err = self.deleteExtraneousLocalFiles(files, args)
if err != nil {
return err
}
}
fmt.Fprintf(args.Out, "Sync finished in %s\n", time.Since(started))
return nil
}
func (self *Drive) getSyncRoot(rootId string) (*drive.File, error) {
fields := []googleapi.Field{"id", "name", "mimeType", "appProperties"}
f, err := self.service.Files.Get(rootId).Fields(fields...).Do()
if err != nil {
return nil, fmt.Errorf("Failed to find root dir: %s", err)
}
// Ensure file is a directory
if !isDir(f) {
return nil, fmt.Errorf("Provided root id is not a directory")
}
// Ensure directory is a proper syncRoot
if _, ok := f.AppProperties["syncRoot"]; !ok {
return nil, fmt.Errorf("Provided id is not a sync root directory")
}
return f, nil
}
func (self *Drive) createMissingLocalDirs(files *syncFiles, args DownloadSyncArgs) error {
missingDirs := files.filterMissingLocalDirs()
missingCount := len(missingDirs)
if missingCount > 0 {
fmt.Fprintf(args.Out, "\n%d local directories are missing\n", missingCount)
}
// Sort directories so that the dirs with the shortest path comes first
sort.Sort(byRemotePathLength(missingDirs))
for i, rf := range missingDirs {
absPath, err := filepath.Abs(filepath.Join(args.Path, rf.relPath))
if err != nil {
return fmt.Errorf("Failed to determine local absolute path: %s", err)
}
fmt.Fprintf(args.Out, "[%04d/%04d] Creating directory %s\n", i+1, missingCount, filepath.Join(filepath.Base(args.Path), rf.relPath))
if args.DryRun {
continue
}
os.MkdirAll(absPath, 0775)
}
return nil
}
func (self *Drive) downloadMissingFiles(files *syncFiles, args DownloadSyncArgs) error {
missingFiles := files.filterMissingLocalFiles()
missingCount := len(missingFiles)
if missingCount > 0 {
fmt.Fprintf(args.Out, "\n%d local files are missing\n", missingCount)
}
for i, rf := range missingFiles {
absPath, err := filepath.Abs(filepath.Join(args.Path, rf.relPath))
if err != nil {
return fmt.Errorf("Failed to determine local absolute path: %s", err)
}
fmt.Fprintf(args.Out, "[%04d/%04d] Downloading %s -> %s\n", i+1, missingCount, rf.relPath, filepath.Join(filepath.Base(args.Path), rf.relPath))
err = self.downloadRemoteFile(rf.file.Id, absPath, args, 0)
if err != nil {
return err
}
}
return nil
}
func (self *Drive) downloadChangedFiles(changedFiles []*changedFile, args DownloadSyncArgs) error {
changedCount := len(changedFiles)
if changedCount > 0 {
fmt.Fprintf(args.Out, "\n%d remote files has changed\n", changedCount)
}
for i, cf := range changedFiles {
if skip, reason := checkLocalConflict(cf, args.Resolution); skip {
fmt.Fprintf(args.Out, "[%04d/%04d] Skipping %s (%s)\n", i+1, changedCount, cf.remote.relPath, reason)
continue
}
absPath, err := filepath.Abs(filepath.Join(args.Path, cf.remote.relPath))
if err != nil {
return fmt.Errorf("Failed to determine local absolute path: %s", err)
}
fmt.Fprintf(args.Out, "[%04d/%04d] Downloading %s -> %s\n", i+1, changedCount, cf.remote.relPath, filepath.Join(filepath.Base(args.Path), cf.remote.relPath))
err = self.downloadRemoteFile(cf.remote.file.Id, absPath, args, 0)
if err != nil {
return err
}
}
return nil
}
func (self *Drive) downloadRemoteFile(id, fpath string, args DownloadSyncArgs, try int) error {
if args.DryRun {
return nil
}
// Get timeout reader wrapper and context
timeoutReaderWrapper, ctx := getTimeoutReaderWrapperContext(args.Timeout)
res, err := self.service.Files.Get(id).Context(ctx).Download()
if err != nil {
if isBackendOrRateLimitError(err) && try < MaxErrorRetries {
exponentialBackoffSleep(try)
try++
return self.downloadRemoteFile(id, fpath, args, try)
} else if isTimeoutError(err) {
return fmt.Errorf("Failed to download file: timeout, no data was transferred for %v", args.Timeout)
} else {
return fmt.Errorf("Failed to download file: %s", err)
}
}
// Close body on function exit
defer res.Body.Close()
// Wrap response body in progress reader
progressReader := getProgressReader(res.Body, args.Progress, res.ContentLength)
// Wrap reader in timeout reader
reader := timeoutReaderWrapper(progressReader)
// Ensure any parent directories exists
if err = mkdir(fpath); err != nil {
return err
}
// Download to tmp file
tmpPath := fpath + ".incomplete"
// Create new file
outFile, err := os.Create(tmpPath)
if err != nil {
return fmt.Errorf("Unable to create local file: %s", err)
}
// Save file to disk
_, err = io.Copy(outFile, reader)
if err != nil {
outFile.Close()
if try < MaxErrorRetries {
exponentialBackoffSleep(try)
try++
return self.downloadRemoteFile(id, fpath, args, try)
} else {
os.Remove(tmpPath)
return fmt.Errorf("Download was interrupted: %s", err)
}
}
// Close file
outFile.Close()
// Rename tmp file to proper filename
return os.Rename(tmpPath, fpath)
}
func (self *Drive) deleteExtraneousLocalFiles(files *syncFiles, args DownloadSyncArgs) error {
extraneousFiles := files.filterExtraneousLocalFiles()
extraneousCount := len(extraneousFiles)
if extraneousCount > 0 {
fmt.Fprintf(args.Out, "\n%d local files are extraneous\n", extraneousCount)
}
// Sort files so that the files with the longest path comes first
sort.Sort(sort.Reverse(byLocalPathLength(extraneousFiles)))
for i, lf := range extraneousFiles {
fmt.Fprintf(args.Out, "[%04d/%04d] Deleting %s\n", i+1, extraneousCount, lf.absPath)
if args.DryRun {
continue
}
err := os.Remove(lf.absPath)
if err != nil {
return fmt.Errorf("Failed to delete local file: %s", err)
}
}
return nil
}
func checkLocalConflict(cf *changedFile, resolution ConflictResolution) (bool, string) {
// No conflict unless local file was last modified
if cf.compareModTime() != LocalLastModified {
return false, ""
}
// Don't skip if want to keep the remote file
if resolution == KeepRemote {
return false, ""
}
// Skip if we want to keep the local file
if resolution == KeepLocal {
return true, "conflicting file, keeping local file"
}
if resolution == KeepLargest {
largest := cf.compareSize()
// Skip if the local file is largest
if largest == LocalLargestSize {
return true, "conflicting file, local file is largest, keeping local"
}
// Don't skip if the remote file is largest
if largest == RemoteLargestSize {
return false, ""
}
// Keep local if both files have the same size
if largest == EqualSize {
return true, "conflicting file, file sizes are equal, keeping local"
}
}
// The conditionals above should cover all cases,
// unless the programmer did something wrong,
// in which case we default to being non-destructive and skip the file
return true, "conflicting file, unhandled case"
}
func ensureNoLocalModifications(files []*changedFile) error {
conflicts := findLocalConflicts(files)
if len(conflicts) == 0 {
return nil
}
buffer := bytes.NewBufferString("")
formatConflicts(conflicts, buffer)
return fmt.Errorf(buffer.String())
}