Skip to content

Instantly share code, notes, and snippets.

@procrastinatio
Created July 29, 2024 15:38
Show Gist options
  • Save procrastinatio/a48578e39cf49f9acade6e0298feadc4 to your computer and use it in GitHub Desktop.
Save procrastinatio/a48578e39cf49f9acade6e0298feadc4 to your computer and use it in GitHub Desktop.
Intelligent directory copy
#!/usr/bin/env python3
import os
import shutil
from pathlib import Path
import argparse
def parse_arguments():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description="Process directories and files.")
parser.add_argument(
"--target-dir", default="toto", help="Target directory to work with."
)
parser.add_argument(
"--source-dir",
default="input",
help="Source directory to search for input data.",
)
parser.add_argument(
"--temp-dir", default="tmp", help="Temporary directory to store data."
)
parser.add_argument(
"--yes",
action="store_true",
help="Automatically confirm all actions without prompting.",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Run in test mode, only printing actions without executing them.",
)
return parser.parse_args()
def create_directories(directories, base_dir, test_mode):
"""Create directories under the base directory."""
for directory in directories:
dir_path = os.path.join(base_dir, directory)
if test_mode:
print(f"Test mode: Would create directory {dir_path}")
else:
try:
os.makedirs(dir_path, exist_ok=True)
except IOError as e:
print(f"Error creating directory {dir_path}: {e}")
def list_subdirectories(directory):
"""List all subdirectories in the given directory."""
return [os.path.join(root, d) for root, dirs, _ in os.walk(directory) for d in dirs]
def prompt_yes_no(question, default_yes=False):
"""Prompt the user with a yes/no question."""
prompt = f"{question} ? ({'Y/n' if default_yes else 'y/N'}): "
ans = input(prompt).strip().lower()
if not ans and default_yes:
return True
while ans not in ["y", "n", ""]:
print(f"Invalid response '{ans}', please enter 'y' or 'n'.")
ans = input(prompt).strip().lower()
return ans == "y"
def copy_directories(source_dirs, target_base_dir, temp_dir, dry_run, yes):
"""Copy directories from source to a temporary location if they don't exist in the target."""
target_subdirs = list_subdirectories(target_base_dir)
for src_dir in source_dirs:
dirname = Path(src_dir).stem
found = any(dirname in os.path.basename(path) for path in target_subdirs)
if not found:
print(f"Directory '{dirname}' not found in target; processing...")
temp_path = os.path.join(temp_dir, dirname)
if not yes:
dry_run = not prompt_yes_no(f"Copy {src_dir} to {temp_path}")
if dry_run:
print(f"Dry-run mode: Would copy {src_dir} to {temp_path}")
else:
try:
shutil.copytree(src_dir, temp_path)
except (OSError, IOError) as e:
print(f"Error copying {src_dir} to {temp_path}: {e}")
if __name__ == "__main__":
args = parse_arguments()
# List directories in the source directory
source_subdirs = list_subdirectories(args.source_dir)
print("Source subdirectories:", source_subdirs)
# Process and potentially copy directories
copy_directories(
source_subdirs, args.target_dir, args.temp_dir, args.dry_run, args.yes
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment