This commit is contained in:
olivier committed 2025-10-28 11:14:35 -04:00
commit 3d122b5022
8 files changed
+1065

No files matched your search

Binary file not shown.
+675
View File
@@ -0,0 +1,675 @@
#!/usr/bin/env python3
import click
import os
import yaml
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path
import re
from typing import List, Union, Optional, Dict, Any
from urllib.parse import quote
class OnyxCLI:
def __init__(self):
self.config_file = Path.home() / '.onyx-cli' / 'config.yaml'
self._ensure_config_exists()
self.default_vault = self._load_default_vault()
if self.default_vault:
try:
self.vault_path = self._get_vault_path(self.default_vault)
except click.UsageError:
# Vault is set but not configured - will be handled by commands
self.vault_path = None
else:
self.vault_path = None
def _ensure_config_exists(self):
self.config_file.parent.mkdir(parents=True, exist_ok=True)
if not self.config_file.exists():
self.config_file.write_text(yaml.dump({'default_vault': None, 'vaults': {}}))
def _load_default_vault(self):
if self.config_file.exists():
config = yaml.safe_load(self.config_file.read_text())
return config.get('default_vault')
return None
def _get_vault_path(self, vault_name: str) -> Path:
config = yaml.safe_load(self.config_file.read_text())
vault_path = config.get('vaults', {}).get(vault_name)
if not vault_path:
raise click.UsageError(f"Vault '{vault_name}' not found in config")
return Path(vault_path)
def _get_vault_and_path(self, vault: Optional[str] = None) -> tuple[str, Path]:
vault_name = vault or self.default_vault
if not vault_name:
raise click.UsageError("No vault specified. Either set a default vault or provide --vault option")
vault_path = self._get_vault_path(vault_name)
return vault_name, vault_path
def _get_daily_note_settings(self, vault_path: Path) -> Dict[str, Any]:
"""
Get daily note settings from Periodic Notes plugin (if enabled),
falling back to core Daily Notes plugin if not available.
Returns a dict with: format, folder, template
"""
# Try Periodic Notes plugin first
periodic_notes_config = vault_path / ".obsidian" / "plugins" / "periodic-notes" / "data.json"
if periodic_notes_config.exists():
try:
config = json.loads(periodic_notes_config.read_text())
daily_config = config.get('daily', {})
# Check if daily notes are enabled in Periodic Notes
if daily_config.get('enabled', False):
return {
'format': daily_config.get('format', 'YYYY-MM-DD'),
'folder': daily_config.get('folder', ''),
'template': daily_config.get('template', '')
}
except (json.JSONDecodeError, KeyError):
pass # Fall through to core plugin
# Fall back to core Daily Notes plugin
daily_notes_config = vault_path / ".obsidian" / "daily-notes.json"
if daily_notes_config.exists():
try:
config = json.loads(daily_notes_config.read_text())
return {
'format': config.get('format', 'YYYY-MM-DD'),
'folder': config.get('folder', ''),
'template': config.get('template', '')
}
except (json.JSONDecodeError, KeyError):
pass
# Default settings if neither plugin is configured
return {
'format': 'YYYY-MM-DD',
'folder': '',
'template': ''
}
def set_default_vault(self, vault_name: str, vault_path: str = None):
try:
config = yaml.safe_load(self.config_file.read_text()) if self.config_file.exists() else {}
except Exception:
config = {}
config.setdefault('vaults', {})
if vault_path is not None:
# If path is provided, always update or create the vault entry
try:
resolved_path = Path(vault_path).resolve()
if not resolved_path.exists():
click.echo(f"Creating vault directory: {resolved_path}")
resolved_path.mkdir(parents=True, exist_ok=True)
config['vaults'][vault_name] = str(resolved_path)
except Exception as e:
raise click.UsageError(f"Error setting vault path: {str(e)}")
elif vault_name not in config['vaults']:
# If no path and vault doesn't exist, show error
raise click.UsageError(
f"Vault '{vault_name}' not found. Please provide the path when setting a new vault:\n"
f"ob-cli set-default \"{vault_name}\" --path \"path/to/vault\""
)
config['default_vault'] = vault_name
self.config_file.write_text(yaml.dump(config))
self.default_vault = vault_name
actual_path = config['vaults'][vault_name]
click.echo(f"Default vault set to: {vault_name}")
click.echo(f"Vault path: {actual_path}")
def print_default(self):
if not self.default_vault:
click.echo("No default vault set")
return
config = yaml.safe_load(self.config_file.read_text())
vault_path = config.get('vaults', {}).get(self.default_vault)
if not vault_path:
raise click.UsageError(
f"Vault '{self.default_vault}' not found in config. Please set it up with:\n"
f"ob-cli set-default \"{self.default_vault}\" --path \"path/to/vault\""
)
click.echo(f"Default vault: {self.default_vault}")
click.echo(f"Path: {vault_path}")
def create_note(self, note_name: str, content: str = "", vault: str = None,
overwrite: bool = False, append: bool = False, open_after: bool = False):
vault_name, vault_path = self._get_vault_and_path(vault)
note_path = vault_path / note_name
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
note_path.parent.mkdir(parents=True, exist_ok=True)
if note_path.exists():
if overwrite:
mode = 'w'
elif append:
mode = 'a'
else:
raise click.UsageError(f"Note {note_name} already exists. Use --overwrite or --append to modify")
else:
mode = 'w'
with note_path.open(mode) as f:
if append and note_path.exists():
f.write('\n')
f.write(content)
click.echo(f"Note {'updated' if note_path.exists() else 'created'}: {note_path}")
if open_after:
self.open_note(note_name, vault_name)
def open_note(self, note_name: str, vault: str = None):
vault_name, vault_path = self._get_vault_and_path(vault)
# Try exact path first
note_path = vault_path / note_name
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
# If not found, try in daily notes folder if configured
# if not note_path.exists():
# settings = self._get_daily_note_settings(vault_path)
# if settings['folder']:
# daily_note_path = vault_path / settings['folder'] / f"{note_name}.md"
# if daily_note_path.exists():
# note_path = daily_note_path
# If still not found, try searching the entire vault
if not note_path.exists():
matches = list(vault_path.rglob(f"{note_name}.md"))
if matches:
note_path = matches[0] # Use first match
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
# Get the relative path from the vault root for the URI
relative_path = note_path.relative_to(vault_path)
# URL encode both the vault name and file path to handle special characters
encoded_vault = self._url_encode(vault_name)
encoded_file = self._url_encode(relative_path.as_posix())
uri = f"obsidian://open?vault={encoded_vault}&file={encoded_file}"
self._open_uri(uri)
def _convert_moment_format(self, moment_format: str) -> str:
"""Convert moment.js date format to Python strftime format."""
# Handle literal text in brackets first (e.g., [W] -> W)
result = re.sub(r'\[([^\]]+)\]', r'\1', moment_format)
# Use non-printable placeholders to avoid conflicts
# Order matters: process longest patterns first
placeholders = [
('YYYY', '\x001'),
('MMMM', '\x002'),
('dddd', '\x003'),
('MMM', '\x004'),
('ddd', '\x005'),
('Do', '\x006'),
('YY', '\x007'),
('MM', '\x008'),
('DD', '\x009'),
('HH', '\x00A'),
('hh', '\x00B'),
('mm', '\x00C'),
('ss', '\x00D'),
('M', '\x00E'),
('D', '\x00F'),
('H', '\x010'),
('h', '\x011'),
('A', '\x012'),
('a', '\x013'),
]
strftime_codes = {
'\x001': '%Y',
'\x007': '%y',
'\x002': '%B',
'\x004': '%b',
'\x008': '%m',
'\x00E': '%m',
'\x009': '%d',
'\x00F': '%d',
'\x006': '%d',
'\x003': '%A',
'\x005': '%a',
'\x00A': '%H',
'\x010': '%H',
'\x00B': '%I',
'\x011': '%I',
'\x00C': '%M',
'\x00D': '%S',
'\x012': '%p',
'\x013': '%p',
}
# First pass: replace moment patterns with placeholders
for moment_pattern, placeholder in placeholders:
result = result.replace(moment_pattern, placeholder)
# Second pass: replace placeholders with strftime codes
for placeholder, strftime_code in strftime_codes.items():
result = result.replace(placeholder, strftime_code)
return result
def _create_or_open_periodic_note(self, note_type: str, vault: str = None):
"""Generic method to create or open periodic notes."""
vault_name, vault_path = self._get_vault_and_path(vault)
# Get settings from plugin
settings = self._get_daily_note_settings(vault_path)
# Load periodic notes settings if available
periodic_notes_config = vault_path / ".obsidian" / "plugins" / "periodic-notes" / "data.json"
if periodic_notes_config.exists():
try:
config = json.loads(periodic_notes_config.read_text())
note_config = config.get(note_type, {})
if note_config.get('enabled', False):
settings = {
'format': note_config.get('format', 'YYYY-MM-DD'),
'folder': note_config.get('folder', ''),
'template': note_config.get('template', '')
}
except (json.JSONDecodeError, KeyError):
pass
# Convert format and generate filename
date_format = self._convert_moment_format(settings['format'])
# Handle week format specially for ISO weeks
if 'W' in settings['format'] and '[W]' in settings['format']:
# Handle formats like "yyyy-[W]WW" or "YYYY-[W]WW" or "yy-[W]WW"
# Use ISO week number
year_format = 'yyyy' if 'yyyy' in settings['format'] else ('YYYY' if 'YYYY' in settings['format'] else 'yy')
if year_format == 'yyyy' or year_format == 'YYYY':
year = datetime.now().strftime('%G') # ISO year (4 digits)
else:
year = datetime.now().strftime('%g') # ISO year (2 digits)
week = datetime.now().strftime('%V') # ISO week number
filename = f"{year}-W{week}"
else:
filename = datetime.now().strftime(date_format)
# Get template content if specified
content = ""
if settings['template']:
template_path = vault_path / settings['template']
if not template_path.suffix:
template_path = template_path.with_suffix('.md')
if template_path.exists():
content = template_path.read_text()
# Construct note path with folder
folder = settings['folder']
if folder:
note_path = f"{folder}/{filename}.md"
else:
note_path = f"{filename}.md"
# Check if note exists
full_note_path = vault_path / note_path
if not full_note_path.suffix:
full_note_path = full_note_path.with_suffix('.md')
if full_note_path.exists():
# Note exists, just open it
self.open_note(note_path, vault_name)
else:
# Note doesn't exist, create and open it
self.create_note(note_path, content=content, vault=vault_name, open_after=True)
def daily_note(self, vault: str = None):
"""Create or open today's daily note."""
self._create_or_open_periodic_note('daily', vault)
def weekly_note(self, vault: str = None):
"""Create or open this week's note."""
self._create_or_open_periodic_note('weekly', vault)
def monthly_note(self, vault: str = None):
"""Create or open this month's note."""
self._create_or_open_periodic_note('monthly', vault)
def quarterly_note(self, vault: str = None):
"""Create or open this quarter's note."""
self._create_or_open_periodic_note('quarterly', vault)
def yearly_note(self, vault: str = None):
"""Create or open this year's note."""
self._create_or_open_periodic_note('yearly', vault)
def print_note(self, note_name: str, vault: str = None):
vault_name, vault_path = self._get_vault_and_path(vault)
note_path = vault_path / note_name
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
click.echo(note_path.read_text())
def move_note(self, current_path: str, new_path: str, vault: str = None, open_after: bool = False):
vault_name, vault_path = self._get_vault_and_path(vault)
current = vault_path / current_path
if not current.suffix:
current = current.with_suffix('.md')
new = vault_path / new_path
if not new.suffix:
new = new.with_suffix('.md')
if not current.exists():
raise click.UsageError(f"Note {current_path} does not exist")
new.parent.mkdir(parents=True, exist_ok=True)
current.rename(new)
# Update internal links in all vault files
old_link_pattern = f"\\[\\[{current.stem}\\]\\]"
new_link = f"[[{new.stem}]]"
for md_file in vault_path.rglob("*.md"):
if md_file != new: # Skip the moved file
content = md_file.read_text()
updated_content = re.sub(old_link_pattern, new_link, content)
if updated_content != content:
md_file.write_text(updated_content)
click.echo(f"Moved {current_path} to {new_path}")
if open_after:
self.open_note(new_path, vault_name)
def delete_note(self, note_path: str, vault: str = None):
vault_name, vault_path = self._get_vault_and_path(vault)
note = vault_path / note_path
if not note.suffix:
note = note.with_suffix('.md')
if not note.exists():
raise click.UsageError(f"Note {note_path} does not exist")
note.unlink()
click.echo(f"Deleted {note_path}")
def _parse_frontmatter(self, content: str) -> tuple[dict, str, int]:
if not content.startswith('---\n'):
return {}, content, 0
parts = content.split('---\n', 2)
if len(parts) < 3:
return {}, content, 0
try:
frontmatter = yaml.safe_load(parts[1]) or {}
return frontmatter, parts[2], len(parts[0]) + len(parts[1]) + 6
except yaml.YAMLError:
return {}, content, 0
def _update_frontmatter(self, note_path: Path, updates: dict):
content = note_path.read_text()
frontmatter, rest_content, fm_length = self._parse_frontmatter(content)
frontmatter.update(updates)
new_content = '---\n'
new_content += yaml.dump(frontmatter, default_flow_style=False)
new_content += '---\n'
new_content += rest_content if fm_length else content
note_path.write_text(new_content)
def frontmatter_edit(self, note_name: str, key: str, value: str = None, vault: str = None):
vault_name, vault_path = self._get_vault_and_path(vault)
note_path = vault_path / note_name
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
# Handle multiple keys
keys = [k.strip() for k in re.split(r',|\[|\]', key) if k.strip()]
updates = {}
for k in keys:
if k == 'tags':
if value:
updates[k] = value.split(',') if ',' in value else [value]
else:
updates[k] = []
else:
updates[k] = value if value is not None else ""
self._update_frontmatter(note_path, updates)
click.echo(f"Updated frontmatter for {note_name}")
def frontmatter_view(self, note_name: str, key: str, value: str = None, vault: str = None):
vault_name, vault_path = self._get_vault_and_path(vault)
note_path = vault_path / note_name
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
content = note_path.read_text()
frontmatter, _, _ = self._parse_frontmatter(content)
if key not in frontmatter:
click.echo(f"Key '{key}' not found in frontmatter")
return
if value is not None:
# Check if value exists
current_value = frontmatter[key]
if isinstance(current_value, list):
result = value in current_value
else:
result = str(current_value) == value
click.echo(str(result).lower())
else:
click.echo(yaml.dump({key: frontmatter[key]}, default_flow_style=False).strip())
def frontmatter_clear(self, note_name: str, key: str, vault: str = None):
vault_name, vault_path = self._get_vault_and_path(vault)
note_path = vault_path / note_name
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
keys = [k.strip() for k in re.split(r',|\[|\]', key) if k.strip()]
updates = {}
for k in keys:
updates[k] = [] if k == 'tags' else ""
self._update_frontmatter(note_path, updates)
click.echo(f"Cleared frontmatter values for {note_name}")
def frontmatter_delete(self, note_name: str, key: str, vault: str = None):
vault_name, vault_path = self._get_vault_and_path(vault)
note_path = vault_path / note_name
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
content = note_path.read_text()
frontmatter, rest_content, _ = self._parse_frontmatter(content)
keys = [k.strip() for k in re.split(r',|\[|\]', key) if k.strip()]
modified = False
for k in keys:
if k in frontmatter:
del frontmatter[k]
modified = True
if modified:
if frontmatter:
new_content = '---\n'
new_content += yaml.dump(frontmatter, default_flow_style=False)
new_content += '---\n'
new_content += rest_content
else:
new_content = rest_content
note_path.write_text(new_content)
click.echo(f"Deleted frontmatter keys from {note_name}")
else:
click.echo("No matching keys found in frontmatter")
def _url_encode(self, text: str) -> str:
"""URL encode a string, preserving forward slashes."""
return quote(text, safe='/')
def _open_uri(self, uri: str):
"""Open URI using the appropriate command for the current platform."""
if sys.platform == 'darwin': # macOS
subprocess.run(['open', uri])
elif sys.platform == 'win32': # Windows
os.startfile(uri)
else: # Linux
subprocess.run(['xdg-open', uri])
# CLI Commands
@click.group(name='ob-cli')
def cli():
"""Onyx CLI - Interact with Obsidian from the command line"""
pass
@cli.command()
@click.argument('vault_name')
@click.option('--path', help="Path to the vault directory")
def set_default(vault_name, path):
"""Set the default vault for future operations"""
# Convert Windows backslashes to forward slashes if needed
if path:
path = str(Path(path))
OnyxCLI().set_default_vault(vault_name, path)
@cli.command()
def print_default():
"""Print the current default vault and its path"""
OnyxCLI().print_default()
@cli.command()
@click.argument('note_name')
@click.option('--vault', help="Vault name (if not using default)")
def open(note_name, vault):
"""Open a note in Obsidian"""
OnyxCLI().open_note(note_name, vault)
@cli.command()
@click.option('--vault', help="Vault name (if not using default)")
def daily(vault):
"""Create or open today's daily note"""
OnyxCLI().daily_note(vault)
@cli.command()
@click.option('--vault', help="Vault name (if not using default)")
def weekly(vault):
"""Create or open this week's note"""
OnyxCLI().weekly_note(vault)
@cli.command()
@click.option('--vault', help="Vault name (if not using default)")
def monthly(vault):
"""Create or open this month's note"""
OnyxCLI().monthly_note(vault)
@cli.command()
@click.option('--vault', help="Vault name (if not using default)")
def quarterly(vault):
"""Create or open this quarter's note"""
OnyxCLI().quarterly_note(vault)
@cli.command()
@click.option('--vault', help="Vault name (if not using default)")
def yearly(vault):
"""Create or open this year's note"""
OnyxCLI().yearly_note(vault)
@cli.command()
@click.argument('note_name')
@click.option('--content', default="", help="Content to write to the note")
@click.option('--vault', help="Vault name (if not using default)")
@click.option('--overwrite', is_flag=True, help="Overwrite existing note")
@click.option('--append', is_flag=True, help="Append to existing note")
@click.option('--open', 'open_after', is_flag=True, help="Open note after creation")
def create(note_name, content, vault, overwrite, append, open_after):
"""Create a new note in the vault"""
OnyxCLI().create_note(note_name, content, vault, overwrite, append, open_after)
@cli.command()
@click.argument('note_name')
@click.option('--vault', help="Vault name (if not using default)")
def print_note(note_name, vault):
"""Print the contents of a note"""
OnyxCLI().print_note(note_name, vault)
@cli.command()
@click.argument('current_path')
@click.argument('new_path')
@click.option('--vault', help="Vault name (if not using default)")
@click.option('--open', 'open_after', is_flag=True, help="Open note after moving")
def move(current_path, new_path, vault, open_after):
"""Move/rename a note and update all internal links"""
OnyxCLI().move_note(current_path, new_path, vault, open_after)
@cli.command()
@click.argument('note_path')
@click.option('--vault', help="Vault name (if not using default)")
def delete(note_path, vault):
"""Delete a note"""
OnyxCLI().delete_note(note_path, vault)
@cli.command(name='frontmatter')
@click.argument('note_name')
@click.option('--edit', is_flag=True, help="Edit frontmatter")
@click.option('--view', is_flag=True, help="View frontmatter")
@click.option('--clear', is_flag=True, help="Clear frontmatter values")
@click.option('--delete', is_flag=True, help="Delete frontmatter keys")
@click.option('--key', required=True, help="Frontmatter key to manage")
@click.option('--value', help="Value to set or check for")
@click.option('--vault', help="Vault name (if not using default)")
def frontmatter_command(note_name, edit, view, clear, delete, key, value, vault):
"""Manage note frontmatter"""
cli = OnyxCLI()
if sum([edit, view, clear, delete]) != 1:
raise click.UsageError("Exactly one of --edit, --view, --clear, or --delete must be specified")
if edit:
cli.frontmatter_edit(note_name, key, value, vault)
elif view:
cli.frontmatter_view(note_name, key, value, vault)
elif clear:
cli.frontmatter_clear(note_name, key, vault)
elif delete:
cli.frontmatter_delete(note_name, key, vault)
if __name__ == '__main__':
cli()