|
|
@@ -9,6 +9,7 @@ import datetime
|
|
|
|
import builtins
|
|
|
|
import builtins
|
|
|
|
from pathlib import Path
|
|
|
|
from pathlib import Path
|
|
|
|
import re
|
|
|
|
import re
|
|
|
|
|
|
|
|
from collections import Counter
|
|
|
|
from typing import List, Union, Optional, Dict, Any
|
|
|
|
from typing import List, Union, Optional, Dict, Any
|
|
|
|
from urllib.parse import quote
|
|
|
|
from urllib.parse import quote
|
|
|
|
|
|
|
|
|
|
|
@@ -24,6 +25,71 @@ def _write_text(path: Path, text: str, mode: str = 'w') -> None:
|
|
|
|
f.write(text)
|
|
|
|
f.write(text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_FRONTMATTER = re.compile(r'\A---\n(.*?)^---[ \t]*(?:\n|\Z)', re.S | re.M)
|
|
|
|
|
|
|
|
_FRONTMATTER_KEY = re.compile(r'^([^\s#\-][^:]*?):(?:[ \t]|$)')
|
|
|
|
|
|
|
|
_WIKILINK = re.compile(r'\[\[([^\[\]|#]+?)(#[^\[\]|]*)?(\|[^\[\]]*)?\]\]')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _yaml_scalar(value: str) -> str:
|
|
|
|
|
|
|
|
"""Render a CLI string as Obsidian stores it: plain when YAML reads it back
|
|
|
|
|
|
|
|
as-is (text, numbers, dates, booleans), double-quoted otherwise ([[links]],
|
|
|
|
|
|
|
|
': ', '#', leading/trailing spaces)."""
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
|
|
parsed = yaml.safe_load(value)
|
|
|
|
|
|
|
|
except yaml.YAMLError:
|
|
|
|
|
|
|
|
parsed = None
|
|
|
|
|
|
|
|
plain = parsed == value or isinstance(parsed, (bool, int, float, datetime.date))
|
|
|
|
|
|
|
|
return value if plain and value == value.strip() else json.dumps(value, ensure_ascii=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _frontmatter_entry(key: str, value: Union[str, list]) -> str:
|
|
|
|
|
|
|
|
if isinstance(value, list):
|
|
|
|
|
|
|
|
if not value:
|
|
|
|
|
|
|
|
return f"{key}: []\n"
|
|
|
|
|
|
|
|
return f"{key}:\n" + ''.join(f" - {_yaml_scalar(v)}\n" for v in value)
|
|
|
|
|
|
|
|
return f"{key}: {_yaml_scalar(value)}\n" if value else f"{key}:\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _splice_frontmatter(content: str, updates: Dict[str, Union[str, list]], deletions=()) -> str:
|
|
|
|
|
|
|
|
"""Replace, add or remove top-level frontmatter keys, leaving every other
|
|
|
|
|
|
|
|
line of the note byte-for-byte untouched. A key's block is its line plus the
|
|
|
|
|
|
|
|
following indented or '- ' lines. Removing the last key drops the frontmatter."""
|
|
|
|
|
|
|
|
match = _FRONTMATTER.match(content)
|
|
|
|
|
|
|
|
fm, body = (match.group(1), content[match.end():]) if match else ('', content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
blocks: List[list] = [] # [key or None, raw text]
|
|
|
|
|
|
|
|
for line in fm.splitlines(keepends=True):
|
|
|
|
|
|
|
|
key_match = _FRONTMATTER_KEY.match(line)
|
|
|
|
|
|
|
|
if key_match or not blocks:
|
|
|
|
|
|
|
|
blocks.append([key_match.group(1).strip() if key_match else None, line])
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
blocks[-1][1] += line
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if not updates and not any(key in deletions for key, _ in blocks):
|
|
|
|
|
|
|
|
return content
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
out, seen = [], set()
|
|
|
|
|
|
|
|
for key, text in blocks:
|
|
|
|
|
|
|
|
if key in deletions:
|
|
|
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
if key in updates:
|
|
|
|
|
|
|
|
out.append(_frontmatter_entry(key, updates[key]))
|
|
|
|
|
|
|
|
seen.add(key)
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
out.append(text if text.endswith('\n') else text + '\n')
|
|
|
|
|
|
|
|
out.extend(_frontmatter_entry(k, v) for k, v in updates.items() if k not in seen)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
new_fm = ''.join(out)
|
|
|
|
|
|
|
|
return f"---\n{new_fm}---\n{body}" if new_fm.strip() else body
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _iter_notes(vault_path: Path):
|
|
|
|
|
|
|
|
"""Markdown files in the vault, skipping dot folders (.obsidian, .trash, .git)."""
|
|
|
|
|
|
|
|
for path in vault_path.rglob('*.md'):
|
|
|
|
|
|
|
|
if not any(part.startswith('.') for part in path.relative_to(vault_path).parts[:-1]):
|
|
|
|
|
|
|
|
yield path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class OnyxCLI:
|
|
|
|
class OnyxCLI:
|
|
|
|
_PERIODIC_DEFAULTS: Dict[str, Dict[str, str]] = {
|
|
|
|
_PERIODIC_DEFAULTS: Dict[str, Dict[str, str]] = {
|
|
|
|
'daily': {'format': 'YYYY-MM-DD', 'folder': '', 'template': ''},
|
|
|
|
'daily': {'format': 'YYYY-MM-DD', 'folder': '', 'template': ''},
|
|
|
@@ -182,7 +248,8 @@ class OnyxCLI:
|
|
|
|
return None
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def create_note(self, note_name: str, content: str = "", vault: str = 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):
|
|
|
|
overwrite: bool = False, append: bool = False, open_after: bool = False, template: str = None,
|
|
|
|
|
|
|
|
quiet: bool = False):
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
note_path = vault_path / note_name
|
|
|
|
note_path = vault_path / note_name
|
|
|
|
if not str(note_path).endswith('.md'):
|
|
|
|
if not str(note_path).endswith('.md'):
|
|
|
@@ -225,6 +292,7 @@ class OnyxCLI:
|
|
|
|
content = '\n' + content
|
|
|
|
content = '\n' + content
|
|
|
|
_write_text(note_path, content, mode)
|
|
|
|
_write_text(note_path, content, mode)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if not quiet:
|
|
|
|
click.echo(f"Note {'updated' if note_path.exists() else 'created'}: {note_path}")
|
|
|
|
click.echo(f"Note {'updated' if note_path.exists() else 'created'}: {note_path}")
|
|
|
|
|
|
|
|
|
|
|
|
if open_after:
|
|
|
|
if open_after:
|
|
|
@@ -336,8 +404,13 @@ class OnyxCLI:
|
|
|
|
|
|
|
|
|
|
|
|
return result
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def _create_or_open_periodic_note(self, note_type: str, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
|
|
|
def _create_or_open_periodic_note(self, note_type: str, vault: str = None, date: str = None, next_: bool = False,
|
|
|
|
"""Generic method to create or open periodic notes with date navigation."""
|
|
|
|
previous: bool = False, open_after: bool = True, print_path: bool = False):
|
|
|
|
|
|
|
|
"""Generic method to create or open periodic notes with date navigation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
open_after=False creates the note (if missing) without opening Obsidian; Templater
|
|
|
|
|
|
|
|
syntax in the template then stays raw until Obsidian processes the new file.
|
|
|
|
|
|
|
|
print_path=True prints only the note's absolute path."""
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
settings = self._resolve_periodic_settings(vault_name, vault_path, note_type)
|
|
|
|
settings = self._resolve_periodic_settings(vault_name, vault_path, note_type)
|
|
|
|
|
|
|
|
|
|
|
@@ -435,29 +508,37 @@ class OnyxCLI:
|
|
|
|
full_note_path = full_note_path.with_suffix('.md')
|
|
|
|
full_note_path = full_note_path.with_suffix('.md')
|
|
|
|
|
|
|
|
|
|
|
|
if full_note_path.exists():
|
|
|
|
if full_note_path.exists():
|
|
|
|
|
|
|
|
if open_after:
|
|
|
|
self.open_note(note_path, vault_name)
|
|
|
|
self.open_note(note_path, vault_name)
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
self.create_note(note_path, content=content, vault=vault_name, open_after=True)
|
|
|
|
self.create_note(note_path, content=content, vault=vault_name, open_after=open_after, quiet=print_path)
|
|
|
|
|
|
|
|
if print_path:
|
|
|
|
|
|
|
|
click.echo(str(full_note_path))
|
|
|
|
|
|
|
|
|
|
|
|
def daily_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
|
|
|
def daily_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False,
|
|
|
|
|
|
|
|
open_after: bool = True, print_path: bool = False):
|
|
|
|
"""Create or open a daily note for a specific date, next, or previous day."""
|
|
|
|
"""Create or open a daily note for a specific date, next, or previous day."""
|
|
|
|
self._create_or_open_periodic_note('daily', vault, date=date, next_=next_, previous=previous)
|
|
|
|
self._create_or_open_periodic_note('daily', vault, date, next_, previous, open_after, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
def weekly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
|
|
|
def weekly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False,
|
|
|
|
|
|
|
|
open_after: bool = True, print_path: bool = False):
|
|
|
|
"""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."""
|
|
|
|
self._create_or_open_periodic_note('weekly', vault, date=date, next_=next_, previous=previous)
|
|
|
|
self._create_or_open_periodic_note('weekly', vault, date, next_, previous, open_after, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
def monthly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
|
|
|
def monthly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False,
|
|
|
|
|
|
|
|
open_after: bool = True, print_path: bool = False):
|
|
|
|
"""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."""
|
|
|
|
self._create_or_open_periodic_note('monthly', vault, date=date, next_=next_, previous=previous)
|
|
|
|
self._create_or_open_periodic_note('monthly', vault, date, next_, previous, open_after, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
def quarterly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
|
|
|
def quarterly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False,
|
|
|
|
|
|
|
|
open_after: bool = True, print_path: bool = False):
|
|
|
|
"""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."""
|
|
|
|
self._create_or_open_periodic_note('quarterly', vault, date=date, next_=next_, previous=previous)
|
|
|
|
self._create_or_open_periodic_note('quarterly', vault, date, next_, previous, open_after, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
def yearly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
|
|
|
def yearly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False,
|
|
|
|
|
|
|
|
open_after: bool = True, print_path: bool = False):
|
|
|
|
"""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."""
|
|
|
|
self._create_or_open_periodic_note('yearly', vault, date=date, next_=next_, previous=previous)
|
|
|
|
self._create_or_open_periodic_note('yearly', vault, date, next_, previous, open_after, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
def print_note(self, note_name: str, vault: str = None):
|
|
|
|
def print_note(self, note_name: str, vault: str = None):
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
@@ -471,6 +552,13 @@ class OnyxCLI:
|
|
|
|
click.echo(note_path.read_text(encoding='utf-8-sig'))
|
|
|
|
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):
|
|
|
|
def move_note(self, current_path: str, new_path: str, vault: str = None, open_after: bool = False):
|
|
|
|
|
|
|
|
"""Move/rename a note and rewrite wikilinks that resolve to it.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Handles [[name]], [[name|alias]], [[name#heading]], ![[embeds]], path links
|
|
|
|
|
|
|
|
([[folder/name]], partial paths, optional .md), frontmatter links, and links in
|
|
|
|
|
|
|
|
the moved note itself. A bare-name link is only rewritten when the old name was
|
|
|
|
|
|
|
|
unique in the vault; the new link is bare unless the new name is ambiguous.
|
|
|
|
|
|
|
|
Markdown-style [text](path.md) links are not rewritten."""
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
|
|
|
|
|
|
|
|
current = vault_path / current_path
|
|
|
|
current = vault_path / current_path
|
|
|
@@ -483,22 +571,57 @@ class OnyxCLI:
|
|
|
|
|
|
|
|
|
|
|
|
if not current.exists():
|
|
|
|
if not current.exists():
|
|
|
|
raise click.UsageError(f"Note {current_path} does not exist")
|
|
|
|
raise click.UsageError(f"Note {current_path} does not exist")
|
|
|
|
|
|
|
|
if new.exists() and not new.samefile(current):
|
|
|
|
|
|
|
|
raise click.UsageError(f"Note {new_path} already exists")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
old_rel = current.relative_to(vault_path).with_suffix('').as_posix()
|
|
|
|
|
|
|
|
new_rel = new.relative_to(vault_path).with_suffix('').as_posix()
|
|
|
|
new.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
new.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
current.rename(new)
|
|
|
|
current.rename(new)
|
|
|
|
|
|
|
|
|
|
|
|
# Update internal links in all vault files
|
|
|
|
notes = list(_iter_notes(vault_path))
|
|
|
|
old_link_pattern = f"\\[\\[{current.stem}\\]\\]"
|
|
|
|
stems = Counter(p.stem.casefold() for p in notes)
|
|
|
|
new_link = f"[[{new.stem}]]"
|
|
|
|
old_stem, new_stem = current.stem.casefold(), new.stem.casefold()
|
|
|
|
|
|
|
|
stem_changed = old_stem != new_stem
|
|
|
|
|
|
|
|
old_bare_unique = stems[old_stem] == (0 if stem_changed else 1)
|
|
|
|
|
|
|
|
new_target_bare = new.stem if stems[new_stem] == 1 else new_rel
|
|
|
|
|
|
|
|
old_rel_cf = old_rel.casefold()
|
|
|
|
|
|
|
|
links = ambiguous = 0
|
|
|
|
|
|
|
|
|
|
|
|
for md_file in vault_path.rglob("*.md"):
|
|
|
|
def rewrite(match: re.Match) -> str:
|
|
|
|
if md_file != new: # Skip the moved file
|
|
|
|
nonlocal links, ambiguous
|
|
|
|
|
|
|
|
target = match.group(1).strip().replace('\\', '/')
|
|
|
|
|
|
|
|
has_md = target.lower().endswith('.md')
|
|
|
|
|
|
|
|
key = (target[:-3] if has_md else target).casefold()
|
|
|
|
|
|
|
|
if '/' in key:
|
|
|
|
|
|
|
|
if key.lstrip('/') != old_rel_cf and not old_rel_cf.endswith('/' + key):
|
|
|
|
|
|
|
|
return match.group(0)
|
|
|
|
|
|
|
|
replacement = new_rel
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
if key != old_stem:
|
|
|
|
|
|
|
|
return match.group(0)
|
|
|
|
|
|
|
|
if not old_bare_unique:
|
|
|
|
|
|
|
|
ambiguous += stem_changed
|
|
|
|
|
|
|
|
return match.group(0)
|
|
|
|
|
|
|
|
replacement = new_target_bare
|
|
|
|
|
|
|
|
replacement += '.md' if has_md else ''
|
|
|
|
|
|
|
|
if replacement == target:
|
|
|
|
|
|
|
|
return match.group(0)
|
|
|
|
|
|
|
|
links += 1
|
|
|
|
|
|
|
|
return f"[[{replacement}{match.group(2) or ''}{match.group(3) or ''}]]"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
files = 0
|
|
|
|
|
|
|
|
for md_file in notes:
|
|
|
|
content = md_file.read_text(encoding='utf-8-sig')
|
|
|
|
content = md_file.read_text(encoding='utf-8-sig')
|
|
|
|
updated_content = re.sub(old_link_pattern, new_link, content)
|
|
|
|
updated = _WIKILINK.sub(rewrite, content)
|
|
|
|
if updated_content != content:
|
|
|
|
if updated != content:
|
|
|
|
_write_text(md_file, updated_content)
|
|
|
|
_write_text(md_file, updated)
|
|
|
|
|
|
|
|
files += 1
|
|
|
|
|
|
|
|
|
|
|
|
click.echo(f"Moved {current_path} to {new_path}")
|
|
|
|
click.echo(f"Moved {current_path} to {new_path} ({links} link(s) updated in {files} note(s))")
|
|
|
|
|
|
|
|
if ambiguous:
|
|
|
|
|
|
|
|
click.echo(f"Warning: {ambiguous} [[{current.stem}]] link(s) left unchanged: "
|
|
|
|
|
|
|
|
f"several notes are named '{current.stem}'")
|
|
|
|
|
|
|
|
|
|
|
|
if open_after:
|
|
|
|
if open_after:
|
|
|
|
self.open_note(new_path, vault_name)
|
|
|
|
self.open_note(new_path, vault_name)
|
|
|
@@ -529,32 +652,35 @@ class OnyxCLI:
|
|
|
|
except yaml.YAMLError:
|
|
|
|
except yaml.YAMLError:
|
|
|
|
return {}, content, 0
|
|
|
|
return {}, content, 0
|
|
|
|
|
|
|
|
|
|
|
|
def _update_frontmatter(self, note_path: Path, updates: dict):
|
|
|
|
def _find_note(self, vault_path: Path, note_name: str) -> Path:
|
|
|
|
content = note_path.read_text(encoding='utf-8-sig')
|
|
|
|
"""Exact vault-relative path first, then the first note with that name anywhere."""
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_write_text(note_path, new_content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
note_path = vault_path / note_name
|
|
|
|
if not note_path.suffix:
|
|
|
|
if not note_path.suffix:
|
|
|
|
note_path = note_path.with_suffix('.md')
|
|
|
|
note_path = note_path.with_suffix('.md')
|
|
|
|
|
|
|
|
|
|
|
|
if not note_path.exists():
|
|
|
|
if not note_path.exists():
|
|
|
|
matches = list(vault_path.rglob(f"{note_name}.md"))
|
|
|
|
matches = list(vault_path.rglob(f"{note_name}.md"))
|
|
|
|
if matches:
|
|
|
|
if matches:
|
|
|
|
note_path = matches[0]
|
|
|
|
note_path = matches[0]
|
|
|
|
|
|
|
|
|
|
|
|
if not note_path.exists():
|
|
|
|
if not note_path.exists():
|
|
|
|
raise click.UsageError(f"Note {note_name} does not exist")
|
|
|
|
raise click.UsageError(f"Note {note_name} does not exist")
|
|
|
|
|
|
|
|
return note_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
|
|
def _split_keys(keys: tuple) -> List[str]:
|
|
|
|
|
|
|
|
"""--key values, also accepting comma/bracket-separated keys (legacy)."""
|
|
|
|
|
|
|
|
return [k.strip() for key in keys for k in re.split(r',|\[|\]', key) if k.strip()]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _rewrite_frontmatter(self, note_path: Path, updates: dict, deletions=()) -> bool:
|
|
|
|
|
|
|
|
content = note_path.read_text(encoding='utf-8-sig')
|
|
|
|
|
|
|
|
new_content = _splice_frontmatter(content, updates, deletions)
|
|
|
|
|
|
|
|
if new_content == content:
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
_write_text(note_path, new_content)
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 = self._find_note(vault_path, note_name)
|
|
|
|
|
|
|
|
|
|
|
|
updates = {}
|
|
|
|
updates = {}
|
|
|
|
|
|
|
|
|
|
|
@@ -563,36 +689,19 @@ class OnyxCLI:
|
|
|
|
values = values * len(keys)
|
|
|
|
values = values * len(keys)
|
|
|
|
|
|
|
|
|
|
|
|
for i, key in enumerate(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
|
|
|
|
value = values[i] if values and i < len(values) else None
|
|
|
|
|
|
|
|
for k in self._split_keys((key,)):
|
|
|
|
for k in sub_keys:
|
|
|
|
|
|
|
|
if k == 'tags':
|
|
|
|
if k == 'tags':
|
|
|
|
if value:
|
|
|
|
updates[k] = [t.strip() for t in value.split(',') if t.strip()] if value else []
|
|
|
|
updates[k] = [t.strip() for t in value.split(',')] if ',' in value else [value.strip()]
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
updates[k] = []
|
|
|
|
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
updates[k] = value if value is not None else ""
|
|
|
|
updates[k] = value if value is not None else ""
|
|
|
|
|
|
|
|
|
|
|
|
self._update_frontmatter(note_path, updates)
|
|
|
|
self._rewrite_frontmatter(note_path, updates)
|
|
|
|
click.echo(f"Updated frontmatter for {note_name}")
|
|
|
|
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, output_path: Union[bool, str, None] = None):
|
|
|
|
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)
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
note_path = vault_path / note_name
|
|
|
|
note_path = self._find_note(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')
|
|
|
|
content = note_path.read_text(encoding='utf-8-sig')
|
|
|
|
frontmatter, _, _ = self._parse_frontmatter(content)
|
|
|
|
frontmatter, _, _ = self._parse_frontmatter(content)
|
|
|
@@ -641,7 +750,7 @@ class OnyxCLI:
|
|
|
|
|
|
|
|
|
|
|
|
click.echo(val)
|
|
|
|
click.echo(val)
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
click.echo(yaml.dump({k: frontmatter[k]}, default_flow_style=False).strip())
|
|
|
|
click.echo(yaml.dump({k: frontmatter[k]}, default_flow_style=False, allow_unicode=True).strip())
|
|
|
|
|
|
|
|
|
|
|
|
def _handle_open_file(self, current_value, vault):
|
|
|
|
def _handle_open_file(self, current_value, vault):
|
|
|
|
val_str = str(current_value)
|
|
|
|
val_str = str(current_value)
|
|
|
@@ -661,68 +770,15 @@ class OnyxCLI:
|
|
|
|
|
|
|
|
|
|
|
|
def frontmatter_clear(self, note_name: str, keys: tuple, vault: str = None):
|
|
|
|
def frontmatter_clear(self, note_name: str, keys: tuple, vault: str = None):
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
note_path = vault_path / note_name
|
|
|
|
note_path = self._find_note(vault_path, note_name)
|
|
|
|
if not note_path.suffix:
|
|
|
|
updates = {k: [] if k == 'tags' else "" for k in self._split_keys(keys)}
|
|
|
|
note_path = note_path.with_suffix('.md')
|
|
|
|
self._rewrite_frontmatter(note_path, updates)
|
|
|
|
|
|
|
|
|
|
|
|
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}")
|
|
|
|
click.echo(f"Cleared frontmatter values for {note_name}")
|
|
|
|
|
|
|
|
|
|
|
|
def frontmatter_delete(self, note_name: str, keys: tuple, vault: str = None):
|
|
|
|
def frontmatter_delete(self, note_name: str, keys: tuple, vault: str = None):
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
note_path = vault_path / note_name
|
|
|
|
note_path = self._find_note(vault_path, note_name)
|
|
|
|
if not note_path.suffix:
|
|
|
|
if self._rewrite_frontmatter(note_path, {}, set(self._split_keys(keys))):
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_write_text(note_path, new_content)
|
|
|
|
|
|
|
|
click.echo(f"Deleted frontmatter keys from {note_name}")
|
|
|
|
click.echo(f"Deleted frontmatter keys from {note_name}")
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
click.echo("No matching keys found in frontmatter")
|
|
|
|
click.echo("No matching keys found in frontmatter")
|
|
|
@@ -862,7 +918,15 @@ class OnyxCLI:
|
|
|
|
|
|
|
|
|
|
|
|
# CLI Commands
|
|
|
|
# CLI Commands
|
|
|
|
|
|
|
|
|
|
|
|
@click.version_option(version='0.1.1', prog_name='onyx')
|
|
|
|
def _periodic_output_options(command):
|
|
|
|
|
|
|
|
"""--no-open / --print-path, shared by the periodic note commands."""
|
|
|
|
|
|
|
|
command = click.option('--print-path', is_flag=True,
|
|
|
|
|
|
|
|
help="Print only the note's absolute path (for scripts)")(command)
|
|
|
|
|
|
|
|
return click.option('--no-open', is_flag=True,
|
|
|
|
|
|
|
|
help="Don't open Obsidian; a newly created note keeps raw Templater syntax "
|
|
|
|
|
|
|
|
"until Obsidian processes it")(command)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@click.version_option(version='0.2.0', prog_name='onyx')
|
|
|
|
@click.group(name='onyx')
|
|
|
|
@click.group(name='onyx')
|
|
|
|
def cli():
|
|
|
|
def cli():
|
|
|
|
"""Onyx - Interact with Obsidian vaults from the command line
|
|
|
|
"""Onyx - Interact with Obsidian vaults from the command line
|
|
|
@@ -919,57 +983,62 @@ def open(note_name, vault):
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
|
|
|
@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")
|
|
|
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
|
|
|
def daily(vault, date, next_, previous):
|
|
|
|
@_periodic_output_options
|
|
|
|
|
|
|
|
def daily(vault, date, next_, previous, no_open, print_path):
|
|
|
|
"""Create or open a daily note for a specific date, next, or previous day
|
|
|
|
"""Create or open a daily note for a specific date, next, or previous day
|
|
|
|
|
|
|
|
|
|
|
|
Folder, filename format, and template are resolved from onyx's own config
|
|
|
|
Folder, filename format, and template are resolved from onyx's own config
|
|
|
|
(see `onyx periodic --type daily`), falling back to Obsidian's Daily Notes
|
|
|
|
(see `onyx periodic --type daily`), falling back to Obsidian's Daily Notes
|
|
|
|
or Periodic Notes plugin settings, then to built-in defaults."""
|
|
|
|
or Periodic Notes plugin settings, then to built-in defaults."""
|
|
|
|
OnyxCLI().daily_note(vault, date=date, next_=next_, previous=previous)
|
|
|
|
OnyxCLI().daily_note(vault, date, next_, previous, not no_open, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
|
|
|
@cli.command()
|
|
|
|
@click.option('--vault', help="Vault name (if not using default)")
|
|
|
|
@click.option('--vault', help="Vault name (if not using default)")
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
|
|
|
@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")
|
|
|
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
|
|
|
def weekly(vault, date, next_, previous):
|
|
|
|
@_periodic_output_options
|
|
|
|
|
|
|
|
def weekly(vault, date, next_, previous, no_open, print_path):
|
|
|
|
"""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`."""
|
|
|
|
Folder, filename format, and template are configurable via `onyx periodic --type weekly`."""
|
|
|
|
OnyxCLI().weekly_note(vault, date=date, next_=next_, previous=previous)
|
|
|
|
OnyxCLI().weekly_note(vault, date, next_, previous, not no_open, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
|
|
|
@cli.command()
|
|
|
|
@click.option('--vault', help="Vault name (if not using default)")
|
|
|
|
@click.option('--vault', help="Vault name (if not using default)")
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
|
|
|
@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")
|
|
|
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
|
|
|
def monthly(vault, date, next_, previous):
|
|
|
|
@_periodic_output_options
|
|
|
|
|
|
|
|
def monthly(vault, date, next_, previous, no_open, print_path):
|
|
|
|
"""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`."""
|
|
|
|
Folder, filename format, and template are configurable via `onyx periodic --type monthly`."""
|
|
|
|
OnyxCLI().monthly_note(vault, date=date, next_=next_, previous=previous)
|
|
|
|
OnyxCLI().monthly_note(vault, date, next_, previous, not no_open, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
|
|
|
@cli.command()
|
|
|
|
@click.option('--vault', help="Vault name (if not using default)")
|
|
|
|
@click.option('--vault', help="Vault name (if not using default)")
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
|
|
|
@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")
|
|
|
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
|
|
|
def quarterly(vault, date, next_, previous):
|
|
|
|
@_periodic_output_options
|
|
|
|
|
|
|
|
def quarterly(vault, date, next_, previous, no_open, print_path):
|
|
|
|
"""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`."""
|
|
|
|
Folder, filename format, and template are configurable via `onyx periodic --type quarterly`."""
|
|
|
|
OnyxCLI().quarterly_note(vault, date=date, next_=next_, previous=previous)
|
|
|
|
OnyxCLI().quarterly_note(vault, date, next_, previous, not no_open, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
|
|
|
@cli.command()
|
|
|
|
@click.option('--vault', help="Vault name (if not using default)")
|
|
|
|
@click.option('--vault', help="Vault name (if not using default)")
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
|
|
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
|
|
|
@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")
|
|
|
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
|
|
|
def yearly(vault, date, next_, previous):
|
|
|
|
@_periodic_output_options
|
|
|
|
|
|
|
|
def yearly(vault, date, next_, previous, no_open, print_path):
|
|
|
|
"""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`."""
|
|
|
|
Folder, filename format, and template are configurable via `onyx periodic --type yearly`."""
|
|
|
|
OnyxCLI().yearly_note(vault, date=date, next_=next_, previous=previous)
|
|
|
|
OnyxCLI().yearly_note(vault, date, next_, previous, not no_open, print_path)
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
|
|
|
@cli.command()
|
|
|
|
@click.option('--type', 'note_type', required=True,
|
|
|
|
@click.option('--type', 'note_type', required=True,
|
|
|
@@ -1040,7 +1109,9 @@ def print_note(note_name, vault):
|
|
|
|
def move(current_path, new_path, vault, open_after):
|
|
|
|
def move(current_path, new_path, vault, open_after):
|
|
|
|
"""Move or rename a note and auto-update internal links
|
|
|
|
"""Move or rename a note and auto-update internal links
|
|
|
|
|
|
|
|
|
|
|
|
Automatically updates all [[links]] pointing to this note in other vault files.
|
|
|
|
Rewrites wikilinks that resolve to this note anywhere in the vault: [[name]],
|
|
|
|
|
|
|
|
[[name|alias]], [[name#heading]], embeds, path links and frontmatter links.
|
|
|
|
|
|
|
|
Refuses to overwrite an existing note.
|
|
|
|
|
|
|
|
|
|
|
|
USAGE:
|
|
|
|
USAGE:
|
|
|
|
onyx move "old-name" "new-name"
|
|
|
|
onyx move "old-name" "new-name"
|
|
|
@@ -1098,4 +1169,9 @@ def frontmatter_command(note_name, edit, view, clear, delete, key, value, open_f
|
|
|
|
cli.frontmatter_delete(note_name, key, vault)
|
|
|
|
cli.frontmatter_delete(note_name, key, vault)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
|
|
|
# Scripts read onyx's output (e.g. `--print-path`): emit UTF-8 with LF on every OS.
|
|
|
|
|
|
|
|
# Without this, Windows pipes get the ANSI code page (é -> 0xE9; PyInstaller ignores
|
|
|
|
|
|
|
|
# PYTHONUTF8) and CRLF, whose trailing \r survives bash's $(...).
|
|
|
|
|
|
|
|
for stream in (sys.stdout, sys.stderr):
|
|
|
|
|
|
|
|
stream.reconfigure(encoding='utf-8', newline='\n')
|
|
|
|
cli()
|
|
|
|
cli()
|