-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.py
More file actions
executable file
·459 lines (420 loc) · 16.5 KB
/
sync.py
File metadata and controls
executable file
·459 lines (420 loc) · 16.5 KB
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
#!/usr/bin/env python
# encoding: utf-8
"""
filesync.sync
Created by Brennan Chapman and Bohdon Sayre on 2012-08-07.
Copyright (c) 2012 Moonbot Studios. All rights reserved.
"""
import os, stat, re, time, sys
import shutil, filecmp
import logging
from diff import Diff
from utils import *
try:
import mbotenv
LOG = mbotenv.get_logger(__name__)
ROOTLOG = mbotenv.get_logger()
except:
import logging
LOG = logging.getLogger(__name__)
ROOTLOG = mbotenv.get_logger()
ROOTLOG.indent = 0
__all__ = [
'FileSyncError',
'Sync',
'Diff',
]
class Sync(object):
"""
Sync is a class for synchronizing or updating one directory with another.
The class operates one directionally, so a true sync would require multiple
Syncs that do not purge files.
Optionally, a file path list can be supplied to limit the sync between
the src and dst. This file list can either be relative paths or include
the src or dst prefixes in their file paths.
The basic setup is to pass a src and dst path then run the ``diff`` method.
This will generate a Diff instance that will provide information about
which files would be created/updated/purged if the sync was run. The diff
can then be trimmed using ``difftrim``. Once the difference reflects the
desired changes, run the ``sync`` or ``update`` methods depending on if
files/dirs should be created and updated, or only updated.
TODO: describe the diff settings and run settings here
"""
def __init__(self, src=None, dst=None, **kwargs):
self.src = None if src is None else os.path.normpath(src)
self.dst = None if dst is None else os.path.normpath(dst)
self.origdiff = None
self.trimdiff = None
self.ops = ['create', 'update', 'purge']
self.diffstngs = {
'filters':[],
'excludes':['.DS_Store','Thumbs.db','.place-holder'],
'filelist':[],
'regexfilters':False,
'includedirs':True,
'timeprecision':3,
'recursive':True,
'newer':True,
'forceUpdate':False,
'sizeLimit':0,
}
self.runstngs = {
'maketarget':True,
'trimmed':True,
'create':False,
'update':False,
'purge':False,
'forceOwnership':False,
'errorsToDebug':False,
}
self.progressfnc = None
self.progresscheck = None
self.progressamt = 0
self.stats = {
'stime':0.0,
'etime':0.0,
'creates':[],
'createfails':[],
'updates':[],
'updatefails':[],
'purges':[],
'purgefails':[],
}
self.__hasrun = False
self.__hasrundiff = False
self.__diffcurrent = False
for k, v in kwargs.items():
if k in self.diffstngs.keys():
self.diffstngs[k] = v
elif k in self.runstngs.keys():
self.runstngs[k] = v
def getopts(self):
"""
Return a list of options and their values
"""
result = {}
for k in self.diffstngs.keys():
result[k] = self.diffstngs[k]
for k in self.runstngs.keys():
result[k] = self.runstngs[k]
return result
def __validate(self):
if self.src is None or self.dst is None:
return False
return True
def diff(self, **kwargs):
"""
Compile a difference list of files between src and dst directories
"""
if self.__validate():
# TODO: filter kwargs
self.diffstngs.update(kwargs)
self.origdiff = Diff(self.src, self.dst, **self.diffstngs)
self.trimdiff = self.origdiff.copy()
self.__hasrundiff = True
self.__diffcurrent = True
def difftrim(self, create=[], update=[], purge=[]):
"""
Removes items from ``origdiff`` and saves the results in ``trimdiff``
``create`` -- a list of full paths to remove from the create diff list
``update`` -- a list of full paths to remove from the update diff list
``purge`` -- a list of full paths to remove from the purge diff list
"""
for path in create:
self.trimdiff.remove_create(path)
for path in update:
self.trimdiff.remove_update(path)
for path in purge:
self.trimdiff.remove_purge(path)
def sync(self, refreshDiff=False, dry_run=False, **kwargs):
"""
Copy any new files and update any existing files from src to dst
directories using the compiled dirdiff list
"""
self.runstngs['create'] = True
self.runstngs['update'] = True
self.runstngs.update(kwargs)
self.run(refreshDiff=refreshDiff, dry_run=dry_run)
def update(self, refreshDiff=False, dry_run=False, **kwargs):
"""
Update only files that already exist in both src and dst
"""
self.runstngs['create'] = False
self.runstngs['update'] = True
self.runstngs.update(kwargs)
self.run(refreshDiff=refreshDiff, dry_run=dry_run)
def run(self, refreshDiff=False, dry_run=False, **kwargs):
"""
Run the directory sync given the current run settings
``refreshDiff`` -- re-runs diff() after syncing
"""
try:
if kwargs.has_key('no_update'):
LOG.warning('Filesync Deprecation Warning: \'no_update\' is no longer supported, use \'refreshDiff\' instead')
refreshDiff = not kwargs['no_update']
if not self.__diffcurrent:
LOG.warning('diff is not current; it\'s recommended to run diff again before updating/synching')
self.stats['stime'] = time.time()
self.__run(dry_run=dry_run)
self.stats['etime'] = time.time()
self.__hasrun = True
self.__diffcurrent = False
if refreshDiff:
self.diff()
except:
LOG.exception("Exception running filesync")
def __run(self, dry_run=False):
# reset stats
self.stats['creates'] = []
self.stats['createfails'] = []
self.stats['updates'] = []
self.stats['updatefails'] = []
self.stats['purges'] = []
self.stats['purgefails'] = []
# determine the diff to use (trimmed or untrimmed)
d = self.trimdiff if self.runstngs['trimmed'] else self.origdiff
if d is None:
return
return self.runwithdiff(d, dry_run)
def runwithdiff(self, diff, dry_run=False):
if not isinstance(diff, Diff):
raise TypeError('expected Diff, got {0}'.format(type(diff).__name__))
# run through all 'create' files
if self.runstngs['create']:
LOG.debug('Creating')
if LOG.getEffectiveLevel() <= logging.DEBUG:
ROOTLOG.indent += 1
items = sorted(diff.create.items())
for path, files in items:
if self.progresscheck is not None:
if not self.progresscheck():
return
relpath = os.path.relpath(path, self.src)
if relpath == '.':
relpath = ''
srcdir = os.path.join(self.src, relpath)
dstdir = os.path.join(self.dst, relpath)
# make the destination dir if it doesn't exist
if not os.path.isdir(dstdir):
self.__makedirs(dstdir, self.stats['creates'], self.stats['createfails'], dry_run)
for f in files:
srcp = os.path.join(srcdir, f)
dstp = os.path.join(dstdir, f)
if os.path.isdir(srcp):
self.__copydir(srcp, dstp, self.stats['creates'], self.stats['createfails'], dry_run)
elif os.path.isfile(srcp):
self.__copy(srcp, dstp, self.stats['creates'], self.stats['createfails'], dry_run)
if LOG.getEffectiveLevel() <= logging.DEBUG:
ROOTLOG.indent -= 1
# run through all 'update' files
if self.runstngs['update']:
LOG.debug('Updating')
if LOG.getEffectiveLevel() <= logging.DEBUG:
ROOTLOG.indent += 1
items = sorted(diff.update.items())
for path, files in items:
if self.progresscheck is not None:
if not self.progresscheck():
return
relpath = os.path.relpath(path, self.src)
if relpath == '.':
relpath = ''
srcdir = os.path.join(self.src, relpath)
dstdir = os.path.join(self.dst, relpath)
for f in files:
# updates never include dirs
srcp = os.path.join(srcdir, f)
dstp = os.path.join(dstdir, f)
self.__copy(srcp, dstp, self.stats['updates'], self.stats['updatefails'], dry_run)
if LOG.getEffectiveLevel() <= logging.DEBUG:
ROOTLOG.indent -= 1
# run through all 'purge' files
if self.runstngs['purge']:
LOG.debug('Purging')
if LOG.getEffectiveLevel() <= logging.DEBUG:
ROOTLOG.indent += 1
items = sorted(diff.purge.items())
for path, files in items:
if self.progresscheck is not None:
if not self.progresscheck():
return
relpath = os.path.relpath(path, self.dst)
if relpath == '.':
relpath = ''
dstdir = os.path.join(self.dst, relpath)
for f in files:
dstp = os.path.join(dstdir, f)
if os.path.isdir(dstp):
self.__rmdir(dstp, self.stats['purges'], self.stats['purgefails'], dry_run)
elif os.path.isfile(dstp):
self.__remove(dstp, self.stats['purges'], self.stats['purgefails'], dry_run)
else:
LOG.debug('file/folder not found: {0}'.format(dstp))
if LOG.getEffectiveLevel() <= logging.DEBUG:
ROOTLOG.indent -= 1
if self.progressfnc:
self.progressfnc("Sync Complete", 100)
def __makedirs(self, dir_, passes=None, fails=None, dry_run=False):
"""
Make the given dir_ including any parent dirs
Append dir_ to ``fails`` on error
"""
try:
os.makedirs(dir_)
except Exception as e:
LOG.error(e)
if fails is not None:
fails.append(dir_)
else:
if passes is not None:
passes.append(dir_)
LOG.debug('made dirs: {0}'.format(dir_))
def __getProgPercent(self):
"""
Get a progress percentage and return it.
"""
self.progressamt += 1
return float(self.progressamt) / float(self.origdiff.totalcount) * 100
def __copydir(self, src, dst, passes=None, fails=None, dry_run=False):
"""
Make the given dst directory and copy stats from src
Append dst to ``fails`` on error
"""
if self.progressfnc:
self.progressfnc('Copying to {0}'.format(dst), self.__getProgPercent())
try:
if not dry_run:
os.mkdir(dst)
except Exception as e:
LOG.error(e)
if fails is not None:
fails.append(dst)
else:
if os.path.exists(dst) and self.runstngs['forceOwnership']:
# make writable
fileAtt = os.stat(dst)[0]
if (not fileAtt & stat.S_IWRITE):
try:
os.chmod(dst, stat.S_IWRITE)
except Exception as e:
LOG.error('could not make file writable {0}: {1}'.format(dst, e))
return False
shutil.copystat(src, dst)
if passes is not None:
passes.append(dst)
LOG.debug('Created Directory: {0}'.format(dst))
def __copy(self, src, dst, passes=None, fails=None, dry_run=False):
"""
Copy the given src file to dst
Append dst to ``fails`` on error
"""
if self.progressfnc:
self.progressfnc('Copying {0} -> {1}'.format(src, dst), self.__getProgPercent())
try:
if not dry_run:
if os.path.exists(dst) and self.runstngs['forceOwnership']:
# make writable
fileAtt = os.stat(dst)[0]
if (not fileAtt & stat.S_IWRITE):
try:
os.chmod(dst, stat.S_IWRITE)
except Exception as e:
LOG.error('Could not make file writable {0}: {1}'.format(dst, e))
return False
shutil.copy2(src, dst)
except (IOError, OSError) as e:
if self.runstngs['errorsToDebug']:
LOG.debug(e)
else:
LOG.error(e)
if fails is not None:
fails.append(dst)
else:
if passes is not None:
passes.append(dst)
LOG.debug('Copied: {0}'.format(dst))
def __rmdir(self, dir_, passes=None, fails=None, dry_run=False):
"""
Remove the given dir_.
Append dir_ to ``fails`` on error
"""
if self.progressfnc:
self.progressfnc('Deleting {0}'.format(dir_), self.__getProgPercent())
if not os.path.isdir(dir_):
LOG.warning('Directory does not exist: {0}'.format(dir_))
return
try:
if not dry_run:
shutil.rmtree(dir_)
except Exception as e:
LOG.error(e)
if fails is not None:
fails.append(dir_)
else:
if passes is not None:
passes.append(dir_)
LOG.debug('Removed dir: {0}'.format(dir_))
def __remove(self, f, passes=None, fails=None, dry_run=False):
"""
Delete the given file
Append f to ``fails`` on error
"""
if self.progressfnc:
self.progressfnc('Deleting {0}'.format(f), self.__getProgPercent())
if not os.path.isfile(f):
LOG.warning('File does not exist: {0}'.format(f))
return
try:
if not dry_run:
os.remove(f)
except OSError as e:
LOG.error(e)
if fails is not None:
fails.append(f)
else:
if passes is not None:
passes.append(f)
LOG.debug('Deleted: {0}'.format(f))
def report(self, diff=False):
if not self.__hasrun or diff:
if not self.__diffcurrent:
LOG.warning('diff is not current')
return self.diffreport()
else:
self.runreport()
def diffreport(self, **kwargs):
"""
Return a report from the current diff
``trimmed`` -- if True, returns the trimmed diff's report
"""
if self.origdiff is None:
return
if self.runstngs['trimmed']:
return self.trimdiff.report(**kwargs)
else:
return self.origdiff.report(**kwargs)
def runreport(self):
"""
Print a report for the last update/sync/run.
"""
if self.src is None:
LOG.info('No source path is defined')
return
if self.dst is None:
LOG.info('No destination path is defined')
return
# build title
title = 'Sync report ({0} -> {1}):'.format(self.src, self.dst)
dashes = '-'*len(title)
result = '\n{0}\n{1}\n'.format(title, dashes)
# loop through all attributes
attrs = ['create', 'update', 'purge']
for attr in attrs:
fails = self.stats['{0}fails'.format(attr)]
passes = self.stats['{0}s'.format(attr)]
result += ('\n{attr}: ({0})\n'.format(len(passes), attr=(attr.title() + ' Passes')))
result += ('{attr}: ({0})\n'.format(len(fails), attr=(attr.title() + ' Fails')))
for item in fails:
result += (' {0}\n'.format(item))
LOG.info(result)
return result