-
Notifications
You must be signed in to change notification settings - Fork 11
/
scorch
executable file
·1651 lines (1366 loc) · 48.8 KB
/
scorch
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# ISC License (ISC)
#
# Copyright (c) 2019, Antonio SJ Musumeci <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import argparse
import collections
import csv
import errno
import fcntl
import gzip
import hashlib
import io
import math
import os
import random
import re
import shlex
import shutil
import signal
import stat
import sys
import tempfile
import time
import zlib
from collections import namedtuple
from datetime import datetime as dt
from itertools import takewhile
DEFAULT_DB = 'scorch'
DEFAULT_DBPATH = '/var/tmp/scorch'
SUCCESS = 0
ERROR_PROCESSING = 1
ERROR_ARG = 2
ERROR_DIGEST_MISMATCH = 4
ERROR_FOUND = 8
ERROR_NOT_FOUND = 16
ERROR_INTERRUPTED = 32
MAX_ACTIONS = 2**64
MAX_TIME = 2**64
MAX_DATA = 2**64
class Options(object):
verbose = 0
hash = 'md5'
quote = 0
sort = None
filter = None
maxactions = MAX_ACTIONS
maxdata = MAX_DATA
maxtime = MAX_TIME
breakonerror = False
diff_fields = ['size']
class FileInfo(object):
def __init__(self,digest,size,mode,mtime,inode,state='U',checked=0):
self.digest = digest
self.size = size
self.mode = mode
self.mtime = mtime
self.inode = inode
self.state = state
self.checked = checked
def __str__(self):
return str({'digest': self.digest,
'size': self.size,
'mode': self.mode,
'mtime': self.mtime,
'inode': self.inode,
'state': self.state,
'checked': self.checked})
def __eq__(self, rhs):
return ((self.digest == rhs.digest) and
(self.size == rhs.size) and
(self.mode == rhs.mode) and
(self.mtime == rhs.mtime) and
(self.inode == rhs.inode))
class FileFilter(object):
def __init__(self,basepath,fnfilter,fifilter):
self.basepath = basepath
self.fnfilter = fnfilter
self.fifilter = fifilter
def filter(self,filepath,fi,other=(lambda f: False)):
common = commonprefix([self.basepath,filepath])
if common != self.basepath:
return True
if self.fnfilter(filepath):
return True
if self.fifilter(fi):
return True
if other(filepath):
return True
return False
class NullFileHash(object):
def hash(self,fullpath):
return 'null:'
class Crc32FileHash(object):
def hash(self,fullpath):
digest = 0
blocksize = 65536
with open(fullpath,'rb') as f:
buf = f.read(blocksize)
while buf:
digest = zlib.crc32(buf,digest)
buf = f.read(blocksize)
return 'crc32:{:08x}'.format(digest)
class Adler32FileHash(object):
def hash(self,fullpath):
digest = 0
blocksize = 65536
with open(fullpath,'rb') as f:
buf = f.read(blocksize)
while buf:
digest = zlib.adler32(buf,digest)
buf = f.read(blocksize)
return 'adler32:{:08x}'.format(digest)
class HashLibFileHash(object):
_hash = None
def __init__(self,algo):
self._hash = hashlib.new(algo)
def hash(self,fullpath):
blocksize = 65536
with open(fullpath,'rb') as f:
buf = f.read(blocksize)
while buf:
self._hash.update(buf)
buf = f.read(blocksize)
return '{}:{}'.format(self._hash.name,
self._hash.hexdigest())
def available_hashes():
hashes = hashlib.algorithms_available
hashes.add('adler32')
hashes.add('crc32')
hashes.add('null')
return sorted(hashes)
def file_hash_factory(algo):
if algo == 'adler32':
return Adler32FileHash()
if algo == 'crc32':
return Crc32FileHash()
if algo == 'null':
return NullFileHash()
return HashLibFileHash(algo)
def allnamesequal(name):
return all(n==name[0] for n in name[1:])
def commonprefix(paths,sep='/'):
bydirectorylevels = zip(*[p.split(sep) for p in paths])
return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))
def regex_type(pat):
try:
re.compile(pat)
except:
raise argparse.ArgumentTypeError('invalid regex')
return pat
def print_help():
help = \
'''
usage: scorch [<options>] <instruction> [<directory>]
scorch (Silent CORruption CHecker) is a tool to catalog files, hash
digests, and other metadata to help in discovering file corruption,
missing files, duplicates, etc.
positional arguments:
instruction: * add: compute & store digests for found files
* append: compute & store digests for unhashed files
* backup: backs up selected database
* restore: restore backed up database
* list-backups: list database backups
* diff-backup: show diff between current & backup DB
* hashes: print available hash functions
* check: check stored info against files
* update: update metadata of changed files
* check+update: check and update if new
* cleanup: remove info of missing files
* delete: remove info for found files
* list: md5sum'ish compatible listing
* list-unhashed: list files not yet hashed
* list-missing: list files no longer on filesystem
* list-dups: list files w/ dup digests
* list-solo: list files w/ no dup digests
* list-failed: list files marked failed
* list-changed: list files marked changed
* in-db: show if files exist in DB
* found-in-db: print files found in DB
* notfound-in-db: print files not found in DB
directory: Directory or file to scan.
optional arguments:
-d, --db=: File to store digests and other metadata in. See
docs for info. (default: /var/tmp/scorch/scorch.db)
-v, --verbose: Make `instruction` more verbose. Actual behavior
depends on the instruction. Can be used multiple
times.
-q, --quote: Shell quote/escape filenames when printed.
-r, --restrict=: * sticky: restrict scan to files with sticky bit
* readonly: restrict scan to readonly files
-f, --fnfilter=: Restrict actions to files which match regex.
-F, --negate-fnfilter Negate the fnfilter regex match.
-s, --sort=: Sorting routine on input & output. (default: natural)
* random: shuffled / random
* natural: human-friendly sort, ascending
* natural-desc: human-friendly sort, descending
* radix: RADIX sort, ascending
* radix-desc: RADIX sort, descending
* mtime: sort by file mtime, ascending
* mtime-desc: sort by file mtime, descending
* checked: sort by last time checked, ascending
* checked-desc: sort by last time checked, descending
-m, --maxactions=: Max actions before exiting. (default: 2**64)
-M, --maxdata=: Max bytes to process before exiting. (default: 2**64)
Can use 'K', 'M', 'G', 'T' suffix.
-T, --maxtime=: Max time to process before exiting. (default: 2**64)
Can use 's', 'm', 'h', 'd' suffix.
-b, --break-on-error: Any error or digest mismatch will cause an exit.
-D, --diff-fields=: Fields to use to indicate a file has 'changed' (vs.
bitrot / modified) and should be rehashed.
Combine with ','. (default: size)
* size
* inode
* mtime
* mode
-H, --hash=: Hash algo. Use 'scorch hashes' get available algos.
(default: md5)
-h, --help: Print this message.
exit codes:
* 0 : success, behavior executed, something found
* 1 : processing error
* 2 : error with command line arguments
* 4 : hash mismatch
* 8 : found
* 16 : not found, nothing processed
* 32 : interrupted
'''
print(help)
def build_arg_parser():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-d','--db',
type=str,
default=DEFAULT_DB)
parser.add_argument('inst',
choices=['hashes',
'add','append',
'backup','restore',
'list-backups','diff-backup',
'check','update',
'check+update','delete',
'cleanup','list',
'list-unhashed','list-dups',
'list-solo','list-missing',
'list-failed','list-changed',
'in-db',
'found-in-db','notfound-in-db'],
nargs='?')
parser.add_argument('dir',
type=str,
nargs='*')
parser.add_argument('-v','--verbose',
action='count',
default=0)
parser.add_argument('-q','--quote',
action='store_true',
default=False)
parser.add_argument('-r','--restrict',
choices=['sticky',
'readonly'])
parser.add_argument('-f','--fnfilter',
type=regex_type)
parser.add_argument('-F','--negate-fnfilter',
action='store_true',
default=False)
parser.add_argument('-s','--sort',
choices=['none',
'random',
'radix','radix-desc',
'natural','natural-desc',
'mtime','mtime-desc',
'checked','checked-desc'],
default='natural')
parser.add_argument('-m','--maxactions',
type=int,
default=sys.maxsize)
parser.add_argument('-M','--maxdata',
type=str,
default=str(sys.maxsize))
parser.add_argument('-T','--maxtime',
type=str,
default=str(sys.maxsize))
parser.add_argument('-b','--break-on-error',
action='store_true',
default=False)
parser.add_argument('-D','--diff-fields',
type=str,
default='size')
parser.add_argument('-H','--hash',
type=str,
choices=available_hashes(),
default='md5')
parser.add_argument('-h','--help',
action='store_true',
default=False)
return parser
def hash_file(filepath, algo):
algo = algo.split(':')[0]
filehash = file_hash_factory(algo)
return filehash.hash(filepath)
def get_files(basepath,filefilter,db={}):
if os.path.isfile(basepath):
fi = get_fileinfo(basepath)
if not fi:
return []
return [(basepath,fi)]
files = []
for (dirname,dirnames,filenames) in os.walk(basepath):
for filename in filenames:
filepath = os.path.join(dirname,filename)
if filepath in db:
continue
fi = get_fileinfo(filepath)
if not fi:
continue
if filefilter.filter(filepath,fi):
continue
files.append((filepath,fi))
return files
def filter_files(files,filefilter,other=(lambda f: False)):
if filefilter.basepath == '/':
return [(filepath,fi) for (filepath,fi) in files]
if filefilter.basepath in files:
return files
rv = []
for (filepath,fi) in files:
if filefilter.filter(filepath,fi,other):
continue
rv.append((filepath,fi))
return rv
def get_fileinfo(filepath):
try:
st = os.lstat(filepath)
if not stat.S_ISREG(st.st_mode):
return None
return FileInfo(digest='',
size=st.st_size,
mode=st.st_mode,
mtime=st.st_mtime,
inode=st.st_ino)
except IOError as e:
return None
def iso8601(timestamp):
return dt.utcfromtimestamp(timestamp).isoformat() + 'Z'
def print_filepath(filepath,count=0,total=0,quote=False,end=''):
if quote:
filepath = shlex.quote(filepath)
s = ''
if count or total:
padding = len(str(total))
padded = str(count).zfill(padding)
s = '{0}/{1} '.format(padded,total)
s += filepath
print(s,end=end)
sys.stdout.flush()
def human_to_bytes(s):
m = s[-1]
if m == 'K':
i = int(s[0:-1]) * 1024
elif m == 'M':
i = int(s[0:-1]) * 1024 * 1024
elif m == 'G':
i = int(s[0:-1]) * 1024 * 1024 * 1024
elif m == 'T':
i = int(s[0:-1]) * 1024 * 1024 * 1024 * 1024
else:
i = int(s)
return i
def human_to_time(s):
m = s[-1]
if m in ['s','S']:
t = int(s[0:-1])
elif m in ['m','M']:
t = int(s[0:-1]) * 60
elif m in ['h','H']:
t = int(s[0:-1]) * 60 * 60
elif m in ['d','D']:
t = int(s[0:-1]) * 60 * 60 * 24
else:
t = int(s)
return t
def humansize(nbytes):
suffixes = ['B','KB','MB','GB','TB','PB','ZB']
rank = int(math.log(nbytes,1024)) if nbytes else 0
rank = min(rank, len(suffixes) - 1)
human = nbytes / (1024.0 ** rank)
if suffixes[rank] == 'B':
f = int(human)
else:
f = '{:.2f}'.format(human)
return '{}{}'.format(f, suffixes[rank])
def inst_hashes(opts,path,db,dbremove):
for hash in available_hashes():
print(hash)
return SUCCESS
def inst_add(opts,path,db,dbremove):
rv = ERROR_NOT_FOUND
err = SUCCESS;
filepaths = get_files(path,opts.filter)
opts.sort(filepaths)
actions = 0
processed = 0
endtime = time.time() + opts.maxtime
total = min(opts.maxactions,len(filepaths))
for (filepath,fi) in filepaths:
if actions >= opts.maxactions:
break
if processed >= opts.maxdata:
break
if time.time() >= endtime:
break
actions += 1
processed += fi.size
if opts.verbose:
print_filepath(filepath,actions,total,opts.quote)
try:
fi.digest = hash_file(filepath,opts.hash)
fi.state = 'O'
fi.checked = time.time()
if opts.verbose:
print(':',fi.digest)
append_to_db(opts.dbpath,filepath,fi)
rv = SUCCESS
except (KeyboardInterrupt,SystemExit):
err = err | ERROR_INTERRUPTED
break
except Exception as e:
err = err | ERROR_PROCESSING
if opts.verbose:
print(': ERROR -',e)
if opts.breakonerror:
break
return rv | err
def inst_append(opts,path,db,dbremote):
rv = ERROR_NOT_FOUND
err = SUCCESS
filepaths = get_files(path,opts.filter,db)
opts.sort(filepaths)
actions = 0
processed = 0
endtime = time.time() + opts.maxtime
total = min(opts.maxactions,len(filepaths))
for (filepath,fi) in filepaths:
if actions >= opts.maxactions:
break
if processed >= opts.maxdata:
break
if time.time() >= endtime:
break
actions += 1
processed += fi.size
if opts.verbose:
print_filepath(filepath,actions,total,opts.quote)
try:
fi.digest = hash_file(filepath,opts.hash)
fi.state = 'O'
fi.checked = time.time()
if opts.verbose:
print(':',fi.digest)
append_to_db(opts.dbpath,filepath,fi)
rv = SUCCESS
except (KeyboardInterrupt,SystemExit):
err = err | ERROR_INTERRUPTED
break
except Exception as e:
err = err | ERROR_PROCESSING
if opts.verbose:
print(': ERROR -',e)
if opts.breakonerror:
break
return rv | err
def fileinfo_changes(oldfi,newfi):
changes = []
text = ' - size: '
if oldfi.size != newfi.size:
text += '{} -> {}'.format(humansize(oldfi.size),humansize(newfi.size))
else:
text += '{} (unchanged)'.format(humansize(oldfi.size))
changes.append(text)
text = ' - mtime: '
if oldfi.mtime != newfi.mtime:
text += '{} -> {}'.format(iso8601(oldfi.mtime),iso8601(newfi.mtime))
else:
text += '{} (unchanged)'.format(iso8601(oldfi.mtime))
changes.append(text)
text = ' - mode: '
if oldfi.mode != newfi.mode:
text += '{0:03o} -> {1:03o}'.format(oldfi.mode,newfi.mode)
else:
text += '{0:03o} (unchanged)'.format(oldfi.mode)
changes.append(text)
text = ' - inode: '
if oldfi.inode != newfi.inode:
text += '{} -> {}'.format(oldfi.inode,newfi.inode)
else:
text += '{} (unchanged)'.format(oldfi.inode)
changes.append(text)
return changes
def different_files(old,new,fields):
return ((('size' in fields) and (old.size != new.size)) or
(('inode' in fields) and (old.inode != new.inode)) or
(('mtime' in fields) and (old.mtime != new.mtime)) or
(('mode' in fields) and (old.mode != new.mode)))
def inst_check(opts,path,db,dbremove,update=False):
rv = ERROR_NOT_FOUND
err = SUCCESS
filepaths = filter_files(db.items(),opts.filter)
opts.sort(filepaths)
actions = 0
processed = 0
endtime = time.time() + opts.maxtime
total = min(opts.maxactions,len(filepaths))
for (filepath,oldfi) in filepaths:
if actions >= opts.maxactions:
break
if processed >= opts.maxdata:
break
if time.time() >= endtime:
break
actions += 1
processed += oldfi.size
try:
newfi = get_fileinfo(filepath)
if not newfi:
print_filepath(filepath,actions,total,opts.quote)
print(': MISSING')
continue
rv = SUCCESS
if different_files(oldfi,newfi,opts.diff_fields):
err = err | ERROR_DIGEST_MISMATCH
changes = fileinfo_changes(oldfi,newfi)
print_filepath(filepath,actions,total,opts.quote)
print(': CHANGED{}'.format(' (updated)' if update else ''))
for change in changes:
print(change)
print(' - digest: {} -> '.format(oldfi.digest),end='')
if update:
newfi.digest = hash_file(filepath,opts.hash)
newfi.state = 'O'
newfi.checked = time.time()
print(newfi.digest)
append_to_db(opts.dbpath,filepath,newfi)
else:
oldfi.state = 'C'
oldfi.checked = time.time()
print('not calculated')
append_to_db(opts.dbpath,filepath,oldfi)
else:
if opts.verbose:
print_filepath(filepath,actions,total,opts.quote)
newfi.digest = hash_file(filepath,oldfi.digest)
if newfi.digest != oldfi.digest:
err = err | ERROR_DIGEST_MISMATCH
oldfi.state = 'F'
oldfi.checked = time.time()
if not opts.verbose:
print_filepath(filepath,actions,total,opts.quote)
print(': FAILED')
changes = fileinfo_changes(oldfi,newfi)
for change in changes:
print(change)
print(' - digest: {} -> {}'.format(oldfi.digest,newfi.digest))
append_to_db(opts.dbpath,filepath,oldfi)
if opts.breakonerror:
break
elif opts.verbose:
if update and oldfi != newfi:
print(': OK (updated)')
changes = fileinfo_changes(oldfi,newfi)
for change in changes:
print(change)
print(' - digest: {} (unchanged)'.format(oldfi.digest))
newfi.state = 'O'
newfi.checked = time.time()
append_to_db(opts.dbpath,filepath,newfi)
else:
oldfi.state = 'O'
oldfi.checked = time.time()
print(': OK')
append_to_db(opts.dbpath,filepath,oldfi)
except (KeyboardInterrupt,SystemExit):
err = err | ERROR_INTERRUPTED
break
except Exception as e:
err = err | ERROR_PROCESSING
print_filepath(filepath,actions,total,opts.quote)
print(': ERROR -',e)
if opts.breakonerror:
break
return rv | err
def inst_check_and_update(opts,path,db,dbremove):
return inst_check(opts,path,db,dbremove,update=True)
def inst_update(opts,path,db,dbremove):
rv = SUCCESS
filepaths = filter_files(db.items(),opts.filter)
opts.sort(filepaths)
actions = 0
processed = 0
endtime = time.time() + opts.maxtime
total = min(opts.maxactions,len(filepaths))
for (filepath,oldfi) in filepaths:
if actions >= opts.maxactions:
break
if processed >= opts.maxdata:
break
if time.time() >= endtime:
break
actions += 1
processed += oldfi.size
try:
newfi = get_fileinfo(filepath)
if not newfi:
print_filepath(filepath,actions,total,opts.quote)
print(': MISSING')
continue
newfi.digest = oldfi.digest
if oldfi == newfi:
if opts.verbose:
print_filepath(filepath,actions,total,opts.quote)
print(': UNCHANGED')
continue
changes = fileinfo_changes(oldfi,newfi)
if changes:
print_filepath(filepath,actions,total,opts.quote)
print(': CHANGED')
for change in changes:
print(change)
print(' - digest: ',end='')
if different_files(oldfi,newfi,opts.diff_fields):
print('{} -> '.format(oldfi.digest),end='')
newfi.digest = hash_file(filepath,opts.hash)
print('{}'.format(newfi.digest))
else:
print('{} (unchanged)'.format(oldfi.digest))
newfi.state = 'O'
newfi.checked = time.time()
append_to_db(opts.dbpath,filepath,newfi)
except (KeyboardInterrupt,SystemExit):
rv = rv | ERROR_INTERRUPTED
break
except Exception as e:
rv = rv | ERROR_PROCESSING
print_filepath(filepath,actions,total,opts.quote)
print(': ERROR -',e)
if opts.breakonerror:
break
return rv
def inst_delete(opts,path,db,dbremove):
rv = ERROR_NOT_FOUND
err = SUCCESS
filepaths = filter_files(db.items(),opts.filter)
opts.sort(filepaths)
actions = 0
processed = 0
endtime = time.time() + opts.maxtime
total = min(opts.maxactions,len(filepaths))
for (filepath,fi) in filepaths:
if actions >= opts.maxactions:
break
if processed >= opts.maxdata:
break
if time.time() >= endtime:
break
actions += 1
processed += fi.size
rv = SUCCESS
dbremove.append(filepath)
if opts.verbose == 1:
print_filepath(filepath,quote=opts.quote,end='\n')
elif opts.verbose == 2:
print_filepath(filepath,actions,total,opts.quote)
print(': REMOVED')
return rv | err
def inst_cleanup(opts,path,db,dbremove):
rv = ERROR_NOT_FOUND
err = SUCCESS
filepaths = filter_files(db.items(),opts.filter,os.path.exists)
opts.sort(filepaths)
actions = 0
processed = 0
endtime = time.time() + opts.maxtime
total = min(opts.maxactions,len(filepaths))
for (filepath,fi) in filepaths:
if actions >= opts.maxactions:
break
if processed >= opts.maxdata:
break
if time.time() >= endtime:
break
actions += 1
processed += fi.size
rv = SUCCESS
dbremove.append(filepath)
if opts.verbose:
print_filepath(filepath,actions,total,opts.quote)
print(': REMOVED')
return rv | err
def inst_list(opts,path,db,dbremove):
rv = ERROR_NOT_FOUND
err = SUCCESS
filepaths = filter_files(db.items(),opts.filter)
opts.sort(filepaths)
actions = 0
processed = 0
endtime = time.time() + opts.maxtime
for (filepath,fi) in filepaths:
if actions >= opts.maxactions:
break
if processed >= opts.maxdata:
break
if time.time() >= endtime:
break
actions += 1
processed += fi.size
rv = SUCCESS
if not opts.verbose:
filepath = os.path.relpath(filepath,path)
if opts.quote:
filepath = shlex.quote(filepath)
print(fi.digest,filepath)
return rv | err
def inst_list_unhashed(opts,path,db,dbremove):
rv = ERROR_NOT_FOUND
err = SUCCESS
filepaths = get_files(path,opts.filter,db)
opts.sort(filepaths)
actions = 0
processed = 0
endtime = time.time() + opts.maxtime
for (filepath,fi) in filepaths:
if actions >= opts.maxactions:
break
if processed >= opts.maxdata:
break
if time.time() >= endtime:
break
actions += 1
processed += fi.size
rv = SUCCESS
if not opts.verbose:
filepath = os.path.relpath(filepath,path)
print_filepath(filepath,quote=opts.quote,end='\n')
return rv | err
def inst_list_dups(opts,path,db,dbremove):
rv = ERROR_NOT_FOUND
err = SUCCESS
hashdb = {}
for (filepath,fi) in db.items():
if opts.filter.filter(filepath,fi):
continue
if not fi.digest in hashdb:
hashdb[fi.digest] = []
hashdb[fi.digest].append(filepath)
actions = 0
endtime = time.time() + opts.maxtime
for (digest,filepaths) in hashdb.items():
if len(filepaths) <= 1:
continue
if actions >= opts.maxactions:
break
if time.time() >= endtime:
break
actions += 1
rv = SUCCESS
if opts.quote:
filepaths = [shlex.quote(filepath) for filepath in filepaths]
filepaths.sort()
if opts.verbose:
print(digest,'\n -','\n - '.join(filepaths))
else:
print(digest,' '.join(filepaths))
return rv | err
def inst_list_solo(opts,path,db,dbremove):
rv = ERROR_NOT_FOUND
err = SUCCESS
hashdb = {}
for (filepath,fi) in db.items():
if opts.filter.filter(filepath,fi):
continue
if not fi.digest in hashdb:
hashdb[fi.digest] = []
hashdb[fi.digest].append(filepath)
actions = 0
endtime = time.time() + opts.maxtime
for (digest,filepaths) in hashdb.items():
if len(filepaths) > 1:
continue
if actions >= opts.maxactions:
return rv
if time.time() >= endtime:
break
actions += 1
rv = SUCCESS
if opts.quote:
filepaths[0] = shlex.quote(filepaths[0])
print(digest,filepaths[0])
return rv | err
def inst_list_missing(opts,path,db,dbremove):
rv = ERROR_NOT_FOUND
err = SUCCESS
filepaths = get_files(path,opts.filter)
filepaths = dict(filepaths)
actions = 0
processed = 0
endtime = time.time() + opts.maxtime
output = []
for (filepath,fi) in db.items():
if commonprefix([path,filepath]) != path:
continue
if filepath in filepaths:
continue
if actions >= opts.maxactions:
break