Last active
May 2, 2020 22:09
-
-
Save felko/e8bac68ece2f8a3f52e954fe5be78952 to your computer and use it in GitHub Desktop.
Migrate your zettelkasten to the new link format
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.8 | |
import os | |
import sys | |
import re | |
import glob | |
ZK, = sys.argv[1:] | |
def make_link_regex(url_regex): | |
return re.compile(rf"\[(?P<text>[A-Za-z0-9\. \t]*)\]\((?P<url>{url_regex})\)") | |
SINGLE_ZETTEL_LINK = make_link_regex(r"z(?P<conn>cf)?:(?P<path>[^\t\n\\ \^\(\)\[\]\{\}]*?)") | |
ZETTEL_QUERY_LINK = make_link_regex(r"z(?P<conn>cf)?query://search(?P<query>[^\t\n\\ \^\(\)\[\]\{\}]*?)") | |
TAG_QUERY_LINK = make_link_regex(r"z(?P<conn>cf)?query://tags(?P<query>[^\t\n\\ \^\(\)\[\]\{\}]*?)") | |
link_formatter = lambda fmt: lambda match: ("<" + fmt + "{cf}>").format(**{**match.groupdict(), 'cf': '?cf' if match.group('conn') == 'cf' else ''}) | |
repl_single_zettel_link = link_formatter("{text}") | |
repl_zettel_query_link = link_formatter("z:zettels{query}") | |
repl_tag_query_link = link_formatter("z:tags{query}") | |
def replace_links(md): | |
step1 = re.sub(SINGLE_ZETTEL_LINK, repl_single_zettel_link, md) | |
step2 = re.sub(ZETTEL_QUERY_LINK, repl_zettel_query_link, step1) | |
step3 = re.sub(TAG_QUERY_LINK, repl_tag_query_link, step2) | |
return step3 | |
def main(): | |
os.chdir(ZK) | |
for zettel_path in glob.glob(f"[A-Za-z-_0-9]*.md"): | |
with open(zettel_path, 'r+') as file: | |
md = file.read() | |
updated = replace_links(md) | |
if md != updated: | |
print(f"Updated {zettel_path}") | |
file.seek(0) | |
file.truncate() | |
file.write(updated) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment