Add per-vault periodic notes config, fix version/print-default bugs, stop tracking build artifacts

- onyx periodic --view/--edit: configure folder/format/template per note type,
  independent of Obsidian's Daily Notes / Periodic Notes plugin state
- fix: weekly/monthly/quarterly/yearly notes no longer silently inherit the
  daily note's folder/template when no plugin config exists
- fix: quarterly notes now resolve the real quarter number instead of a
  literal 'Q'
- fix: onyx --version now works at the root command group; remove the
  redundant no-op 'version' subcommand
- fix: print-default no longer dumps the raw vault config dict for
  long-form vault entries
- expand --help text across periodic/create/set-default commands
- add .gitignore; stop tracking build/, dist/, __pycache__/, .idea/, .vscode/
This commit is contained in:
olivier committed 2026-09-24 17:11:43 -04:00
1 parent d13e377aba
commit 0dddb57d76
30 files changed
+457 -21318

No files matched your search

Binary file not shown.
Binary file not shown.
+252 -58
View File
@@ -13,6 +13,14 @@ from typing import List, Union, Optional, Dict, Any
from urllib.parse import quote
class OnyxCLI:
_PERIODIC_DEFAULTS: Dict[str, Dict[str, str]] = {
'daily': {'format': 'YYYY-MM-DD', 'folder': '', 'template': ''},
'weekly': {'format': 'YYYY-[W]WW', 'folder': '', 'template': ''},
'monthly': {'format': 'YYYY-MM', 'folder': '', 'template': ''},
'quarterly': {'format': 'YYYY-[Q]Q', 'folder': '', 'template': ''},
'yearly': {'format': 'YYYY', 'folder': '', 'template': ''},
}
def __init__(self):
self.config_file = Path.home() / '.onyx-cli' / 'config.yaml'
self._ensure_config_exists()
@@ -39,10 +47,40 @@ class OnyxCLI:
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:
vault_config = config.get('vaults', {}).get(vault_name)
if not vault_config:
raise click.UsageError(f"Vault '{vault_name}' not found in config")
return Path(vault_path)
# Support both string path (old format) and dict format (new format)
if isinstance(vault_config, str):
return Path(vault_config)
elif isinstance(vault_config, dict):
vault_path = vault_config.get('path')
if not vault_path:
raise click.UsageError(f"Vault '{vault_name}' configuration missing 'path' key")
return Path(vault_path)
else:
raise click.UsageError(f"Invalid vault configuration format for '{vault_name}'")
def _get_vault_config(self, vault_name: str) -> Dict[str, Any]:
"""Get the full vault configuration for a given vault name.
Returns a dict with 'path' and optionally 'path_prefix'.
Converts old string format to new dict format for consistency.
"""
config = yaml.safe_load(self.config_file.read_text(encoding='utf-8-sig'))
vault_config = config.get('vaults', {}).get(vault_name)
if not vault_config:
raise click.UsageError(f"Vault '{vault_name}' not found in config")
# Convert string format to dict format for consistency
if isinstance(vault_config, str):
return {'path': vault_config}
elif isinstance(vault_config, dict):
return vault_config
else:
raise click.UsageError(f"Invalid vault configuration format for '{vault_name}'")
def _get_vault_and_path(self, vault: Optional[str] = None) -> tuple[str, Path]:
vault_name = vault or self.default_vault
@@ -51,22 +89,56 @@ class OnyxCLI:
vault_path = self._get_vault_path(vault_name)
return vault_name, vault_path
def set_default_vault(self, vault_name: str, vault_path: Optional[str] = None, path_prefix: Optional[str] = None):
"""Set the default vault and optionally configure its path and path_prefix.
Args:
vault_name: Name of the vault to set as default
vault_path: Optional path to the vault directory
path_prefix: Optional path prefix for resolving relative paths in frontmatter
"""
config = yaml.safe_load(self.config_file.read_text(encoding='utf-8-sig'))
# Set the default vault
config['default_vault'] = vault_name
# Update vault configuration if path is provided
if vault_path:
if 'vaults' not in config:
config['vaults'] = {}
# Create vault config dict
vault_config = {'path': str(Path(vault_path).resolve())}
# Add path_prefix if provided
if path_prefix:
vault_config['path_prefix'] = str(Path(path_prefix).resolve())
config['vaults'][vault_name] = vault_config
# Write updated config
self.config_file.write_text(yaml.dump(config, default_flow_style=False), encoding='utf-8-sig')
# Update instance variables
self.default_vault = vault_name
if vault_path:
self.vault_path = Path(vault_path).resolve()
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:
try:
vault_config = self._get_vault_config(self.default_vault)
except click.UsageError:
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}")
click.echo(f"Path: {vault_config['path']}")
def _get_template_folder(self, vault_path: Path) -> Optional[Path]:
"""
@@ -256,21 +328,7 @@ class OnyxCLI:
def _create_or_open_periodic_note(self, note_type: str, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
"""Generic method to create or open periodic notes with date navigation."""
vault_name, vault_path = self._get_vault_and_path(vault)
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
settings = self._resolve_periodic_settings(vault_name, vault_path, note_type)
# Date calculation
base_date = None
@@ -317,22 +375,11 @@ class OnyxCLI:
base_date = base_date.replace(year=base_date.year - 1, month=1, day=1)
# Force correct format for yearly, monthly, and weekly notes
if note_type == 'yearly':
settings['format'] = 'YYYY'
elif note_type == 'monthly':
settings['format'] = 'YYYY-MM'
elif note_type == 'weekly':
# Only override if not set to a weekly format
fmt = settings.get('format', '')
if not ('W' in fmt and '[' in fmt and ']' in fmt):
settings['format'] = 'YYYY-[W]WW'
date_format = self._convert_moment_format(settings['format'])
# Handle week format specially for ISO weeks
# Handle week and quarter formats specially (no direct strftime equivalent)
filename = None
if 'W' in settings['format'] and '[W]' in settings['format']:
if note_type == 'weekly' and 'W' in settings['format'] and '[W]' in settings['format']:
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 = base_date.strftime('%G') # ISO year (4 digits)
@@ -340,6 +387,11 @@ class OnyxCLI:
year = base_date.strftime('%g') # ISO year (2 digits)
week = base_date.strftime('%V') # ISO week number
filename = f"{year}-W{week}"
elif note_type == 'quarterly' and 'Q' in settings['format']:
year_format = 'yyyy' if 'yyyy' in settings['format'] else ('YYYY' if 'YYYY' in settings['format'] else 'yy')
year = base_date.strftime('%Y') if year_format in ('yyyy', 'YYYY') else base_date.strftime('%y')
quarter = (base_date.month - 1) // 3 + 1
filename = f"{year}-Q{quarter}"
else:
try:
filename = base_date.strftime(date_format)
@@ -517,7 +569,7 @@ class OnyxCLI:
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):
def frontmatter_view(self, note_name: str, keys: tuple, value: str = None, vault: str = None, open_file: bool = False, output_path: Union[bool, str, None] = None):
vault_name, vault_path = self._get_vault_and_path(vault)
note_path = vault_path / note_name
if not note_path.suffix:
@@ -557,7 +609,26 @@ class OnyxCLI:
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]))
val = str(frontmatter[k])
# Handle path resolution if requested
if output_path is not None:
# Determine prefix
prefix = ""
if isinstance(output_path, str):
# Use provided custom prefix
prefix = output_path
elif output_path is True:
# Use prefix from config
vault_config = self._get_vault_config(vault_name)
prefix = vault_config.get('path_prefix', '')
if prefix:
# Join prefix and value using OS separator
# Normalize separators to handle potential mix of forward/backslashes
val = str(Path(prefix) / val)
click.echo(val)
else:
click.echo(yaml.dump({k: frontmatter[k]}, default_flow_style=False).strip())
@@ -697,8 +768,90 @@ class OnyxCLI:
'template': ''
}
def _resolve_periodic_settings(self, vault_name: str, vault_path: Path, note_type: str) -> Dict[str, Any]:
"""
Resolve folder/format/template settings for a periodic note type.
Priority (highest first):
1. onyx's own config (`onyx periodic --edit`, stored in ~/.onyx-cli/config.yaml)
2. Obsidian's Periodic Notes plugin (or core Daily Notes plugin for 'daily')
3. Built-in defaults for that note type
Each note type is resolved independently - a type with no plugin/config data
never inherits another type's folder or template.
"""
settings = dict(self._PERIODIC_DEFAULTS.get(note_type, self._PERIODIC_DEFAULTS['daily']))
# Layer: Obsidian plugin auto-detection
if note_type == 'daily':
settings.update(self._get_daily_note_settings(vault_path))
else:
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):
if note_config.get('format'):
settings['format'] = note_config['format']
if 'folder' in note_config:
settings['folder'] = note_config.get('folder', '')
if 'template' in note_config:
settings['template'] = note_config.get('template', '')
except (json.JSONDecodeError, KeyError):
pass
# Layer: onyx's own config.yaml (explicit user intent, wins over everything)
try:
vault_config = self._get_vault_config(vault_name)
except click.UsageError:
vault_config = {}
user_settings = (vault_config.get('periodic_notes') or {}).get(note_type, {})
for key in ('folder', 'format', 'template'):
if user_settings.get(key):
settings[key] = user_settings[key]
return settings
def set_periodic_config(self, note_type: str, folder: str = None, format: str = None,
template: str = None, vault: str = None):
"""Persist folder/format/template overrides for a periodic note type in onyx's own config."""
vault_name, _ = self._get_vault_and_path(vault)
config = yaml.safe_load(self.config_file.read_text(encoding='utf-8-sig'))
vaults = config.setdefault('vaults', {})
vault_entry = vaults.get(vault_name)
if isinstance(vault_entry, str):
vault_entry = {'path': vault_entry}
elif not isinstance(vault_entry, dict):
raise click.UsageError(f"Vault '{vault_name}' not found in config")
periodic = vault_entry.setdefault('periodic_notes', {})
type_entry = periodic.setdefault(note_type, {})
if folder is not None:
type_entry['folder'] = folder
if format is not None:
type_entry['format'] = format
if template is not None:
type_entry['template'] = template
vaults[vault_name] = vault_entry
config['vaults'] = vaults
self.config_file.write_text(yaml.dump(config, default_flow_style=False), encoding='utf-8-sig')
click.echo(f"Updated {note_type} note settings for vault '{vault_name}'")
def print_periodic_config(self, note_type: str, vault: str = None):
"""Print the resolved folder/format/template settings for a periodic note type."""
vault_name, vault_path = self._get_vault_and_path(vault)
settings = self._resolve_periodic_settings(vault_name, vault_path, note_type)
click.echo(f"{note_type} note settings for vault '{vault_name}':")
click.echo(f" folder: {settings['folder'] or '(vault root)'}")
click.echo(f" format: {settings['format']}")
click.echo(f" template: {settings['template'] or '(none)'}")
# CLI Commands
@click.version_option(version='0.0.1', prog_name='onyx')
@click.group(name='onyx')
def cli():
"""Onyx - Interact with Obsidian vaults from the command line
@@ -719,7 +872,8 @@ def cli():
@cli.command()
@click.argument('vault_name')
@click.option('--path', help="Path to the vault directory")
def set_default(vault_name, path):
@click.option('--path-prefix', help="Base path prepended to relative frontmatter path values when using 'onyx frontmatter --view --output-path'")
def set_default(vault_name, path, path_prefix):
"""Set or switch the default vault
USAGE:
@@ -728,7 +882,7 @@ def set_default(vault_name, path):
# Convert Windows backslashes to forward slashes if needed
if path:
path = str(Path(path))
OnyxCLI().set_default_vault(vault_name, path)
OnyxCLI().set_default_vault(vault_name, path, path_prefix)
@cli.command()
def print_default():
@@ -756,8 +910,10 @@ def open(note_name, vault):
@click.option('--previous', is_flag=True, help="Open the previous period's note")
def daily(vault, date, next_, previous):
"""Create or open a daily note for a specific date, next, or previous day
Uses Obsidian's daily notes plugin settings (format, folder, template) if configured."""
Folder, filename format, and template are resolved from onyx's own config
(see `onyx periodic --type daily`), falling back to Obsidian's Daily Notes
or Periodic Notes plugin settings, then to built-in defaults."""
OnyxCLI().daily_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@@ -766,7 +922,9 @@ def daily(vault, date, next_, previous):
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
@click.option('--previous', is_flag=True, help="Open the previous period's note")
def weekly(vault, date, next_, previous):
"""Create or open a weekly note for a specific date, next, or previous week"""
"""Create or open a weekly note for a specific date, next, or previous week
Folder, filename format, and template are configurable via `onyx periodic --type weekly`."""
OnyxCLI().weekly_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@@ -775,7 +933,9 @@ def weekly(vault, date, next_, previous):
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
@click.option('--previous', is_flag=True, help="Open the previous period's note")
def monthly(vault, date, next_, previous):
"""Create or open a monthly note for a specific date, next, or previous month"""
"""Create or open a monthly note for a specific date, next, or previous month
Folder, filename format, and template are configurable via `onyx periodic --type monthly`."""
OnyxCLI().monthly_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@@ -784,7 +944,9 @@ def monthly(vault, date, next_, previous):
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
@click.option('--previous', is_flag=True, help="Open the previous period's note")
def quarterly(vault, date, next_, previous):
"""Create or open a quarterly note for a specific date, next, or previous quarter"""
"""Create or open a quarterly note for a specific date, next, or previous quarter
Folder, filename format, and template are configurable via `onyx periodic --type quarterly`."""
OnyxCLI().quarterly_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@@ -793,9 +955,43 @@ def quarterly(vault, date, next_, previous):
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
@click.option('--previous', is_flag=True, help="Open the previous period's note")
def yearly(vault, date, next_, previous):
"""Create or open a yearly note for a specific date, next, or previous year"""
"""Create or open a yearly note for a specific date, next, or previous year
Folder, filename format, and template are configurable via `onyx periodic --type yearly`."""
OnyxCLI().yearly_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@click.option('--type', 'note_type', required=True,
type=click.Choice(['daily', 'weekly', 'monthly', 'quarterly', 'yearly']),
help="Periodic note type to configure")
@click.option('--view', is_flag=True, help="View the resolved settings")
@click.option('--edit', is_flag=True, help="Edit onyx's own settings for this note type")
@click.option('--folder', help="Folder where notes of this type are stored (relative to vault root)")
@click.option('--format', 'note_format', help="Moment.js-style filename format, e.g. YYYY-MM-DD, YYYY-[W]WW")
@click.option('--template', help="Path to template file (relative to vault root)")
@click.option('--vault', help="Vault name (if not using default)")
def periodic(note_type, view, edit, folder, note_format, template, vault):
"""View or edit onyx's own folder/format/template settings for a periodic note type.
These settings take priority over anything detected from Obsidian's Daily Notes
or Periodic Notes plugins, and are the only source of truth for note types that
plugin isn't configured for.
USAGE:
onyx periodic --type weekly --view
onyx periodic --type weekly --edit --folder "periodic/weekly" --format "YYYY-[W]WW" --template "resources/template/weekly-note.md"
"""
if sum([view, edit]) != 1:
raise click.UsageError("Exactly one of --view or --edit must be specified")
cli = OnyxCLI()
if edit:
if not any([folder, note_format, template]):
raise click.UsageError("Provide at least one of --folder, --format, --template with --edit")
cli.set_periodic_config(note_type, folder=folder, format=note_format, template=template, vault=vault)
else:
cli.print_periodic_config(note_type, vault)
@cli.command()
@click.argument('note_name')
@click.option('--content', default="", help="Content to write to the note")
@@ -803,10 +999,13 @@ def yearly(vault, date, next_, previous):
@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")
@click.option('--template', help="Template name (without extension) from the vault's Templater or core Templates folder; using this implies --open")
def create(note_name, content, vault, overwrite, append, open_after, template):
"""Create or modify a note in the vault
--template looks up the vault's Templater (or core Templates) folder and
prepends its content; the note is then opened automatically.
USAGE:
onyx create "my-note"
onyx create "my-note" --content "Some content" --open
@@ -855,7 +1054,8 @@ def delete(note_path, vault):
@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):
@click.option('--output-path', is_flag=False, flag_value=True, default=None, help="Resolve relative paths. Can be a flag (uses config prefix) or a string (custom prefix).")
def frontmatter_command(note_name, edit, view, clear, delete, key, value, open_file, vault, output_path):
"""Manage YAML frontmatter in notes
Must specify exactly one action: --edit, --view, --clear, or --delete
@@ -880,17 +1080,11 @@ def frontmatter_command(note_name, edit, view, clear, delete, key, value, open_f
# 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)
cli.frontmatter_view(note_name, key, val, vault, open_file, output_path)
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()