1. import hashlib
  2. import os
  3. import argparse
  4. def hash_directory(path, verbose=False):
  5. """Hashes the contents of a directory."""
  6. hasher = hashlib.sha256()
  7. try:
  8. for item in os.listdir(path):
  9. item_path = os.path.join(path, item)
  10. if os.path.isfile(item_path):
  11. with open(item_path, 'rb') as f:
  12. while True:
  13. chunk = f.read(4096) # Read in chunks
  14. if not chunk:
  15. break
  16. hasher.update(chunk)
  17. elif os.path.isdir(item_path):
  18. if verbose:
  19. print(f"Hashing subdirectory: {item_path}")
  20. hasher.update(os.path.basename(item_path).encode('utf-8')) # Hash directory name
  21. except OSError as e:
  22. print(f"Error accessing {path}: {e}")
  23. return None
  24. return hasher.hexdigest()
  25. def main():
  26. """Parses arguments and hashes the specified directory."""
  27. parser = argparse.ArgumentParser(description='Hash a directory.')
  28. parser.add_argument('directory', help='The directory to hash.')
  29. parser.add_argument('--dry-run', action='store_true', help='Perform a dry run (print hashes without actual computation).')
  30. args = parser.parse_args()
  31. if not os.path.isdir(args.directory):
  32. print(f"Error: {args.directory} is not a directory.")
  33. return
  34. if args.dry_run:
  35. print("Dry run mode enabled. Printing hashes without computation.")
  36. hashes = {}
  37. for item in os.listdir(args.directory):
  38. item_path = os.path.join(args.directory, item)
  39. if os.path.isfile(item_path):
  40. hashes[item] = hash_directory(item_path, verbose=True)
  41. elif os.path.isdir(item_path):
  42. hashes[item] = hash_directory(item_path, verbose=True)
  43. print(hashes)
  44. return
  45. hash_value = hash_directory(args.directory)
  46. if hash_value:
  47. print(f"Directory hash: {hash_value}")
  48. if __name__ == "__main__":
  49. main()

Add your comment