Skip to content

Instantly share code, notes, and snippets.

@jepler
Last active August 27, 2024 18:49
Show Gist options
  • Save jepler/126cbf31ff349be62d453d102aa68634 to your computer and use it in GitHub Desktop.
Save jepler/126cbf31ff349be62d453d102aa68634 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import subprocess
import pathlib
import click
def gross_lektor_parser(content):
parsed = {}
for c in content.split("\n---\n"):
if ':' in c:
k, v = c.split(":", 1)
else:
k, v = "name", c
parsed[k.strip()] = v.strip()
return parsed
def fspath_to_webpath(s):
s = pathlib.Path(s.removeprefix("content/")).parent
return f"/{s}/"
def is_redirect(filename):
content = pathlib.Path(filename).read_text(encoding="utf-8")
parsed = gross_lektor_parser(content)
new_path = parsed.get("new_path", None)
model = parsed.get("_model", None)
if new_path and model != "redirect":
print(f"Suspicious: {new_path=} {model=}")
return new_path
def create_redirect_webpath(src, dest):
src_path = pathlib.Path(f"content/{src}/contents.lr")
print(src_path)
src_path.parent.mkdir(parents=True, exist_ok=True)
src_path.write_text(
f"""\
_model: redirect
---
new_path: {dest}
---
_discoverable: no
"""
)
print(f"{src_path}: Created or updated redirect to {dest} (may need to git add)")
@click.command
def main():
num_redirects = 0
missing = set()
files = subprocess.check_output(
[
"git",
"-c",
"core.quotePath=true",
"ls-files",
"**/contents.lr",
],
encoding="utf-8",
).splitlines()
redirects = {}
for file in files:
target = is_redirect(file)
redirects[fspath_to_webpath(file)] = target
for src, dest in redirects.items():
if dest is None:
continue
dest2 = redirects.get(dest, None)
if dest2:
print(f"Double redirect: {src} -> {dest} -> {dest2}")
create_redirect_webpath(src, dest2)
if __name__ == "__main__":
main()
#!/usr/bin/env python
import subprocess
import pathlib
import click
def fspath_to_webpath(s):
s = pathlib.Path(s.removeprefix("content/")).parent
return f"/{s}/"
def maybe_unquote(s):
if s.startswith('"'):
raise ValueError("Quoted filenames not supported. Choose boring filenames.")
return s
def create_redirect(src, dest):
src_path = pathlib.Path(src)
src_path.parent.mkdir(parents=True, exist_ok=True)
src_path.write_text(
f"""\
_model: redirect
---
new_path: {fspath_to_webpath(dest)}
---
_discoverable: no
"""
)
print(f"{src}: Created or updated redirect to {dest} (may need to git add)")
@click.command
@click.argument("branch", default="HEAD")
@click.argument("base", default="lektor")
def main(branch, base):
num_redirects = 0
missing = set()
diff = subprocess.check_output(
[
"git",
"-c",
"core.quotePath=true",
"diff",
"--name-status",
f"{base}...{branch}",
"**/contents.lr"
],
encoding="utf-8",
).splitlines()
for row in diff:
if row.startswith("R"):
stat, src, dst = row.split("\t", 3)
src = maybe_unquote(src)
dest = maybe_unquote(dst)
create_redirect(src, dest)
num_redirects += 1
elif row.startswith("D"):
stat, src = row.split("\t", 2)
src = maybe_unquote(src)
if src.endswith(".lr") and not "+" in src:
missing.add(src)
print()
print(f"Created/updated {num_redirects} redirects.")
if missing:
print()
for src in missing:
print(f"{src}: File removed, may need a manual redirect")
print(f"{len(missing)} redirects may need to be created manually")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment