diff --git a/batch_cleanup_journals.sh b/batch_cleanup_journals.sh new file mode 100644 index 0000000..93e3d97 --- /dev/null +++ b/batch_cleanup_journals.sh @@ -0,0 +1,112 @@ +#!/bin/bash +# Batch cleanup script for Logseq journal Task List query blocks +# Automatically excludes the most recent journal file to avoid disrupting active work + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CLEANUP_SCRIPT="$SCRIPT_DIR/clean_task_lists.py" + +# Default options +DRY_RUN=false +INCLUDE_MOST_RECENT=false + +# Parse arguments +while [[ $# -gt 0 ]]; do + case $1 in + --dry-run) + DRY_RUN=true + shift + ;; + --include-most-recent) + INCLUDE_MOST_RECENT=true + shift + ;; + -h|--help) + echo "Usage: $0 [OPTIONS] " + echo "" + echo "Options:" + echo " --dry-run Show what would be changed without modifying files" + echo " --include-most-recent Include the most recent file (normally excluded)" + echo " -h, --help Show this help message" + exit 0 + ;; + *) + if [[ -z "$JOURNALS_DIR" ]]; then + JOURNALS_DIR="$1" + fi + shift + ;; + esac +done + +# Check if journals directory was provided +if [[ -z "$JOURNALS_DIR" ]]; then + echo "Error: Please provide the journals directory path" + echo "Usage: $0 [--dry-run] " + exit 1 +fi + +# Check if cleanup script exists +if [[ ! -f "$CLEANUP_SCRIPT" ]]; then + echo "Error: Cleanup script not found at $CLEANUP_SCRIPT" + exit 1 +fi + +# Find all markdown files, sorted by name (which should be chronological for date-named files) +ALL_FILES=$(find "$JOURNALS_DIR" -name '*.md' -type f | sort) + +if [[ -z "$ALL_FILES" ]]; then + echo "No markdown files found in $JOURNALS_DIR" + exit 0 +fi + +# Count total files +TOTAL_FILES=$(echo "$ALL_FILES" | wc -l) +echo "Found $TOTAL_FILES journal files" + +# Determine which file to exclude (most recent - last in sorted list) +MOST_RECENT_FILE=$(echo "$ALL_FILES" | tail -n 1) +echo "Most recent file: $(basename "$MOST_RECENT_FILE")" + +if [[ "$INCLUDE_MOST_RECENT" == "true" ]]; then + echo "Including most recent file (--include-most-recent flag set)" + FILES_TO_PROCESS="$ALL_FILES" +else + echo "Excluding most recent file from processing" + # Remove the last line (most recent) + FILES_TO_PROCESS=$(echo "$ALL_FILES" | head -n -1) + PROCESSED_COUNT=$(echo "$FILES_TO_PROCESS" | wc -l) + echo "Processing $PROCESSED_COUNT files (excluding most recent)" +fi + +# Build command +CMD="python3 $CLEANUP_SCRIPT" +if [[ "$DRY_RUN" == "true" ]]; then + CMD="$CMD --dry-run" +fi +CMD="$CMD -r" + +# Process files +echo "" +echo "=========================================" +echo "Starting cleanup..." +echo "=========================================" +echo "" + +# Process each file individually to get per-file output +echo "$FILES_TO_PROCESS" | while read -r file; do + if [[ -n "$file" ]]; then + python3 "$CLEANUP_SCRIPT" "$file" $( [[ "$DRY_RUN" == "true" ]] && echo "--dry-run" ) + fi +done + +# Summary +echo "" +echo "=========================================" +echo "Cleanup complete!" +echo "=========================================" +if [[ "$DRY_RUN" == "true" ]]; then + echo "This was a DRY RUN - no files were modified" +fi +echo "Excluded most recent file: $(basename "$MOST_RECENT_FILE")" \ No newline at end of file diff --git a/clean_task_lists.py b/clean_task_lists.py new file mode 100644 index 0000000..a5b1944 --- /dev/null +++ b/clean_task_lists.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +""" +Logseq Task List Query Block Remover + +This script removes the "Task List" query blocks from Logseq journal pages. +Most days have two such blocks: +1. Work Task List (under work page reference) +2. Personal Task List (non-work tasks) + +The query blocks are marked with #+BEGIN_QUERY ... #+END_QUERY and contain +"title "✅ Task List"" or "title "✅ ToDo List"" in their configuration. +""" + +import re +import sys +from pathlib import Path +from typing import List, Tuple + + +def remove_task_list_queries(content: str) -> Tuple[str, int]: + """ + Remove all Task List query blocks from Logseq content. + + Args: + content: The Logseq markdown content + + Returns: + Tuple of (cleaned content, number of blocks removed) + """ + # Pattern to match Task List query blocks. Handles two formats: + # 1. With query-table:: line: "- query-table:: true" + "collapsed:: true" + "#+BEGIN_QUERY" + # 2. Without query-table:: line: "- collapsed:: true" + "#+BEGIN_QUERY" + # Both formats end with "#+END_QUERY" and contain :title "✅ Task List" or :title "✅ ToDo List" + pattern = r'(?:- query-table::\s*(?:true|false)\s*\n\s+collapsed::\s*true\s*\n\s*#\+BEGIN_QUERY[\s\S]*?:title\s*"[✅✓]?\s*(?:Task|ToDo)\s*List"[\s\S]*?#\+END_QUERY|- collapsed::\s*true\s*\n\s*#\+BEGIN_QUERY[\s\S]*?:title\s*"[✅✓]?\s*(?:Task|ToDo)\s*List"[\s\S]*?#\+END_QUERY)' + + # Find all matches first to count them + matches = re.findall(pattern, content) + count = len(matches) + + # Remove all Task List query blocks + cleaned = re.sub(pattern, '', content) + + return cleaned, count + + +def process_file(file_path: Path, dry_run: bool = False) -> bool: + """ + Process a single Logseq file. + + Args: + file_path: Path to the Logseq file + dry_run: If True, only report what would be changed + + Returns: + True if file was/would be modified, False otherwise + """ + 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 + + # Write cleaned content back + 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(): + """Main entry point for the script.""" + 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 without modifying files' + ) + parser.add_argument( + '--recursive', '-r', + action='store_true', + help='Process directories recursively' + ) + + args = parser.parse_args() + + target = args.path + dry_run = args.dry_run + + # Collect files to process + files = [] + + if target.is_file(): + if target.suffix.lower() not in ['.md', '.markdown']: + print(f"Warning: {target.name} doesn't look like a markdown file") + response = input("Process anyway? [y/N]: ") + if response.lower() != 'y': + sys.exit(0) + files.append(target) + elif target.is_dir(): + if args.recursive: + files.extend(target.rglob('*.md')) + files.extend(target.rglob('*.markdown')) + else: + files.extend(target.glob('*.md')) + files.extend(target.glob('*.markdown')) + else: + print(f"Error: {target} is not a valid file or directory") + sys.exit(1) + + if not files: + print("No markdown files found to process") + sys.exit(0) + + print(f"Found {len(files)} markdown file(s)") + if dry_run: + print("DRY RUN - No files will be modified\n") + + # Process each file + modified_count = 0 + for file_path in sorted(files): + if process_file(file_path, dry_run): + modified_count += 1 + + # Summary + print(f"\n{'Would modify' if dry_run else 'Modified'} {modified_count} of {len(files)} file(s)") + + +if __name__ == '__main__': + main() \ No newline at end of file