Add Obsidian migration scripts by Claude

This commit is contained in:
Daniel McKnight 2026-11-12 19:14:28 -08:00
parent 57d637e02a
commit 3425a2afb5
2 changed files with 794 additions and 0 deletions

View file

@ -0,0 +1,162 @@
#!/usr/bin/env python3
"""
Normalize nested-list indentation in Markdown notes (e.g. after a Logseq -> Obsidian import).
Obsidian's Logseq Importer writes each nesting level as 2 columns, encoded "tabs then spaces"
with a tab worth 4 columns:
level 1: " - " level 2: "\t- " level 3: "\t - " level 4: "\t\t- "
That renders correctly, but it mixes tabs and spaces and doesn't match what Obsidian inserts
when you press Tab, so editing those lists gets messy. This script rewrites every list item so
that each level uses exactly one indent unit (a tab by default, matching Obsidian's default
"Indent using tabs"), and keeps the nesting the same.
How levels are worked out: within a list, a line indented further than the item above it is a
child of that item; one indented the same as an earlier item is its sibling. A paragraph or
heading at column 0 ends the list. Lines that belong to an item but aren't items themselves
(block ids like "^abc123", wrapped text, fenced code inside an item) move with their item and
keep their offset from it, so code inside items stays aligned.
Left untouched: YAML frontmatter, fenced code blocks outside lists, indented lines that aren't
in a list, lists inside blockquotes.
python3 normalize_list_indent.py --dry-run -r <vault> # list files that would change
python3 normalize_list_indent.py --diff note.md # show the exact changes
python3 normalize_list_indent.py -r <vault> # apply
python3 normalize_list_indent.py --indent 2 -r <vault> # 2 spaces per level instead
"""
import argparse
import difflib
import re
import sys
from pathlib import Path
LIST_ITEM = re.compile(r"^([ \t]*)([-*+]|\d{1,9}[.)])([ \t]+|$)")
FENCE = re.compile(r"^[ \t]*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)?(`{3,}|~{3,})")
def lead(line: str) -> str:
return line[: len(line) - len(line.lstrip(" \t"))]
class Normalizer:
def __init__(self, unit: str, tab_width: int):
self.unit = unit # one indent level in the output: "\t" or N spaces
self.tab_width = tab_width # how wide a tab is in the *input*
def col(self, line: str) -> int:
return len(lead(line).expandtabs(self.tab_width))
def normalize(self, text: str) -> str:
lines = text.split("\n")
start = 0
if lines and lines[0] == "---": # YAML frontmatter
for i in range(1, len(lines)):
if lines[i] in ("---", "..."):
start = i + 1
break
out = lines[:start]
stack = [] # open items as (input column, output level), outermost first
fence = None # (marker, owner item or None) while inside a fenced code block
for line in lines[start:]:
if fence:
marker, owner = fence
out.append(self.attach(line, owner) if owner else line)
stripped = line.strip()
if stripped.startswith(marker[0] * len(marker)) and not stripped.strip(marker[0]):
fence = None
continue
if not line.strip():
out.append("") # blank lines don't end a list
continue
c = self.col(line)
m = LIST_ITEM.match(line)
if m:
while stack and stack[-1][0] > c:
stack.pop()
if not stack or stack[-1][0] < c:
stack.append((c, len(stack)))
level = stack[-1][1]
new = self.unit * level + line[len(lead(line)):]
owner = (c, level)
elif c == 0:
stack.clear() # paragraph/heading ends the list
new, owner = line, None
else:
# Continuation text: belongs to the deepest item indented less than it.
owners = [s for s in stack if s[0] < c]
owner = owners[-1] if owners else None
new = self.attach(line, owner) if owner else line
out.append(new)
if fm := FENCE.match(line):
fence = (fm.group(1), owner)
return "\n".join(out)
def attach(self, line: str, owner) -> str:
"""Re-indent a non-item line so it keeps its offset from its (moved) owner item."""
if not line.strip():
return ""
orig_col, level = owner
extra = max(0, self.col(line) - orig_col)
return self.unit * level + " " * extra + line[len(lead(line)):]
def collect(target: Path, recursive: bool):
if target.is_file():
return [target]
if not target.is_dir():
sys.exit(f"Error: {target} is not a valid file or directory")
files = target.rglob("*.md") if recursive else target.glob("*.md")
return sorted(f for f in files if ".obsidian" not in f.parts and ".trash" not in f.parts)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("path", type=Path, help="file or directory to process")
ap.add_argument("-r", "--recursive", action="store_true", help="process directories recursively")
ap.add_argument("--dry-run", action="store_true", help="report changes without writing")
ap.add_argument("--diff", action="store_true", help="print a unified diff (implies --dry-run)")
ap.add_argument("--indent", default="tab",
help='output indent per level: "tab" (default, Obsidian\'s default) or a number of spaces')
ap.add_argument("--tab-width", type=int, default=4,
help="columns a tab is worth in the input (default 4, what the Importer assumes)")
a = ap.parse_args()
if a.indent == "tab":
unit = "\t"
elif a.indent.isdigit() and int(a.indent) > 0:
unit = " " * int(a.indent)
else:
sys.exit('--indent must be "tab" or a positive number of spaces')
dry = a.dry_run or a.diff
norm = Normalizer(unit, a.tab_width)
files = collect(a.path, a.recursive)
changed = 0
for f in files:
try:
text = f.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as e:
print(f" ERROR reading {f}: {e}")
continue
new = norm.normalize(text)
if new == text:
continue
changed += 1
n = sum(1 for x, y in zip(text.split("\n"), new.split("\n")) if x != y)
print(f" {'WOULD fix' if dry else 'Fixed'} {n} line(s) in {f}")
if a.diff:
sys.stdout.writelines(difflib.unified_diff(
text.splitlines(keepends=True), new.splitlines(keepends=True),
fromfile=f"{f} (before)", tofile=f"{f} (after)"))
if not dry:
f.write_text(new, encoding="utf-8")
print(f"\n{'Would modify' if dry else 'Modified'} {changed} of {len(files)} file(s)")
if __name__ == "__main__":
main()

View file

@ -0,0 +1,632 @@
#!/usr/bin/env python3
"""
Compare tags and pages in an Obsidian vault, and turn selected tags into page links.
Logseq treats #tag and [[page]] as the same thing; Obsidian doesn't. After an import you
often have tags like #neon-clary next to a page Work/neon-clary.md, and want the tag to
be a real link instead.
python3 tags_pages.py <vault> # interactive menu (recommended)
Or non-interactively:
python3 tags_pages.py <vault> tags [--sort name|count] # every tag + how often it's used
python3 tags_pages.py <vault> pages [--journals] # every page, minus dated journals
python3 tags_pages.py <vault> overlap # tags that have a matching page
python3 tags_pages.py <vault> replace neon-clary Docker # dry run: show what would change
python3 tags_pages.py <vault> replace neon-clary Docker --diff
python3 tags_pages.py <vault> replace neon-clary Docker --write
Matching a tag to a page: case-insensitive, and spaces/underscores in page names count as
hyphens (Obsidian tags can't contain spaces), so #Wedding-Planning matches "Wedding Planning.md".
A nested tag (#a/b) matches the page whose name is its last part ("b") or whose path ends in
"a/b". If several pages match, the tag is listed as ambiguous and skipped by `replace` unless you
pass --page to choose one.
Replacement: #neon-clary -> [[neon-clary]]. If the tag's spelling differs from the page name
(case, hyphens), the original text is kept as the alias: #docker -> [[Docker|docker]]
(use --no-alias to drop it). If the page name isn't unique in the vault, the link uses its path.
Only inline tags are replaced. Tags in YAML frontmatter (tags: ...) are counted by `tags` but
never changed, since frontmatter can't hold links. Code blocks, inline code, and "#" inside
URLs/links are ignored throughout.
The top-level Archive/ folder is skipped entirely (not listed, scanned, matched or changed).
Use --exclude DIR (repeatable) to choose the folders to skip, or --exclude '' to skip none.
"""
import argparse
import difflib
import pydoc
import re
import shutil
import sys
from collections import Counter, defaultdict
from pathlib import Path
INLINE_TAG = re.compile(r"(?<![^\s(\[{,;])#(" + r"[\w\-/]*[^\W\d][\w\-/]*" + r")", re.UNICODE)
FENCE = re.compile(r"^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)?(`{3,}|~{3,})")
# Spans on a line where '#' is not a tag: inline code, wikilinks, md links/urls, bare urls.
SKIP_SPANS = re.compile(r"`+[^`]*`+|\[\[[^\]]*\]\]|\]\([^)]*\)|<[^>\s]+>|\b[a-z][a-z0-9+.-]*://\S+", re.I)
FM_TAGS_INLINE = re.compile(r"^tags:\s*\[?(.*?)\]?\s*$")
FM_LIST_ITEM = re.compile(r"^\s*-\s*(.+?)\s*$")
JOURNAL = re.compile(r"(?:^|/)\d{4}-\d{2}-\d{2}$") # dated journal page, e.g. Work/Journals/2026-11-12
def norm(name: str) -> str:
return re.sub(r"[\s_]+", "-", name.strip()).lower()
def is_hidden(path: Path, vault: Path) -> bool:
return any(p.startswith(".") for p in path.relative_to(vault).parts)
DEFAULT_EXCLUDE = ["Archive"]
def md_files(vault: Path, exclude=()):
"""Markdown files in the vault, skipping hidden folders and the top-level folders in `exclude`."""
skip = {e.strip("/").lower() for e in exclude if e.strip("/")}
for p in sorted(vault.rglob("*.md")):
if not is_hidden(p, vault) and p.relative_to(vault).parts[0].lower() not in skip:
yield p
def split_frontmatter(lines):
"""Return index of first body line (0 if no frontmatter)."""
if lines and lines[0].strip() == "---":
for i in range(1, len(lines)):
if lines[i].strip() in ("---", "..."):
return i + 1
return 0
def frontmatter_tags(fm_lines):
tags, in_tags = [], False
for line in fm_lines:
if m := re.match(r"^(tags?|aliases?):", line):
in_tags = m.group(1).startswith("tag")
if in_tags and (rest := FM_TAGS_INLINE.match(re.sub(r"^tag:", "tags:", line))) and rest.group(1):
tags += [t.strip().strip("'\"").lstrip("#") for t in rest.group(1).split(",") if t.strip()]
in_tags = False
continue
if in_tags and (m := FM_LIST_ITEM.match(line)):
tags.append(m.group(1).strip("'\"").lstrip("#"))
elif in_tags and line.strip():
in_tags = False
return [t for t in tags if t]
def body_lines(lines, start):
"""Yield (index, line) for body lines outside fenced code blocks."""
fence = None
for i in range(start, len(lines)):
line = lines[i]
m = FENCE.match(line)
if fence:
if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence):
fence = None
continue
if m:
fence = m.group(1)
continue
yield i, line
def tag_matches(line):
"""Yield regex matches for inline tags in a line, skipping code/links/urls."""
skip = [m.span() for m in SKIP_SPANS.finditer(line)]
for m in INLINE_TAG.finditer(line):
if line[m.start() - 1: m.start()] == "\\":
continue
if any(a <= m.start() < b for a, b in skip):
continue
tag = m.group(1).rstrip("/")
if not tag:
continue
yield m, tag
class Vault:
def __init__(self, root: Path, exclude=()):
self.root = root
self.exclude = [e.strip("/") for e in exclude if e.strip("/")]
self.files = list(md_files(root, self.exclude))
self.pages = {p: p.relative_to(root).with_suffix("").as_posix() for p in self.files}
self.by_norm_name = defaultdict(list)
self.by_name = defaultdict(list)
for p, rel in self.pages.items():
self.by_norm_name[norm(p.stem)].append(rel)
self.by_name[p.stem.lower()].append(rel)
self._tags = None
def scan_tags(self):
"""{tag (as written, first-seen spelling per lowercase): Counter} plus per-file details."""
if self._tags is not None:
return self._tags
inline, front = Counter(), Counter()
spellings = defaultdict(Counter)
for p in self.files:
lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
start = split_frontmatter(lines)
for t in frontmatter_tags(lines[1:start - 1] if start else []):
front[t.lower()] += 1
spellings[t.lower()][t] += 1
for _, line in body_lines(lines, start):
for _, t in tag_matches(line):
inline[t.lower()] += 1
spellings[t.lower()][t] += 1
self._tags = (inline, front, spellings)
return self._tags
def pages_for_tag(self, tag: str):
key = norm(tag)
hits = list(self.by_norm_name.get(key, []))
if "/" in tag:
last = key.rsplit("/", 1)[-1]
hits += [r for r in self.by_norm_name.get(last, []) if r not in hits]
hits = [r for r in hits if norm(r).endswith(key)] or hits
return sorted(set(hits))
def link_target(self, rel: str) -> str:
"""Shortest unambiguous link text for a page (name if unique, else path)."""
name = rel.rsplit("/", 1)[-1]
return name if len(self.by_name[name.lower()]) == 1 else rel
def preferred(spellings: Counter) -> str:
return spellings.most_common(1)[0][0]
# ---------------- reports (shared by CLI and menu) ----------------
def sort_key(sort):
return (lambda r: r[0].lower()) if sort == "name" else (lambda r: (-r[1] - r[2], r[0].lower()))
def tags_report(v: Vault, sort="count", plain=False, filt=""):
inline, front, sp = v.scan_tags()
rows = [(preferred(sp[k]), inline[k], front[k]) for k in set(inline) | set(front) if filt in k]
rows.sort(key=sort_key(sort))
if plain:
return [r[0] for r in rows], ""
lines = [f"{'inline':>7} {'front':>6} tag"]
for t, n_in, n_fm in rows:
s = sp[t.lower()]
variants = f" ({len(s)} spellings: {', '.join(s)})" if len(s) > 1 else ""
lines.append(f"{n_in:>7} {n_fm or '':>6} #{t}{variants}")
return lines, f"{len(rows)} tags"
def listed_pages(v: Vault, journals=False):
return [r for r in v.pages.values() if journals or not JOURNAL.search(r)]
def pages_report(v: Vault, plain=False, filt="", journals=False):
rels = sorted((r for r in listed_pages(v, journals) if filt in r.lower()), key=str.lower)
if plain:
return rels, ""
lines = []
for r in rels:
dup = " (name not unique)" if len(v.by_name[r.rsplit("/", 1)[-1].lower()]) > 1 else ""
lines.append(r + dup)
hidden = "" if journals else f" ({len(v.pages) - len(listed_pages(v))} dated journal pages not shown)"
return lines, f"{len(rels)} pages{hidden}"
def overlap_rows(v: Vault):
"""[(tag, inline count, frontmatter count, [matching pages])] for tags that have a page."""
inline, front, sp = v.scan_tags()
rows = []
for k in set(inline) | set(front):
pages = v.pages_for_tag(k)
if pages:
rows.append((preferred(sp[k]), inline[k], front[k], pages))
return rows
def overlap_report(v: Vault, sort="count", plain=False, filt=""):
rows = [r for r in overlap_rows(v) if filt in r[0].lower()]
rows.sort(key=sort_key(sort))
if plain:
return [r[0] for r in rows if len(r[3]) == 1], ""
lines = [f"{'inline':>7} {'front':>6} {'tag':<30} page"]
amb = 0
for t, n_in, n_fm, pages in rows:
if len(pages) > 1:
amb += 1
lines.append(f"{n_in:>7} {n_fm or '':>6} #{t:<29} AMBIGUOUS: {' | '.join(pages)}")
else:
lines.append(f"{n_in:>7} {n_fm or '':>6} #{t:<29} {pages[0]}")
return lines, f"{len(rows)} tags have a page ({amb} ambiguous)"
def tag_examples(v: Vault, tag: str, limit=5):
"""A few 'path:line: text' samples of where an inline tag is used."""
k, out = tag.lower(), []
for p in v.files:
lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
for i, line in body_lines(lines, split_frontmatter(lines)):
if any(t.lower() == k for _, t in tag_matches(line)):
out.append(f"{v.pages[p]}:{i + 1}: {line.strip()[:150]}")
if len(out) >= limit:
return out
return out
# ---------------- replacing ----------------
def make_link(tag_text: str, target: str, alias=True) -> str:
name = target.rsplit("/", 1)[-1]
if not alias or tag_text == name:
return f"[[{target}]]" if target == name else f"[[{target}|{name}]]"
return f"[[{target}|{tag_text}]]"
def build_changes(v: Vault, plan: dict, alias=True):
"""plan: {lowercase tag: link target}. Returns ([(path, old, new, n)], Counter per tag)."""
changes, per_tag = [], Counter()
for p in v.files:
text = p.read_text(encoding="utf-8", errors="replace")
lines = text.split("\n")
new_lines, n = list(lines), 0
for i, line in body_lines(lines, split_frontmatter(lines)):
out, pos = [], 0
for m, t in tag_matches(line):
target = plan.get(t.lower())
if not target:
continue
out += [line[pos:m.start()], make_link(t, target, alias)]
pos = m.start(1) + len(t)
per_tag[t.lower()] += 1
n += 1
if out:
new_lines[i] = "".join(out) + line[pos:]
if n:
changes.append((p, text, "\n".join(new_lines), n))
return changes, per_tag
def diff_text(v: Vault, changes) -> str:
out = []
for p, old, new, _ in changes:
rel = p.relative_to(v.root).as_posix()
out += difflib.unified_diff(old.splitlines(True), new.splitlines(True), f"a/{rel}", f"b/{rel}")
return "".join(out)
def write_changes(changes):
for p, _, new, _ in changes:
p.write_text(new, encoding="utf-8")
def plan_summary(v: Vault, plan, per_tag):
_, _, sp = v.scan_tags()
return [f" #{preferred(sp[k])} -> [[{t}]]: {per_tag[k]} replacements" for k, t in plan.items()]
# ---------------- CLI subcommands ----------------
def emit(lines, summary):
print("\n".join(lines))
if summary:
print(f"\n{summary}", file=sys.stderr)
def cmd_tags(v, a):
emit(*tags_report(v, a.sort, a.plain))
def cmd_pages(v, a):
emit(*pages_report(v, a.plain, journals=a.journals))
def cmd_overlap(v, a):
emit(*overlap_report(v, a.sort, a.plain))
def cmd_replace(v: Vault, a):
inline, _, sp = v.scan_tags()
forced = {}
for spec in a.page or []:
tag, _, rel = spec.partition("=")
rel = rel.removesuffix(".md")
if rel not in v.pages.values():
sys.exit(f"--page {spec}: no page {rel!r} in vault")
forced[tag.lstrip("#").lower()] = rel
wanted = [r[0] for r in overlap_rows(v) if r[1]] if a.all else [t.lstrip("#") for t in a.tags]
if not wanted:
sys.exit("give one or more tags, or --all")
plan = {}
for t in sorted(wanted, key=lambda t: (-inline[t.lower()], t.lower())):
k = t.lower()
pages = [forced[k]] if k in forced else v.pages_for_tag(t)
if not pages:
print(f"skip #{t}: no matching page", file=sys.stderr)
elif len(pages) > 1:
print(f"skip #{t}: ambiguous ({' | '.join(pages)}); use --page '{t}=<path>'", file=sys.stderr)
elif not inline[k]:
print(f"skip #{t}: not used inline (frontmatter-only tags are not changed)", file=sys.stderr)
else:
target = v.link_target(pages[0])
if a.interactive:
r = ask(f"#{preferred(sp[k])} ({inline[k]} uses) -> [[{target}]] ? [y/N/q] ")
if r == "q":
break
if r != "y":
continue
plan[k] = target
if not plan:
print("nothing to replace", file=sys.stderr)
return
changes, per_tag = build_changes(v, plan, not a.no_alias)
if a.diff:
sys.stdout.write(diff_text(v, changes))
elif not a.write:
for p, _, _, n in changes:
print(f"{n:>5} {v.pages[p]}.md")
if a.write:
write_changes(changes)
total = sum(c[3] for c in changes)
print("\n" + "\n".join(plan_summary(v, plan, per_tag)), file=sys.stderr)
verb = "Replaced" if a.write else "Would replace"
print(f"{verb} {total} tags in {len(changes)} files" + ("" if a.write else " (dry run; add --write)"),
file=sys.stderr)
# ---------------- interactive menu ----------------
class Quit(Exception):
pass
def ask(prompt: str, default="") -> str:
try:
r = input(prompt).strip()
except EOFError:
print()
return "q"
return r or default
def choose(prompt: str, options: str, default: str) -> str:
"""Prompt until the answer is one of the single-letter `options`."""
while True:
r = ask(prompt, default).lower()[:1]
if r and r in options:
return r
print(f" please answer one of: {', '.join(options)}")
def show(lines, summary=""):
text = "\n".join(lines) + (f"\n\n{summary}" if summary else "") + "\n"
if sys.stdout.isatty() and len(lines) > shutil.get_terminal_size().lines - 3:
pydoc.pager(text)
if summary:
print(summary)
else:
print(text, end="")
def list_prompts(with_sort=True):
sort = "count"
if with_sort:
sort = "name" if choose("Sort by [c]ount or [n]ame? [c] ", "cn", "c") == "n" else "count"
filt = ask("Only show names containing (Enter for all): ").lower()
return {"sort": sort, "filt": filt} if with_sort else {"filt": filt}
def pick_page(v: Vault, prompt: str, candidates=None):
"""Let the user pick from candidates by number, or type a page path. Returns rel path or None."""
while True:
if candidates:
for i, c in enumerate(candidates, 1):
print(f" {i}) {c}")
r = ask(prompt)
if not r or r.lower() == "n":
return None
if candidates and r.isdigit() and 1 <= int(r) <= len(candidates):
return candidates[int(r) - 1]
rel = r.removesuffix(".md").strip("/")
if rel in v.pages.values():
return rel
hits = sorted(x for x in v.pages.values() if rel.lower() in x.lower())
if len(hits) == 1:
return hits[0]
print(f" no single page matches {r!r}" + (f"; {len(hits)} contain it:" if hits else ""))
candidates = hits[:20] if hits else candidates
def walk_overlap(v: Vault, plan: dict):
rows = sorted((r for r in overlap_rows(v) if r[1] and r[0].lower() not in plan), key=sort_key("count"))
if not rows:
print("No remaining tags with a matching page.")
return
print(f"\n{len(rows)} tags have a page. For each one: "
"[y]es replace, [n]o skip, [e]xamples, [d]one choosing, [a]bort replace.\n")
for i, (t, n_in, _, pages) in enumerate(rows, 1):
header = f"[{i}/{len(rows)}] #{t} ({n_in} uses)"
if len(pages) > 1:
print(f"{header} matches {len(pages)} pages:")
rel = pick_page(v, " Page number or path to link to (Enter to skip): ", pages)
if rel:
plan[t.lower()] = v.link_target(rel)
continue
target = v.link_target(pages[0])
while True:
r = choose(f"{header} -> [[{target}]] [y/n/e/d/a] [n] ", "ynedaq", "n")
if r == "e":
print("\n".join(" " + x for x in tag_examples(v, t)))
continue
break
if r == "y":
plan[t.lower()] = target
elif r == "d":
return
elif r in "aq":
raise Quit
def type_tags(v: Vault, plan: dict):
inline, _, sp = v.scan_tags()
print("\nType tag names (with or without #), separated by spaces. Enter on an empty line when done.")
while True:
r = ask("Tags: ")
if not r or r == "q":
return
for t in r.split():
t = t.lstrip("#")
k = t.lower()
if not inline[k]:
print(f" #{t}: not used as an inline tag" + (" (only in frontmatter)" if k in sp else ""))
continue
pages = v.pages_for_tag(t)
if len(pages) == 1:
plan[k] = v.link_target(pages[0])
print(f" #{preferred(sp[k])} ({inline[k]} uses) -> [[{plan[k]}]]")
continue
msg = "matches several pages:" if pages else "has no page with the same name."
print(f" #{t} {msg}")
rel = pick_page(v, " Page number or path to link to (Enter to skip): ", pages)
if rel:
plan[k] = v.link_target(rel)
print(f" #{preferred(sp[k])} ({inline[k]} uses) -> [[{plan[k]}]]")
def review_and_apply(v: Vault, plan: dict) -> bool:
"""Returns True if files were written."""
alias = True
while True:
changes, per_tag = build_changes(v, plan, alias)
total = sum(c[3] for c in changes)
print("\nPlanned replacements:")
print("\n".join(plan_summary(v, plan, per_tag)))
print(f"{total} tags in {len(changes)} files. "
f"Differently-spelled tags {'keep' if alias else 'drop'} their spelling as link text "
f"(e.g. {make_link('docker', 'Docker', alias)}).")
r = choose("[f]iles list, [d]iff, [t]oggle link text, [r]emove a tag, [w]rite, [c]ancel? ",
"fdtrwcq", "")
if r == "f":
show([f"{n:>5} {v.pages[p]}.md" for p, _, _, n in changes])
elif r == "d":
show(diff_text(v, changes).splitlines())
elif r == "t":
alias = not alias
elif r == "r":
for t in ask("Tags to remove from the plan: ").split():
plan.pop(t.lstrip("#").lower(), None)
if not plan:
print("Plan is empty.")
return False
elif r == "w":
if choose(f"Modify {len(changes)} files in {v.root}? This has no undo. [y/N] ", "ynq", "n") == "y":
write_changes(changes)
print(f"Replaced {total} tags in {len(changes)} files.")
return True
else:
return False
def replace_menu(v: Vault) -> bool:
plan = {}
while True:
print(f"\nReplace tags with page links ({len(plan)} tags chosen so far)")
print(" 1) Go through each tag that has a matching page")
print(" 2) Type tag names (also lets you link a tag to any page)")
if plan:
print(" 3) Review and apply")
print(" b) Back (discards choices)")
r = choose("> ", "123bq", "")
try:
if r == "1":
walk_overlap(v, plan)
elif r == "2":
type_tags(v, plan)
elif r == "3" and plan:
return review_and_apply(v, plan)
elif r in "bq":
return False
except Quit:
return False
if r in "12" and plan:
if choose("Review and apply now? [Y/n] ", "ynq", "y") == "y":
return review_and_apply(v, plan)
def interactive(root: Path, exclude):
v = Vault(root, exclude)
while True:
inline, front, _ = v.scan_tags()
n_overlap = len(overlap_rows(v))
print(f"\nVault: {v.root}")
if v.exclude:
print(f"Skipping: {', '.join(e + '/' for e in v.exclude)}")
print(f" 1) List tags ({len(set(inline) | set(front))})")
print(f" 2) List pages, excluding dated journals ({len(listed_pages(v))})")
print(f" 3) List tags that are also pages ({n_overlap})")
print(" 4) Replace tags with page links")
print(" q) Quit")
r = choose("> ", "1234q", "")
if r == "1":
show(*tags_report(v, **list_prompts()))
elif r == "2":
show(*pages_report(v, **list_prompts(with_sort=False)))
elif r == "3":
show(*overlap_report(v, **list_prompts()))
elif r == "4":
if replace_menu(v):
v = Vault(root, exclude) # rescan after writing
else:
return
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("vault", type=Path, help="vault folder (asked for if no arguments are given)")
ap.add_argument("--exclude", action="append", metavar="DIR",
help="top-level folder to ignore completely; repeatable "
f"(default: {', '.join(DEFAULT_EXCLUDE)}; --exclude '' to ignore none)")
sub = ap.add_subparsers(dest="cmd", help="omit for the interactive menu")
s = sub.add_parser("tags", help="list all tags with use counts")
s.add_argument("--sort", choices=["count", "name"], default="count")
s.add_argument("--plain", action="store_true", help="names only, for piping")
s = sub.add_parser("pages", help="list all pages")
s.add_argument("--plain", action="store_true", help="paths only, no annotations")
s.add_argument("--journals", action="store_true", help="include dated journal pages (YYYY-MM-DD)")
s = sub.add_parser("overlap", help="list tags that match a page")
s.add_argument("--sort", choices=["count", "name"], default="count")
s.add_argument("--plain", action="store_true", help="unambiguous tag names only, for piping into replace")
s = sub.add_parser("replace", help="replace tags with links to their page (dry run unless --write)")
s.add_argument("tags", nargs="*", help="tags to replace (with or without '#')")
s.add_argument("--all", action="store_true", help="every unambiguous overlapping tag")
s.add_argument("-i", "--interactive", action="store_true", help="confirm each tag")
s.add_argument("--page", action="append", metavar="TAG=PATH",
help="pick the page for an ambiguous tag, e.g. --page 'house=Personal/house'")
s.add_argument("--no-alias", action="store_true", help="don't keep the tag's spelling as a link alias")
s.add_argument("--diff", action="store_true", help="show a unified diff")
s.add_argument("--write", action="store_true", help="modify files")
argv = sys.argv[1:] or [ask("Vault folder: ") or "."]
a = ap.parse_args(argv)
vault = a.vault.expanduser()
if not vault.is_dir():
sys.exit(f"not a directory: {vault}")
root = vault.resolve()
exclude = DEFAULT_EXCLUDE if a.exclude is None else a.exclude
if not a.cmd:
try:
interactive(root, exclude)
except KeyboardInterrupt:
print()
return
{"tags": cmd_tags, "pages": cmd_pages, "overlap": cmd_overlap, "replace": cmd_replace}[a.cmd](Vault(root, exclude), a)
if __name__ == "__main__":
main()