2.py 5.7 KB

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