diff --git a/.github/workflows/github-actions-insert-svg-refs.yml b/.github/workflows/github-actions-insert-svg-refs.yml new file mode 100644 index 0000000..7cf90ac --- /dev/null +++ b/.github/workflows/github-actions-insert-svg-refs.yml @@ -0,0 +1,18 @@ +name: GitHub Actions Demo +run-name: Convert excalidraw to svg references +on: [push] +jobs: + Excalidraw-To-SVG: + runs-on: ubuntu-latest + steps: + - name: Check out repository code + uses: actions/checkout@v4 + - name: Set up Python 3.12 + uses: actions/setup-python@v4 + with: + # Semantic version range syntax or exact version of a Python version + python-version: '3.12' + # Optional - x64 or x86 architecture, defaults to x64 + architecture: 'x64' + - run: python main.py ${{ github.workspace }} + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..485dee6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea diff --git a/main.py b/main.py new file mode 100644 index 0000000..5bf4cdb --- /dev/null +++ b/main.py @@ -0,0 +1,74 @@ +from pathlib import Path +from sys import argv, stderr +import re + +excalidraw_re = re.compile(r"\[\[(.*\.excalidraw)\]\]") + + +def eprint(*args, **kwargs): + print(*args, file=stderr, **kwargs) + + +def iter_svgs(vault_path, draws): + for draw in draws: + svg = Path("assets/excalidraw_svg").joinpath(Path(draw).with_suffix(".svg").name) + if vault_path.joinpath(svg).is_file(): + print(svg) + yield draw, svg + else: + eprint(svg) + yield draw, None + + +def iter_refs(vault_path): + pages = [path for path in vault_path.joinpath("pages").glob("*") if path.is_file()] + for page in pages: + with open(page) as f: + content = f.read() + for ref_match in excalidraw_re.finditer(content): + yield page, ref_match + + +def get_draws(vault_path): + draws = set() + pages = set() + for page, ref_match in iter_refs(vault_path): + draws.add(ref_match[1]) + pages.add(page) + return pages, draws + + +def main() -> None: + """ + Replaces excalidraw file references with svg references + If .svg exists in assets/excalidraw_svg it will be used, + otherwise it will be replaced with + + :return: + """ + vault_path = Path(argv[1]).expanduser() + pages, draws = get_draws(vault_path) + + replace_dict = {} + for draw, svg in iter_svgs(vault_path, draws): + if svg is None: + replace_dict[f"[[{draw}]]"] = "

MISSING IMAGE

" + else: + replace_dict[f"[[{draw}]]"] = f"[[{svg}]]" + + print(replace_dict) + print(pages) + + for page in pages: + with open(page) as f: + content = f.read() + + for prev, new in replace_dict.items(): + content = content.replace(prev, new) + + with open(page, "w") as f: + f.write(content) + + +if __name__ == "__main__": + main()