notes-utils/clean_task_lists.py

99 lines
No EOL
3.1 KiB
Python
Executable file

#!/usr/bin/env python3
"""
Logseq Task List Query Block Remover
"""
import re
import sys
from pathlib import Path
from typing import Tuple
def remove_task_list_queries(content: str) -> Tuple[str, int]:
"""
Remove all Task List query blocks from Logseq content.
Handles multiple formats:
1. - query-table:: + collapsed:: (no dash) + #+BEGIN_QUERY
2. collapsed:: (no dash) + - query-table:: + #+BEGIN_QUERY
3. - collapsed:: + #+BEGIN_QUERY
4. - #+BEGIN_QUERY (direct with dash)
5. #+BEGIN_QUERY (no dash, no prefix - just whitespace)
"""
# Pattern handles all 5 formats above
pattern = r'(?:- query-table::\s*(?:true|false)\s*\n\s+collapsed::\s*true\s*\n\s*#\+BEGIN_QUERY|collapsed::\s*true\s*\n\s*- query-table::\s*(?:true|false)\s*\n\s*#\+BEGIN_QUERY|- collapsed::\s*true\s*\n\s*#\+BEGIN_QUERY|- #\+BEGIN_QUERY|\s*#\+BEGIN_QUERY)[\s\S]*?:title\s*"[✅✓]?\s*(?:Task|ToDo)\s*List"[\s\S]*?#\+END_QUERY'
matches = re.findall(pattern, content)
count = len(matches)
cleaned = re.sub(pattern, '', content)
return cleaned, count
def process_file(file_path: Path, dry_run: bool = False) -> bool:
try:
content = file_path.read_text(encoding='utf-8')
except Exception as e:
print(f" ERROR reading {file_path}: {e}")
return False
cleaned, count = remove_task_list_queries(content)
if count == 0:
print(f" No Task List blocks found in {file_path.name}")
return False
if dry_run:
print(f" WOULD remove {count} Task List block(s) from {file_path.name}")
return True
try:
file_path.write_text(cleaned, encoding='utf-8')
print(f" ✓ Removed {count} Task List block(s) from {file_path.name}")
return True
except Exception as e:
print(f" ERROR writing {file_path}: {e}")
return False
def main():
import argparse
parser = argparse.ArgumentParser(description='Remove Task List query blocks from Logseq notes')
parser.add_argument('path', type=Path, help='File or directory to process')
parser.add_argument('--dry-run', action='store_true', help='Show what would be changed')
parser.add_argument('--recursive', '-r', action='store_true', help='Process recursively')
args = parser.parse_args()
target = args.path
dry_run = args.dry_run
files = []
if target.is_file():
files.append(target)
elif target.is_dir():
if args.recursive:
files.extend(target.rglob('*.md'))
else:
files.extend(target.glob('*.md'))
else:
print(f"Error: {target} is not valid")
sys.exit(1)
if not files:
print("No markdown files found")
sys.exit(0)
print(f"Found {len(files)} markdown file(s)")
if dry_run:
print("DRY RUN\n")
modified_count = 0
for file_path in sorted(files):
if process_file(file_path, dry_run):
modified_count += 1
print(f"\n{'Would modify' if dry_run else 'Modified'} {modified_count} of {len(files)} file(s)")
if __name__ == '__main__':
main()