Repository navigation
Expand file tree
/
Copy pathlogseqPageExport.py
More file actions
114 lines (92 loc) · 4.12 KB
/
Copy pathlogseqPageExport.py
File metadata and controls
114 lines (92 loc) · 4.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import os
import sys
import re
import datetime
from pathlib import Path
# ==================== CONFIGURATION ====================
# Paths to your local Logseq directories
# JOURNALS_DIR = r"/home/user/Documents/LogSeq/journals"
# JOURNALS_DIR = r"C:\Users\YourName\Documents\Logseq\journals"
JOURNALS_DIR = Path.home() / "Documents/LogSeq/journals"
PAGES_DIR = Path.home() / "Documents/LogSeq/pages"
# =======================================================
def find_case_insensitive_page(pages_dir, page_name):
"""Finds the page markdown file on Linux by matching lowercase names."""
if not pages_dir.exists():
return None
target_filename = f"{page_name.lower()}.md"
for entry in os.scandir(pages_dir):
if entry.is_file() and entry.name.lower() == target_filename:
return Path(entry.path)
return None
def extract_linked_blocks(file_path, tag):
with open(file_path, "r", encoding="utf-8") as f:
lines = f.readlines()
clean_tag = tag.replace("[", "").replace("]", "").lower()
extracted_content = []
inside_target_block = False
target_indent = -1
for line in lines:
stripped = line.lstrip()
if not stripped or not stripped.startswith("- "):
continue
indent_level = len(line) - len(stripped)
if not inside_target_block:
if clean_tag in line.lower():
inside_target_block = True
target_indent = indent_level
extracted_content.append(line)
else:
if indent_level <= target_indent:
if clean_tag in line.lower():
target_indent = indent_level
extracted_content.append(line)
else:
inside_target_block = False
else:
extracted_content.append(line)
return "".join(extracted_content)
def main():
if len(sys.argv) < 2:
print("Error: Missing target tag parameter.")
print("Usage: python export_logseq.py <tag_or_page_name>")
print("Example: python export_logseq.py fastmail")
sys.exit(1)
raw_tag = sys.argv[1]
search_tag = raw_tag if raw_tag.startswith("[[") else f"[[{raw_tag}]]"
safe_filename_tag = raw_tag.replace("[", "").replace("]", "").replace(" ", "_")
# 1. Read and prepend the core Page file text if it exists
page_content = ""
matched_page_path = find_case_insensitive_page(PAGES_DIR, raw_tag)
if matched_page_path and matched_page_path.exists():
print(f"Found core page file: {matched_page_path.name}")
with open(matched_page_path, "r", encoding="utf-8") as f:
page_content = f.read().strip()
if page_content:
page_content = f"# Core Page: {raw_tag}\n\n{page_content}\n\n"
else:
print(f"⚠️ Note: No core page file found for '{raw_tag}' in {PAGES_DIR}. Skipping prepend.")
# 2. Extract references from Journal files
if not JOURNALS_DIR.exists():
print(f"Error: The directory '{JOURNALS_DIR}' does not exist. Check configuration.")
return
journal_files = sorted(list(JOURNALS_DIR.glob("*.md")))
journal_output = []
for file_path in journal_files:
date_str = file_path.stem.replace("_", "-")
blocks = extract_linked_blocks(file_path, search_tag)
if blocks:
journal_output.append(f"# {date_str}\n\n{blocks}\n")
# 3. Assemble and export to Current Working Directory
if page_content or journal_output:
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H")
output_filename = f"{safe_filename_tag}_{timestamp}.md"
output_file = Path.cwd() / output_filename
full_markdown_payload = page_content + "\n".join(journal_output)
with open(output_file, "w", encoding="utf-8") as f:
f.write(full_markdown_payload.strip() + "\n")
print(f"✅ Success! Output saved to your current directory: {output_file}")
else:
print(f"⚠️ No contents or journal block hierarchies found for '{search_tag}'")
if __name__ == "__main__":
main()