分享:将 org-roam 笔记转换成 denote 格式的脚本

这个脚本用 python 写的。

import os
import re
import sys
from datetime import datetime
import shutil

def sanitize_title(title):
    title = title.lower()
    title = re.sub(r'[^\w\s-]', '_', title)
    title = re.sub(r'\s+', '_', title)
    return title.strip('_')

def convert_signature(signature):
    if not signature:
        return 'z'
    return signature.replace('.', '=').replace('/', '=')

def get_creation_time(file_path):
    return datetime.fromtimestamp(os.path.getctime(file_path))

def generate_denote_filename(file_path, title, signature):
    creation_time = get_creation_time(file_path)
    date_str = creation_time.strftime("%Y%m%dT%H%M%S")
    sanitized_title = sanitize_title(title)
    converted_signature = convert_signature(signature)
    extension = os.path.splitext(file_path)[1]
    
    return f"{date_str}=={converted_signature}--{sanitized_title}{extension}"

def extract_title_and_signature(content):
    title_match = re.search(r'#\+title:\s*(.+)', content)
    signature_match = re.search(r'#\+signature:\s*(.+)', content)
    
    title = title_match.group(1) if title_match else "Untitled"
    signature = signature_match.group(1) if signature_match else ""
    
    return title, signature

def migrate_org_roam_to_denote(org_roam_dir, denote_dir):
    print(f"Starting migration from {org_roam_dir} to {denote_dir}")
    
    if not os.path.exists(org_roam_dir):
        print(f"Error: Source directory {org_roam_dir} does not exist.")
        return
    
    if not os.path.exists(denote_dir):
        print(f"Creating destination directory: {denote_dir}")
        os.makedirs(denote_dir)

    org_files = [f for f in os.listdir(org_roam_dir) if f.endswith(".org")]
    print(f"Found {len(org_files)} .org files in the source directory.")

    for filename in org_files:
        filepath = os.path.join(org_roam_dir, filename)
        print(f"Processing file: {filename}")
        
        try:
            with open(filepath, 'r', encoding='utf-8') as file:
                content = file.read()

            title, signature = extract_title_and_signature(content)
            new_filename = generate_denote_filename(filepath, title, signature)
            new_filepath = os.path.join(denote_dir, new_filename)

            # Copy the file instead of rewriting it
            shutil.copy2(filepath, new_filepath)

            print(f"Migrated: {filename} -> {new_filename}")
        except Exception as e:
            print(f"Error processing {filename}: {str(e)}")

    print("Migration completed.")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python org-roam-to-denote.py <org_roam_dir> <denote_dir>")
        sys.exit(1)

    org_roam_dir = sys.argv[1]
    denote_dir = sys.argv[2]
    migrate_org_roam_to_denote(org_roam_dir, denote_dir)

使用时输入: python org-roam-to-denote.py <org_roam_dir> <denote_dir>

5 个赞