Content 동기화
스크립트
- sync.py
import os
import filecmp
import shutil
def sync_directories(source_dir, target_dir):
"""
Sync the target directory to match the source directory.
"""
# Create target directory if it doesn't exist
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# Compare the two directories
comparison = filecmp.dircmp(source_dir, target_dir)
# Update files that are new or have changed
for file_name in comparison.left_only + comparison.diff_files:
source_file = os.path.join(source_dir, file_name)
target_file = os.path.join(target_dir, file_name)
# Skip directories that start with . or _
if os.path.isdir(source_file) and (os.path.basename(source_file).startswith('.') or os.path.basename(source_file).startswith('_')):
continue
if os.path.isdir(source_file):
if os.path.exists(target_file):
shutil.rmtree(target_file)
shutil.copytree(source_file, target_file)
else:
shutil.copy2(source_file, target_file)
# Delete files that are no longer present in the source directory
for file_name in comparison.right_only:
target_file = os.path.join(target_dir, file_name)
if os.path.isdir(target_file):
shutil.rmtree(target_file)
else:
os.remove(target_file)
# Recursively sync subdirectories
for subdir in comparison.common_dirs:
source_subdir = os.path.join(source_dir, subdir)
target_subdir = os.path.join(target_dir, subdir)
# Skip directories that start with . or _
if os.path.basename(source_subdir).startswith('.') or os.path.basename(source_subdir).startswith('_'):
continue
sync_directories(source_subdir, target_subdir)
def main():
current_dir = os.path.dirname(os.path.abspath(__file__))
target_dir = os.path.dirname(current_dir)
source_dir = os.environ.get('SOURCE_DIR', r"D:\obsidian")
source_static_dir = os.environ.get('SOURCE_STATIC_DIR', os.path.join(source_dir, "resources"))
target_content_dir = os.environ.get('TARGET_CONTENT_DIR', os.path.join(target_dir, "Content"))
target_static_dir = os.environ.get('TARGET_STATIC_DIR', os.path.join(target_dir, "Static"))
print(f"Sync start")
sync_directories(source_dir, target_content_dir)
sync_directories(source_static_dir, target_static_dir)
print(f"Sync end")
print()
if __name__ == "__main__":
main()
스크립트 설명
sync_directories
source_dir
과target_dir
을 비교하고 업데이트합니다.- 타겟 디렉토리가 없는 경우 생성합니다.
filecmp.dircmp
를 사용하여 디렉토리 비교를 수행합니다.- 소스 디렉토리에만 있는 파일 및 변경된 파일을 타겟 디렉토리로 복사합니다.
- 타겟 디렉토리에만 있는 파일을 삭제합니다.
- 공통 하위 디렉토리에 대해 재귀적으로 동일한 작업을 수행합니다.