2.py 5.5 KB

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