import hashlib
import os
import argparse
def hash_directory(path, verbose=False):
"""Hashes the contents of a directory."""
hasher = hashlib.sha256()
try:
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isfile(item_path):
with open(item_path, 'rb') as f:
while True:
chunk = f.read(4096) # Read in chunks
if not chunk:
break
hasher.update(chunk)
elif os.path.isdir(item_path):
if verbose:
print(f"Hashing subdirectory: {item_path}")
hasher.update(os.path.basename(item_path).encode('utf-8')) # Hash directory name
except OSError as e:
print(f"Error accessing {path}: {e}")
return None
return hasher.hexdigest()
def main():
"""Parses arguments and hashes the specified directory."""
parser = argparse.ArgumentParser(description='Hash a directory.')
parser.add_argument('directory', help='The directory to hash.')
parser.add_argument('--dry-run', action='store_true', help='Perform a dry run (print hashes without actual computation).')
args = parser.parse_args()
if not os.path.isdir(args.directory):
print(f"Error: {args.directory} is not a directory.")
return
if args.dry_run:
print("Dry run mode enabled. Printing hashes without computation.")
hashes = {}
for item in os.listdir(args.directory):
item_path = os.path.join(args.directory, item)
if os.path.isfile(item_path):
hashes[item] = hash_directory(item_path, verbose=True)
elif os.path.isdir(item_path):
hashes[item] = hash_directory(item_path, verbose=True)
print(hashes)
return
hash_value = hash_directory(args.directory)
if hash_value:
print(f"Directory hash: {hash_value}")
if __name__ == "__main__":
main()
Add your comment