Created
May 1, 2023 02:14
-
-
Save gabrielfeo/1c91629a746d1bc9aef5ed755a50a267 to your computer and use it in GitHub Desktop.
Craft attachment import fix
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
#!/usr/bin/env python3 | |
import shutil | |
import argparse | |
from pathlib import Path | |
from urllib.parse import quote | |
def prefix_assets(dir_path): | |
for assets_dir in dir_path.rglob("*.assets"): | |
assert assets_dir.is_dir() | |
note_name = assets_dir.name[:-len('.assets')] | |
md_file = assets_dir.parent / f"{note_name}.md" | |
assert md_file.exists() | |
for asset in assets_dir.glob('*'): | |
assert asset.is_file() | |
new_file_path = asset.with_name(f"{note_name}_{asset.name}") | |
asset.rename(new_file_path) | |
# rewrite links to old png paths in the corresponding md file | |
with open(md_file, 'r+') as f: | |
md_content = f.read() | |
old_link = quote(f"{assets_dir.name}/{asset.name}", safe='/:') | |
new_link = quote(f"{assets_dir.name}/{new_file_path.name}", safe='/:') | |
md_content = md_content.replace(old_link, new_link) | |
f.seek(0) | |
f.write(md_content) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description='Rename files in .assets directories to fix Craft importing of its own exports') | |
parser.add_argument('--input-dir', type=Path, required=True) | |
parser.add_argument('--output-dir', type=Path, required=True) | |
args = parser.parse_args() | |
shutil.copytree(args.input_dir, args.output_dir) | |
prefix_assets(args.output_dir) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment