Files
onyx-cli/src/onyx.py
T
olivier a82cb97267 feat: Enhance OnyxCLI functionality
- Added functionality to open directories in the system explorer when a directory path is provided.
- Improved output formatting for frontmatter values in the OnyxCLI, allowing for raw value display when a single key is requested.
- Updated the `things to fix.md` with new tasks: trimming content of tags and adding multiple properties at once.
2025-12-27 20:00:37 -05:00

865 lines
33 KiB
Python

#!/usr/bin/env python3
import click
import os
import yaml
import json
import subprocess
import sys
import datetime
import builtins
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': {}}), encoding='utf-8-sig')
def _load_default_vault(self):
if self.config_file.exists():
config = yaml.safe_load(self.config_file.read_text(encoding='utf-8-sig'))
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(encoding='utf-8-sig'))
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(encoding='utf-8-sig'))
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(encoding='utf-8-sig'))
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(encoding='utf-8-sig')) 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"onyx set-default \"{vault_name}\" --path \"path/to/vault\""
)
config['default_vault'] = vault_name
self.config_file.write_text(yaml.dump(config), encoding='utf-8-sig')
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(encoding='utf-8-sig'))
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"onyx set-default \"{self.default_vault}\" --path \"path/to/vault\""
)
click.echo(f"Default vault: {self.default_vault}")
click.echo(f"Path: {vault_path}")
def _get_template_folder(self, vault_path: Path) -> Optional[Path]:
"""
Get template folder path from Templater plugin (if enabled),
falling back to core Templates plugin.
"""
# Try Templater plugin first
templater_config = vault_path / ".obsidian" / "plugins" / "templater-obsidian" / "data.json"
if templater_config.exists():
try:
config = json.loads(templater_config.read_text(encoding='utf-8-sig'))
folder = config.get('templates_folder')
if folder:
return vault_path / folder
except (json.JSONDecodeError, KeyError):
pass
# Fall back to core Templates plugin
templates_config = vault_path / ".obsidian" / "templates.json"
if templates_config.exists():
try:
config = json.loads(templates_config.read_text(encoding='utf-8-sig'))
folder = config.get('folder')
if folder:
return vault_path / folder
except (json.JSONDecodeError, KeyError):
pass
return None
def create_note(self, note_name: str, content: str = "", vault: str = None,
overwrite: bool = False, append: bool = False, open_after: bool = False, template: str = None):
vault_name, vault_path = self._get_vault_and_path(vault)
note_path = vault_path / note_name
if not str(note_path).endswith('.md'):
note_path = Path(str(note_path) + '.md')
if template:
template_folder = self._get_template_folder(vault_path)
if template_folder:
template_path = template_folder / template
if not template_path.suffix:
template_path = template_path.with_suffix('.md')
if template_path.exists():
template_content = template_path.read_text(encoding='utf-8-sig')
if content:
content = template_content + '\n' + content
else:
content = template_content
# Open by default if template is used
open_after = True
else:
click.echo(f"Warning: Template '{template}' not found at {template_path}")
else:
click.echo("Warning: Template folder not configured")
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, encoding='utf-8-sig') 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
# Check if it's a directory first
if note_path.is_dir():
# Open directory in system explorer
if sys.platform == 'win32':
os.startfile(note_path)
elif sys.platform == 'darwin':
subprocess.run(['open', note_path])
else:
subprocess.run(['xdg-open', note_path])
return
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(encoding='utf-8-sig'))
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.datetime.now().strftime('%G') # ISO year (4 digits)
else:
year = datetime.datetime.now().strftime('%g') # ISO year (2 digits)
week = datetime.datetime.now().strftime('%V') # ISO week number
filename = f"{year}-W{week}"
else:
filename = datetime.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(encoding='utf-8-sig')
# 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(encoding='utf-8-sig'))
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(encoding='utf-8-sig')
updated_content = re.sub(old_link_pattern, new_link, content)
if updated_content != content:
md_file.write_text(updated_content, encoding='utf-8-sig')
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(encoding='utf-8-sig')
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, encoding='utf-8-sig')
def frontmatter_edit(self, note_name: str, keys: tuple, values: tuple = 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():
matches = list(vault_path.rglob(f"{note_name}.md"))
if matches:
note_path = matches[0]
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
updates = {}
# If we have one value and multiple keys, apply value to all keys
if values and len(values) == 1 and len(keys) > 1:
values = values * len(keys)
for i, key in enumerate(keys):
# Handle comma-separated keys in a single string (legacy support)
sub_keys = [k.strip() for k in re.split(r',|\[|\]', key) if k.strip()]
value = values[i] if values and i < len(values) else None
for k in sub_keys:
if k == 'tags':
if value:
updates[k] = [t.strip() for t in value.split(',')] if ',' in value else [value.strip()]
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, keys: tuple, value: str = None, vault: str = None, open_file: 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')
if not note_path.exists():
matches = list(vault_path.rglob(f"{note_name}.md"))
if matches:
note_path = matches[0]
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
content = note_path.read_text(encoding='utf-8-sig')
frontmatter, _, _ = self._parse_frontmatter(content)
for key in keys:
# Handle comma-separated keys (legacy)
sub_keys = [k.strip() for k in re.split(r',|\[|\]', key) if k.strip()]
for k in sub_keys:
if k not in frontmatter:
click.echo(f"Key '{k}' not found in frontmatter")
continue
if open_file:
self._handle_open_file(frontmatter[k], vault)
continue
if value is not None:
# Check if value exists
current_value = frontmatter[k]
if isinstance(current_value, list):
result = value in current_value
else:
result = str(current_value) == value
click.echo(f"{k}: {str(result).lower()}")
else:
# If single key requested and no value check, print raw value
if len(keys) == 1 and len(sub_keys) == 1:
click.echo(str(frontmatter[k]))
else:
click.echo(yaml.dump({k: frontmatter[k]}, default_flow_style=False).strip())
def _handle_open_file(self, current_value, vault):
val_str = str(current_value)
# Extract [[...]] if present
match = re.search(r'\[\[(.*?)\]\]', val_str)
if match:
target_note = match.group(1)
# Handle alias like [[Note Name|Alias]]
if '|' in target_note:
target_note = target_note.split('|')[0]
else:
target_note = val_str
self.open_note(target_note, vault=vault)
def frontmatter_clear(self, note_name: str, keys: tuple, 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():
matches = list(vault_path.rglob(f"{note_name}.md"))
if matches:
note_path = matches[0]
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
all_keys = []
for key in keys:
all_keys.extend([k.strip() for k in re.split(r',|\[|\]', key) if k.strip()])
updates = {}
for k in all_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, keys: tuple, 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():
matches = list(vault_path.rglob(f"{note_name}.md"))
if matches:
note_path = matches[0]
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
content = note_path.read_text(encoding='utf-8-sig')
frontmatter, rest_content, _ = self._parse_frontmatter(content)
all_keys = []
for key in keys:
all_keys.extend([k.strip() for k in re.split(r',|\[|\]', key) if k.strip()])
modified = False
for k in all_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, encoding='utf-8-sig')
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='onyx')
def cli():
"""Onyx - Interact with Obsidian vaults from the command line
Manage your Obsidian notes, frontmatter, and periodic notes directly from the terminal.
EXAMPLES:
onyx open "my-note"
onyx daily
onyx frontmatter "my-note" --view --key "tags"
onyx --version
For more help on a specific command:
onyx COMMAND --help
"""
pass
@cli.command()
@click.argument('vault_name')
@click.option('--path', help="Path to the vault directory")
def set_default(vault_name, path):
"""Set or switch the default vault
USAGE:
onyx set-default VAULT_NAME --path /path/to/vault
"""
# 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():
"""Display the currently configured 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
Searches for the note in the vault and opens it in Obsidian. Supports nested directories.
USAGE:
onyx open "my-note"
onyx open "folder/my-note"
"""
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
Uses Obsidian's daily notes plugin settings (format, folder, template) if configured."""
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")
@click.option('--template', help="Template to use")
def create(note_name, content, vault, overwrite, append, open_after, template):
"""Create or modify a note in the vault
USAGE:
onyx create "my-note"
onyx create "my-note" --content "Some content" --open
"""
if content:
content = content.replace('\\n', '\n')
OnyxCLI().create_note(note_name, content, vault, overwrite, append, open_after, template)
@cli.command()
@click.argument('note_name')
@click.option('--vault', help="Vault name (if not using default)")
def print_note(note_name, vault):
"""Display the full contents of a note in the terminal"""
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 or rename a note and auto-update internal links
Automatically updates all [[links]] pointing to this note in other vault files.
USAGE:
onyx move "old-name" "new-name"
onyx move "old-folder/note" "new-folder/note"
"""
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):
"""Permanently delete a note from the vault"""
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, multiple=True, help="Frontmatter key to manage")
@click.option('--value', multiple=True, help="Value to set or check for")
@click.option('--open', 'open_file', is_flag=True, help="Open the file referenced in the value")
@click.option('--vault', help="Vault name (if not using default)")
def frontmatter_command(note_name, edit, view, clear, delete, key, value, open_file, vault):
"""Manage YAML frontmatter in notes
Must specify exactly one action: --edit, --view, --clear, or --delete
USAGE:
onyx frontmatter "my-note" --view --key "tags"
onyx frontmatter "my-note" --edit --key "tags" --value "project,work"
onyx frontmatter "my-note" --delete --key "date"
"""
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:
if value and len(value) > 1 and len(key) != len(value):
# If we have multiple values, they must match keys count
# Unless we have 1 value, which we apply to all keys (handled in frontmatter_edit)
raise click.UsageError(f"Number of values ({len(value)}) must match number of keys ({len(key)})")
cli.frontmatter_edit(note_name, key, value, vault)
elif view:
# For view, we ignore value unless it's for checking existence, which is complex with multiple keys
# For now, let's pass single value if provided, but view supports multiple keys
val = value[0] if value else None
cli.frontmatter_view(note_name, key, val, vault, open_file)
elif clear:
cli.frontmatter_clear(note_name, key, vault)
elif delete:
cli.frontmatter_delete(note_name, key, vault)
@cli.command()
@click.version_option(version='0.0.1', prog_name='onyx')
def version():
"""Display version information"""
pass
if __name__ == '__main__':
cli()