py-sync-comm-libs/sync_directories.py

44 lines
1.6 KiB
Python

import os
import hashlib
import shutil
import json
import fnmatch
def load_config(config_path):
with open(config_path, 'r', encoding='utf-8') as file:
return json.load(file)
def calculate_hash(file_path):
hash_md5 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def should_ignore(path, ignore_patterns):
"""Check if the given path matches any of the ignore patterns."""
return any(fnmatch.fnmatch(path, pattern) for pattern in ignore_patterns)
def sync_directories(source, destination, ignore_patterns):
if not os.path.exists(destination):
os.makedirs(destination)
for item in os.listdir(source):
src_item = os.path.join(source, item)
dest_item = os.path.join(destination, item)
# Check if the item matches any ignore pattern
if should_ignore(item, ignore_patterns):
continue
if os.path.isdir(src_item):
sync_directories(src_item, dest_item, ignore_patterns)
else:
print(f'Checking {src_item}... ', end='')
if not os.path.exists(dest_item) or calculate_hash(src_item) != calculate_hash(dest_item):
shutil.copy2(src_item, dest_item)
print(f'\033[31mCopied!\033[0m')
else:
print(f'\033[32mSame!\033[0m')
if __name__ == '__main__':
config = load_config('config.json')
sync_directories(config['source_directory'], config['destination_directory'], config['ignore'])