diff --git a/obsidian_migration/logseq_postprocess.py b/obsidian_migration/logseq_postprocess.py new file mode 100644 index 0000000..ae70112 --- /dev/null +++ b/obsidian_migration/logseq_postprocess.py @@ -0,0 +1,461 @@ +#!/usr/bin/env python3 +""" +Post-process the output of Obsidian's official Importer (Logseq format) for this vault. + +Importer does the real conversion (task markers, block ids/refs, tags, properties, pages...). +This script only adds what Importer doesn't do, editing its output line by line: + + 1. Split each journal note's "Work" / "Personal" top-level sections into + Work/Journals/YYYY-MM-DD.md and Personal/Journals/YYYY-MM-DD.md, and repoint + block links ([[...#^id]]) whose target block moved to the other file. + 2. Turn kept :LOGBOOK: / CLOCK: text (Importer's "Keep time tracking") into + "- [clock:: start--end]" items for the Logbook Auto-Clock plugin. + 3. Turn Importer's task details (" — priority A, scheduled [[date]], due [[date]] ...") + into Tasks-plugin emoji fields (⏫ ⏳ 📅 ➕ ✅ ❌ 🔁) so tasks show up in Tasks queries. + 4. Handle SCHEDULED:/DEADLINE: lines Importer left on non-task blocks (see --dated-notes). + +Run Importer with "Use daily notes settings" OFF and "Keep time tracking" ON, then: + + python3 logseq_postprocess.py # dry run + python3 logseq_postprocess.py --preview DIR # write results to DIR only + python3 logseq_postprocess.py --write # apply + +--write never overwrites an existing split journal (that day is skipped and reported), and +backs up every Importer file it moves or edits to a folder outside the vault first. +""" +import argparse +import datetime as dt +import re +import shutil +import sys +from collections import defaultdict +from pathlib import Path + +TS = r"\[(\d{4}-\d{2}-\d{2}) [A-Za-z]{2,3} (\d{2}:\d{2}(?::\d{2})?)\]" +CLOCK_RE = re.compile(r"^CLOCK:\s*" + TS + r"(?:--" + TS + r")?") +FENCE_RE = re.compile(r"^\s*(?:>\s*)*(?:[-*+]\s+)?(```|~~~)") +TASK_LINE = re.compile(r"^(\s*)- \[(.)\]") +BULLET = re.compile(r"^(\s*)- ") +DATE_LINE = re.compile(r"^\s*(SCHEDULED|DEADLINE):\s*<(\d{4}-\d{2}-\d{2})[^>]*>\s*$") +# Importer emits the section heading either bulleted ("- # Work #neonai") or not ("# Work #neonai"). +SECTION = re.compile(r"^(?:-\s+)?#{1,6}\s+(Work|Personal)\b", re.I) +JOURNAL_NAME = re.compile(r"^(\d{4}-\d{2}-\d{2})\.md$") +ANCHOR_TAIL = re.compile(r"\s\^[A-Za-z0-9-]+\s*$") +ANCHOR_ANY = re.compile(r"(?:^|\s)\^([A-Za-z0-9-]+)\s*$") +BLOCK_LINK = re.compile(r"(!?)\[\[([^\]|#]*)#\^([A-Za-z0-9-]+)(\|[^\]]*)?\]\]") +# Day links: [[2026-10-19]], [[Logseq/Journals/2026-10-19|...]], [[2026-10-19|Logseq/Journals/2026-10-19]] +DATE_LINK = re.compile(r"(!?)\[\[((?:[^\]|#]*/)?(\d{4}-\d{2}-\d{2}))(\|[^\]]*)?\]\]") +# Date inside any wikilink, e.g. [[2026-10-19]] or [[2026-10-19|Logseq/Journals/2026-10-19]] +WL_DATE = r"\[\[[^\]]*?(\d{4}-\d{2}-\d{2})[^\]]*\]\]" + +PRIORITY = {"A": "⏫", "B": "🔼", "C": "🔽"} +DATE_EMOJI = {"scheduled": "⏳", "due": "📅", "created": "➕", "completed": "✅", "cancelled": "❌"} +DETAIL_PRIO = re.compile(r"priority ([ABC])") +DETAIL_DATE = re.compile( + r"(scheduled|due) " + WL_DATE + r"(?: (\d{2}:\d{2}))?" + r"(?: (every \d* ?[a-z]+?) \(([.+]{1,2})\d+[ymwdh]\)| \(([^)]*)\))?") +DETAIL_STAMP = re.compile(r"(created|completed|cancelled) " + WL_DATE) + + +def lead(line: str) -> str: + return line[: len(line) - len(line.lstrip(" \t"))] + + +def width(line: str) -> int: + return len(lead(line).expandtabs(4)) + + +def reindent(line: str, delta: int) -> str: + """Shift leading whitespace by `delta` columns, keeping Importer's tabs-then-spaces style.""" + if not line.strip(): + return "" + w = max(0, width(line) + delta) + return "\t" * (w // 4) + " " * (w % 4) + line[len(lead(line)):] + + +def add_fields(line: str, fields: str) -> str: + """Append Tasks fields before a trailing ^block-id, if any.""" + m = ANCHOR_TAIL.search(line) + if m: + return line[: m.start()].rstrip() + f" {fields}" + line[m.start():] + return line.rstrip() + f" {fields}" + + +def owner_index(out, w): + """Index of the nearest preceding bullet that a line indented `w` columns belongs to.""" + for i in range(len(out) - 1, -1, -1): + if BULLET.match(out[i]) and width(out[i]) < w: + return i + return None + + +class Post: + def __init__(self, dated_mode: str): + self.dated_mode = dated_mode + self.today = dt.date.today().isoformat() + self.warnings = defaultdict(list) + self.stats = defaultdict(int) + + # ---------- per-line conversions (2, 3, 4) ---------- + def convert_task_details(self, line: str, warn) -> str: + anchor = ANCHOR_TAIL.search(line) + body = line[: anchor.start()] if anchor else line + idx = body.rfind(" — ") + if idx < 0: + return line + head, details = body[:idx], body[idx + 3:].strip() + prio = recur = "" + dates = {} + for part in details.split(", "): + if m := DETAIL_PRIO.fullmatch(part): + prio = PRIORITY[m.group(1)] + elif m := DETAIL_DATE.fullmatch(part): + kind, date, time, every, rep, raw_rep = m.groups() + dates[kind] = date + if time: + warn(f"dropped time {time} from {kind} date (Tasks has no times)") + if every: + recur = every + (" when done" if rep == ".+" else "") + elif raw_rep: + warn(f"unrecognised repeater ({raw_rep}) dropped") + elif m := DETAIL_STAMP.fullmatch(part): + dates[m.group(1)] = m.group(2) + else: + warn(f"task details not recognised, left as text: {details[:60]!r}") + return line + fields = " ".join(x for x in [ + prio, f"🔁 {recur}" if recur else "", + *(f"{DATE_EMOJI[k]} {dates[k]}" for k in ("created", "scheduled", "due", "completed", "cancelled") if k in dates), + ] if x) + self.stats["task_details"] += 1 + return add_fields(head, fields) + (line[anchor.start():] if anchor else "") + + def convert_lines(self, lines, warn): + out = [] + in_fence = in_log = False + log_indent, log_owner = "", None + for line in lines: + if in_fence: + out.append(line) + if FENCE_RE.match(line): + in_fence = False + continue + s = line.strip() + if in_log: + if s.startswith(":END:"): # same rule as Importer; keep any text after it as a bullet + in_log = False + rest = s[5:].lstrip(" ,;").strip() + if rest: + out.append(f"{log_indent}- {rest}") + warn(f"text after :END: kept as its own bullet: {rest[:50]!r}") + continue + m = CLOCK_RE.match(s) + if not m: + warn(f"unrecognised logbook line kept: {s[:60]!r}") + out.append(line) + continue + start = f"{m.group(1)}T{m.group(2)}" + end = f"{m.group(3)}T{m.group(4)}" if m.group(3) else None + owner_status = None + if log_owner is not None and (tm := TASK_LINE.match(out[log_owner])): + owner_status = tm.group(2) + if end is None: + if owner_status == "/": + self.stats["running_clocks"] += 1 + else: + end = start # the plugin would otherwise close it "now" on the next edit + task = out[log_owner].strip()[:60] if log_owner is not None else "?" + warn(f"closed an open clock (0m) on a task that isn't in progress: {task!r}") + out.append(f"{log_indent}- [clock:: {start}--{end or ''}]") + self.stats["clocks"] += 1 + continue + if s == ":LOGBOOK:": + in_log = True + log_indent = lead(line) + log_owner = owner_index(out, width(line)) + continue + if FENCE_RE.match(line): + in_fence = True + out.append(line) + continue + if m := DATE_LINE.match(line): + oi = owner_index(out, width(line)) + if oi is not None: + kind, date = m.groups() + emoji = "⏳" if kind == "SCHEDULED" else "📅" + target = out[oi] + if not TASK_LINE.match(target) and ( + self.dated_mode == "task" or (self.dated_mode == "future-task" and date >= self.today)): + target = re.sub(r"^(\s*)- ", r"\1- [ ] ", target, count=1) + self.stats["dated_notes_to_tasks"] += 1 + else: + self.stats["dated_notes_text"] += 1 + out[oi] = add_fields(target, f"{emoji} {date}") + continue + if TASK_LINE.match(line): + line = self.convert_task_details(line, warn) + out.append(line) + return out + + # ---------- journals (1) ---------- + def split_journal(self, text: str, date: str, warn, unsectioned: str): + fm = "" + body = text + if text.startswith("---\n"): + end = text.find("\n---\n", 4) + if end >= 0: + fm, body = text[: end + 5], text[end + 5:] + groups = defaultdict(list) + current, shift = None, 0 + for line in body.split("\n"): + if line.strip() and width(line) == 0: + if m := SECTION.match(line): + current, shift = m.group(1).capitalize(), -2 + continue + current, shift = unsectioned, 0 + warn(f"top-level block outside Work/Personal: {line.strip()[:50]!r}" + + ("" if unsectioned == "skip" else f" (put in {unsectioned})")) + if current is None: + if line.strip(): + groups[unsectioned].append(line) + continue + groups[current].append(reindent(line, shift) if shift else line) + result = {} + for sec, lines in groups.items(): + while lines and not lines[-1].strip(): + lines.pop() + while lines and not lines[0].strip(): + lines.pop(0) + if lines: + result[sec] = (fm, lines) + return result + + @staticmethod + def anchors(lines): + ids, in_fence = set(), False + for ln in lines: + if FENCE_RE.match(ln): + in_fence = not in_fence + continue + if not in_fence and (m := ANCHOR_ANY.search(ln)): + ids.add(m.group(1)) + return ids + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("vault", type=Path) + ap.add_argument("import_root", type=Path, help="Importer's output folder (absolute, or relative to the vault)") + ap.add_argument("--journals", type=Path, help="journal folder (default: /Journals)") + ap.add_argument("--unsectioned", choices=["skip", "Personal", "Work"], default="skip", + help="journals with top-level blocks outside a Work/Personal section: leave the whole " + "day untouched in the import folder to fix by hand (default), or put those blocks " + "in Personal/Work") + ap.add_argument("--dated-notes", choices=["text", "task", "future-task"], default="text", + help="non-task blocks with SCHEDULED/DEADLINE: keep as text with ⏳/📅 (default), " + "make them [ ] tasks, or make them tasks only if the date is today or later") + g = ap.add_mutually_exclusive_group() + g.add_argument("--write", action="store_true", help="apply changes in the vault") + g.add_argument("--preview", type=Path, help="write all results under this folder instead of the vault") + ap.add_argument("--backup", type=Path, help="backup folder for --write (default: next to this script)") + a = ap.parse_args() + + vault = a.vault.resolve() + root = (a.import_root if a.import_root.is_absolute() else vault / a.import_root).resolve() + journals = (a.journals if a.journals and a.journals.is_absolute() else + root / (a.journals or "Journals")).resolve() + for p, what in ((vault, "vault"), (root, "import folder"), (journals, "journals folder")): + if not p.is_dir(): + sys.exit(f"{what} not found: {p}") + if vault not in root.parents and root != vault: + sys.exit("The import folder must be inside the vault.") + + post = Post(a.dated_notes) + rel = lambda p: p.relative_to(vault).as_posix() + journals_rel = rel(journals) + + # Pass 1: split journals, convert lines, index block anchors. + planned = {} # vault-relative output path -> text lines (with frontmatter) + moved = [] # original journal paths to move to backup + edited = [] # Importer files edited in place + anchor_home = {} # (date, id) -> vault-relative note path without .md + split_of = defaultdict(dict) # date -> {section: path without .md} + skipped = [] + manual = [] # journals left in place for manual section fixes + for f in sorted(journals.glob("*.md")): + warn = lambda msg, n=rel(f): post.warnings[n].append(msg) + m = JOURNAL_NAME.match(f.name) + if not m: + warn("skipped: not a YYYY-MM-DD journal file name") + continue + date = m.group(1) + parts = post.split_journal(f.read_text(encoding="utf-8"), date, warn, a.unsectioned) + if "skip" in parts: + manual.append(rel(f)) + continue + targets = {sec: f"{sec}/Journals/{date}" for sec in parts} + clash = [t for t in targets.values() if (vault / f"{t}.md").exists()] + if clash: + skipped.append((rel(f), clash)) + continue + for sec, (fm, lines) in parts.items(): + lines = post.convert_lines(lines, warn) + planned[f"{targets[sec]}.md"] = [fm, lines, rel(f)] + split_of[date][sec] = targets[sec] + for i in post.anchors(lines): + anchor_home[(date, i)] = targets[sec] + moved.append(f) + post.stats["journals"] += 1 + + # Other Importer files (pages): convert lines in place. + journal_set = set(moved) | {journals / Path(s[0]).name for s in skipped} | {vault / m for m in manual} + for f in sorted(root.rglob("*.md")): + if f in journal_set or f.parent == journals and JOURNAL_NAME.match(f.name): + continue + warn = lambda msg, n=rel(f): post.warnings[n].append(msg) + text = f.read_text(encoding="utf-8") + fm, body = "", text + if text.startswith("---\n") and (end := text.find("\n---\n", 4)) >= 0: + fm, body = text[: end + 5], text[end + 5:] + planned[rel(f)] = [fm, post.convert_lines(body.split("\n"), warn), rel(f)] + post.stats["pages_scanned"] += 1 + + # Already-split journal notes (from an earlier run) may still link into days split only now: + # include them for link repointing only. + for sec in ("Work", "Personal"): + for f in sorted((vault / sec / "Journals").glob("*.md")): + r = rel(f) + if r in planned: + continue + text = f.read_text(encoding="utf-8") + fm, body = "", text + if text.startswith("---\n") and (end := text.find("\n---\n", 4)) >= 0: + fm, body = text[: end + 5], text[end + 5:] + planned[r] = [fm, body.split("\n"), r] + + # Pass 2: repoint links whose targets were split. + def fix_links(path_noext, line, warn): + def block(m): + bang, target, bid, alias = m.groups() + if target == "": + date_m = JOURNAL_NAME.match(Path(path_noext).name + ".md") + if not date_m: + return m.group(0) + home = anchor_home.get((date_m.group(1), bid)) + if home is None or home == path_noext: + return m.group(0) + else: + date_m = JOURNAL_NAME.match(Path(target).name + ".md") + if not date_m: + return m.group(0) + home = anchor_home.get((date_m.group(1), bid)) + if home is None: + return m.group(0) + post.stats["links_repointed"] += 1 + return f"{bang}[[{home}#^{bid}{alias or ''}]]" + + def day(m): + bang, target, date, alias = m.groups() + folder = target[: -len(date)].rstrip("/") + if folder and folder != journals_rel: + return m.group(0) # some other note named like a date; not an imported journal + homes = split_of.get(date) or {} + if not homes: + return m.group(0) + # Prefer the note in the same section as the linking note; else the default section. + section = path_noext.split("/", 1)[0] + home = homes.get(section) or homes.get("Personal") or next(iter(homes.values())) + display = (alias or "|")[1:] + if not display or display.endswith(date): + display = date # Importer sometimes puts the journal path in the display text + post.stats["links_repointed"] += 1 + return f"{bang}[[{home}|{display}]]" + + parts = re.split(r"(`[^`\n]*`)", line) + for i in range(0, len(parts), 2): + parts[i] = DATE_LINK.sub(day, BLOCK_LINK.sub(block, parts[i])) + return "".join(parts) + + changed_pages = [] + for out_rel, entry in planned.items(): + fm, lines, src = entry + warn = lambda msg, n=src: post.warnings[n].append(msg) + noext = out_rel[:-3] + in_fence = False + new = [] + for ln in lines: + if FENCE_RE.match(ln): + in_fence = not in_fence + new.append(ln) + continue + new.append(ln if in_fence else fix_links(noext, ln, warn)) + entry[1] = new + text = fm + "\n".join(new).rstrip("\n") + "\n" + entry.append(text) + if out_rel == src: # a page edited in place + if text != (vault / src).read_text(encoding="utf-8"): + changed_pages.append(out_rel) + else: + entry.append("unchanged") + + # Output + mode = "WRITE" if a.write else ("PREVIEW -> " + str(a.preview) if a.preview else "DRY RUN (use --preview DIR or --write)") + print(mode) + for out_rel, entry in sorted(planned.items()): + if entry[2] == out_rel and out_rel not in changed_pages: + continue + verb = "edit" if entry[2] == out_rel else f"create (from {entry[2]})" + print(f" {verb:<10} {out_rel}") + for src in manual: + print(f" LEAVE {src}: has blocks outside Work/Personal; fix by hand, then re-run") + for src, clash in skipped: + print(f" SKIP {src}: already exists -> {', '.join(c + '.md' for c in clash)}") + if not a.write: + print(f" {'(original journals would be moved to a backup folder outside the vault)' if moved else ''}") + + if a.preview: + for out_rel, entry in planned.items(): + if entry[2] == out_rel and out_rel not in changed_pages: + continue + dest = a.preview / out_rel + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_text(entry[3], encoding="utf-8") + elif a.write: + backup = (a.backup or Path(__file__).resolve().parent / "backups") / dt.datetime.now().strftime("%Y%m%d-%H%M%S") + if vault in backup.resolve().parents: + sys.exit("Backup folder must be outside the vault.") + for f in moved: + b = backup / rel(f) + b.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(f, b) + for p in changed_pages: + b = backup / p + b.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(vault / p, b) + for out_rel, entry in planned.items(): + if entry[2] == out_rel and out_rel not in changed_pages: + continue + dest = vault / out_rel + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_text(entry[3], encoding="utf-8") + for f in moved: + f.unlink() + print(f"\nBackup of moved/edited Importer files: {backup}") + + s = post.stats + print(f"\n{s['journals']} journals split | {len(skipped)} skipped (exist) | {len(manual)} left for manual fixes | {s['pages_scanned']} other files scanned, " + f"{len(changed_pages)} changed | {s['clocks']} clock entries ({s['running_clocks']} running) | " + f"{s['task_details']} tasks given Tasks fields | {s['links_repointed']} links repointed | " + f"dated notes: {s['dated_notes_text']} text, {s['dated_notes_to_tasks']} -> tasks") + if post.warnings: + print("\nWarnings:") + for name in sorted(post.warnings): + counts = defaultdict(int) + for msg in post.warnings[name]: + counts[msg] += 1 + for msg, n in counts.items(): + print(f" {name}: {msg}" + (f" (x{n})" if n > 1 else "")) + + +if __name__ == "__main__": + main()