Created
November 2, 2023 18:55
-
-
Save kfsone/5df121ceef4a18326dfcdefb9394973a to your computer and use it in GitHub Desktop.
MorphedDirCopy.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Credit: AutoGPT using OpenAI gpt4 | |
import argparse | |
import json | |
import os | |
import random | |
import shutil | |
from pathlib import Path | |
from random import randint | |
def random_letter(letter): | |
if letter.isupper(): | |
return chr(random.randint(65, 90)) | |
else: | |
return chr(random.randint(97, 122)) | |
def morph_name(name): | |
return ''.join([random_letter(c) if c.isalpha() else c for c in name]) | |
def each_path(src: Path, dst: Path, copy_suffix: str=""): | |
mappings = {} | |
work = [(src, dst)] | |
while work: | |
src_path, dst_path = work.pop() | |
for entry in src_path.iterdir(): | |
src_child = src_path / entry.name | |
dst_child = dst_path / morph_name(entry.name) | |
if entry.is_dir(): | |
work.append((src_child, dst_child)) | |
dst_child.mkdir(parents=True) | |
else: | |
real_copy = False | |
if src_child.suffix: | |
if src_child.suffix == copy_suffix: | |
dst_child = dst_path / entry.name | |
real_copy = True | |
else: | |
dst_child = dst_child.with_suffix(src_child.suffix) | |
old_size = src_child.stat().st_size | |
new_size = min(old_size, randint(1, 1024)) | |
with open(dst_child, "w") as df: | |
if real_copy: | |
df.write(src_child.read_text()) | |
elif new_size: | |
df.write(' '*new_size) | |
mappings[src_child] = dst_child | |
def patterned_copy(src, dest, max_size=1024): | |
if not src.exists() or not src.is_dir(): | |
raise ValueError(f'Source directory {src} does not exist or is not a directory.') | |
if dest.exists(): | |
if not dest.is_dir() or any(dest.iterdir()): | |
raise ValueError(f'Destination directory {dest} already exists and is not empty.') | |
else: | |
dest.mkdir(parents=True) | |
mappings = each_path(src, dest, ".resources") | |
with (dest / 'mappings.json').open('w') as mappings_file: | |
json.dump({"src": str(src), "dst": str(dest), "mappings": mappings}, mappings_file, indent=2) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description='Create a patterned copy of a directory tree.') | |
parser.add_argument('src', type=Path, help='Source directory') | |
parser.add_argument('dest', type=Path, help='Destination directory') | |
parser.add_argument('--max-size', type=int, default=1024, help='Maximum file size in bytes (default: 1024)') | |
args = parser.parse_args() | |
patterned_copy(args.src, args.dest, args.max_size) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment