2.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. #!/usr/local/bin/python3
  2. import os, sys, argparse
  3. import hashlib
  4. import humanfriendly
  5. parser = argparse.ArgumentParser(description='What the dupe!?')
  6. optional = parser._action_groups.pop()
  7. required = parser.add_argument_group('required arguments')
  8. exclusive= parser.add_mutually_exclusive_group(required=False)
  9. exclusive.add_argument('--threshold', type=str,
  10. help='Only output files greater than \'size\', e.g. 100M')
  11. exclusive.add_argument('--sizes', type=str, nargs='+',
  12. help='Only output files greater than \'size\', e.g. 100M')
  13. required.add_argument('--dir', type=str, nargs='?', required=True, action='append',
  14. help='Directory to scan. Can be issued multiple times.')
  15. optional.add_argument('--exclude', type=str, nargs='?', action='append',
  16. help='Only output files greater than \'size\', e.g. 100M')
  17. parser._action_groups.append(optional)
  18. args = parser.parse_args()
  19. if args.sizes:
  20. sizes = args.sizes
  21. sizes.append('larger than '+sizes[-1])
  22. else:
  23. sizes = ['10M', '50M', '100M', '1G', '5G']
  24. sizes.append('larger than '+sizes[-1])
  25. if args.exclude:
  26. exclude=args.exclude
  27. if args.threshold:
  28. threshold = humanfriendly.parse_size(args.threshold)
  29. else:
  30. threshold = 0
  31. def findDup(parentFolder):
  32. # Dups in format {hash:[names]}
  33. dups = {}
  34. print()
  35. for dirName, subdirs, fileList in os.walk(parentFolder):
  36. # remove excluded dirs from list
  37. if args.exclude:
  38. for exclude in args.exclude:
  39. subdirs[:] = [dn for dn in subdirs if dirName+'/'+dn != exclude]
  40. print(' Scanning %s...' % dirName)
  41. for filename in fileList:
  42. # Get the path to the file
  43. path = os.path.join(dirName, filename)
  44. # Calculate hash
  45. if os.path.exists(path):
  46. # Calculate hash
  47. file_hash = hashfile(path)
  48. # Add or append the file path
  49. if file_hash in dups:
  50. dups[file_hash].append(path)
  51. else:
  52. dups[file_hash] = [path]
  53. return dups
  54. # Joins two dictionaries
  55. def joinDicts(dict1, dict2):
  56. for key in dict2.keys():
  57. if key in dict1:
  58. dict1[key] = dict2[key]
  59. else:
  60. dict1[key] = dict2[key]
  61. def hashfile(path, blocksize = 65536):
  62. file_size = os.path.getsize(path)
  63. # Only hash files larger than threshold (if set)
  64. if threshold == 0 or (threshold > 0 and file_size > threshold):
  65. try:
  66. afile = open(path, 'rb')
  67. hasher = hashlib.md5()
  68. buf = afile.read(blocksize)
  69. while len(buf) > 0:
  70. hasher.update(buf)
  71. buf = afile.read(blocksize)
  72. afile.close()
  73. return hasher.hexdigest()
  74. except:
  75. pass
  76. def printResults(dict1):
  77. final = {}
  78. for size in sizes:
  79. final[size] = []
  80. del size
  81. if threshold > 0:
  82. final[threshold] = []
  83. results = list(filter(lambda x: len(x) > 1, dict1.values()))
  84. for result in results:
  85. file_size = os.path.getsize(result[0])
  86. if not args.threshold or (args.threshold and args.sizes):
  87. count = 0
  88. while count+1 < len(sizes):
  89. try:
  90. if file_size >= humanfriendly.parse_size(sizes[count]) and file_size < humanfriendly.parse_size(sizes[count+1]):
  91. final[sizes[count+1]].append(result)
  92. except:
  93. final[sizes[-1]].append(result)
  94. count += 1
  95. if args.threshold and args.sizes:
  96. pass
  97. elif file_size < humanfriendly.parse_size(sizes[0]):
  98. final[sizes[0]].append(result)
  99. else:
  100. if file_size >= threshold:
  101. final[threshold].append(result)
  102. status=[x for x in final if len(final[x]) > 0]
  103. if len(results) > 0 and (len(status) > 0):
  104. print('___________________')
  105. print('\n\033[1;34m\033[1;34m\u25b6 Duplicates Found\033[0m\n')
  106. print(' The following files are identical. The name could differ, but the content is identical')
  107. print('___________________')
  108. new = ['0']
  109. if not args.threshold or (args.threshold and args.sizes):
  110. for size in sizes:
  111. new.append(size)
  112. if len(final[size]) > 0:
  113. if size == 'larger than ' + sizes[-2]:
  114. print("\n\033[1;34m\u25b6 >= %s\033[0m" % (new[-2]))
  115. else:
  116. print("\n\033[1;34m\u25b6 %s to %s\033[0m" % (new[-2],size))
  117. for dupe in final[size]:
  118. print('___________________\n')
  119. for file in dupe:
  120. print(' %s' % str(file))
  121. print('___________________')
  122. else:
  123. print("\n\033[1;34m\u25b6 Files bigger than %s\033[0m" % humanfriendly.format_size(threshold, binary=True))
  124. for dupe in final[threshold]:
  125. print('___________________\n')
  126. for file in dupe:
  127. print(' %s' % str(file))
  128. print('___________________')
  129. else:
  130. print('\n\033[1mNo duplicate files found.\033[0m')
  131. if __name__ == '__main__':
  132. dups = {}
  133. folders = args.dir
  134. for i in folders:
  135. # Iterate the folders given
  136. if os.path.exists(i):
  137. # Find the duplicated files and append them to the dups
  138. joinDicts(dups, findDup(i))
  139. else:
  140. print('%s is not a valid path, please verify' % i)
  141. sys.exit()
  142. printResults(dups)