feat: v0.4.3 — open/print-note resolve by filename or alias, refuse ambiguous names

This commit is contained in:
olivier committed 2026-11-05 11:21:55 -05:00
1 parent b2f609ec4a
commit 7f6b598c4a
3 files changed
+99 -66

No files matched your search

+7
View File
@@ -71,6 +71,13 @@ onyx open "note-name"
onyx open "note-name" --vault "vault-name" onyx open "note-name" --vault "vault-name"
``` ```
`open`, `print-note`, `section` and `frontmatter` find a note by its exact
vault-relative path, otherwise by filename or `aliases` entry (case and accents
ignored; a filename beats an alias) or by a partial path such as
`people/Haro`. When several notes match, nothing is opened and the candidate
paths are listed; when none match, close filenames are suggested. There is no
fuzzy opening. `move` and `delete` still require the exact path.
### Periodic Notes ### Periodic Notes
```bash ```bash
+69 -66
View File
@@ -10,6 +10,7 @@ import builtins
from pathlib import Path from pathlib import Path
import re import re
import unicodedata import unicodedata
import difflib
from collections import Counter 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
@@ -91,6 +92,26 @@ def _iter_notes(vault_path: Path):
yield path yield path
def _match_notes(vault_path: Path, name: str, folder: Optional[str] = None) -> List[tuple]:
"""(path, alias) for notes whose filename (alias None) or one of whose aliases equals
`name`, case and accents ignored, sorted by path. No fuzzy matching."""
wanted = _fold(name)
prefix = folder.strip('/') + '/' if folder else None
matches = []
for note in sorted(_iter_notes(vault_path)):
if prefix and not note.relative_to(vault_path).as_posix().startswith(prefix):
continue
if _fold(note.stem) == wanted:
matches.append((note, None))
continue
aliases = _read_frontmatter(note.read_text(encoding='utf-8-sig'), needed='aliases').get('aliases') or []
aliases = aliases if isinstance(aliases, list) else [aliases]
alias = next((str(a) for a in aliases if a is not None and _fold(a) == wanted), None)
if alias is not None:
matches.append((note, alias))
return matches
_HEADING = re.compile(r'^(#{1,6})[ \t]+(.*?)[ \t]*$') _HEADING = re.compile(r'^(#{1,6})[ \t]+(.*?)[ \t]*$')
_FENCE = re.compile(r'^[ \t]*(`{3,}|~{3,})') _FENCE = re.compile(r'^[ \t]*(`{3,}|~{3,})')
_LIST_ITEM = re.compile(r'^[ \t]*([-*+]|\d+[.)])[ \t]') _LIST_ITEM = re.compile(r'^[ \t]*([-*+]|\d+[.)])[ \t]')
@@ -440,41 +461,18 @@ class OnyxCLI:
def open_note(self, note_name: str, vault: str = None): def open_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)
# Try exact path first # A folder opens in the system file explorer
note_path = vault_path / note_name folder_path = vault_path / note_name
if folder_path.is_dir():
# Check if it's a directory first
if note_path.is_dir():
# Open directory in system explorer
if sys.platform == 'win32': if sys.platform == 'win32':
os.startfile(note_path) os.startfile(folder_path)
elif sys.platform == 'darwin': elif sys.platform == 'darwin':
subprocess.run(['open', note_path]) subprocess.run(['open', folder_path])
else: else:
subprocess.run(['xdg-open', note_path]) subprocess.run(['xdg-open', folder_path])
return return
if not note_path.suffix: note_path = self._find_note(vault_path, note_name)
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) relative_path = note_path.relative_to(vault_path)
# URL encode both the vault name and file path to handle special characters # URL encode both the vault name and file path to handle special characters
encoded_vault = self._url_encode(vault_name) encoded_vault = self._url_encode(vault_name)
@@ -700,30 +698,16 @@ class OnyxCLI:
"""Print notes whose filename or one of whose aliases equals `name` (case and accents """Print notes whose filename or one of whose aliases equals `name` (case and accents
ignored, no fuzzy matching). Returns the number of matches.""" ignored, no fuzzy matching). Returns the number of matches."""
vault_name, vault_path = self._get_vault_and_path(vault) vault_name, vault_path = self._get_vault_and_path(vault)
notes = list(_iter_notes(vault_path)) matches = _match_notes(vault_path, name, folder)
stems = Counter(p.stem.casefold() for p in notes) stems = Counter(p.stem.casefold() for p in _iter_notes(vault_path)) if link else None
wanted = _fold(name) for note, alias in matches:
matches = 0
for note in sorted(notes):
if folder and not note.relative_to(vault_path).as_posix().startswith(folder.strip('/') + '/'):
continue
if _fold(note.stem) == wanted:
display = None
else:
text = note.read_text(encoding='utf-8-sig')
aliases = _read_frontmatter(text, needed='aliases').get('aliases') or []
aliases = aliases if isinstance(aliases, list) else [aliases]
display = next((str(a) for a in aliases if a is not None and _fold(a) == wanted), None)
if display is None:
continue
matches += 1
rel = note.relative_to(vault_path).with_suffix('').as_posix() rel = note.relative_to(vault_path).with_suffix('').as_posix()
if link: if link:
target = note.stem if stems[note.stem.casefold()] == 1 else rel target = note.stem if stems[note.stem.casefold()] == 1 else rel
click.echo(f"[[{target}|{display}]]" if display else f"[[{target}]]") click.echo(f"[[{target}|{alias}]]" if alias else f"[[{target}]]")
else: else:
click.echo(rel) click.echo(rel)
return matches return len(matches)
def _notes_in(self, vault_path: Path, folder: Optional[str]) -> List[Path]: def _notes_in(self, vault_path: Path, folder: Optional[str]) -> List[Path]:
base = vault_path / folder if folder else vault_path base = vault_path / folder if folder else vault_path
@@ -782,14 +766,7 @@ class OnyxCLI:
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)
note_path = vault_path / note_name click.echo(self._find_note(vault_path, note_name).read_text(encoding='utf-8-sig'))
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): 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. """Move/rename a note and rewrite wikilinks that resolve to it.
@@ -893,18 +870,39 @@ class OnyxCLI:
return {}, content, 0 return {}, content, 0
def _find_note(self, vault_path: Path, note_name: str) -> Path: def _find_note(self, vault_path: Path, note_name: str) -> Path:
"""Exact vault-relative path first, then the first note with that name anywhere.""" """Exact vault-relative path first; otherwise the single note whose filename or alias
matches (case and accents ignored), or whose path ends with `note_name` when it
contains '/'. Filename matches win over alias matches. Several candidates or none
raise a UsageError listing candidates or close filenames; nothing is guessed."""
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 note_path.is_file():
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")
return note_path return note_path
name = note_name[:-3] if note_name.lower().endswith('.md') else note_name
if '/' in name.replace('\\', '/'):
wanted = _fold(name.replace('\\', '/').strip('/'))
candidates = [p for p in sorted(_iter_notes(vault_path))
if (rel := _fold(p.relative_to(vault_path).with_suffix('').as_posix())) == wanted
or rel.endswith('/' + wanted)]
else:
matches = _match_notes(vault_path, name)
candidates = [p for p, alias in matches if alias is None] or [p for p, _ in matches]
if len(candidates) == 1:
return candidates[0]
if candidates:
listing = '\n'.join(f" {p.relative_to(vault_path).with_suffix('').as_posix()}" for p in candidates)
raise click.UsageError(f"Note {note_name} is ambiguous; use one of these paths:\n{listing}")
stems = sorted({p.stem for p in _iter_notes(vault_path)})
by_fold = {}
for stem in stems:
by_fold.setdefault(_fold(stem), stem)
close = difflib.get_close_matches(_fold(name), list(by_fold), n=3, cutoff=0.6)
hint = f" Did you mean: {', '.join(by_fold[c] for c in close)}?" if close else ""
raise click.UsageError(f"Note {note_name} does not exist.{hint}")
@staticmethod @staticmethod
def _split_keys(keys: tuple) -> List[str]: def _split_keys(keys: tuple) -> List[str]:
"""--key values, also accepting comma/bracket-separated keys (legacy).""" """--key values, also accepting comma/bracket-separated keys (legacy)."""
@@ -1222,7 +1220,7 @@ def _periodic_output_options(command):
help="Don't open Obsidian; a newly created note keeps raw Templater syntax " help="Don't open Obsidian; a newly created note keeps raw Templater syntax "
"until Obsidian processes it")(command) "until Obsidian processes it")(command)
@click.version_option(version='0.4.2', prog_name='onyx') @click.version_option(version='0.4.3', 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
@@ -1266,11 +1264,16 @@ def print_default():
def open(note_name, vault): def open(note_name, vault):
"""Open a note in Obsidian """Open a note in Obsidian
Searches for the note in the vault and opens it in Obsidian. Supports nested directories. Exact vault-relative path first; otherwise the one note whose filename or alias
matches (case and accents ignored), or whose path ends with the given partial
path. Filename matches win over aliases. When several notes match, nothing is
opened and the candidate paths are listed; when none match, close filenames are
suggested. No fuzzy opening. A folder opens in the file explorer.
USAGE: USAGE:
onyx open "my-note" onyx open "my-note"
onyx open "folder/my-note" onyx open "folder/my-note"
onyx open "an alias"
""" """
OnyxCLI().open_note(note_name, vault) OnyxCLI().open_note(note_name, vault)
+23
View File
@@ -358,6 +358,29 @@ Test content"""
(['[[entities/businesses/Haro]]'], 1)) (['[[entities/businesses/Haro]]'], 1))
self.assertEqual(self._echoed(self.cli.resolve_note, 'Charbonneau'), ([], 0)) self.assertEqual(self._echoed(self.cli.resolve_note, 'Charbonneau'), ([], 0))
def test_find_note_by_name_alias_or_partial_path(self):
"""open/cat/frontmatter lookup: alias and accent-insensitive name resolve to the one
note; filename beats alias; several candidates or none raise and never guess"""
self._write_notes({
'entities/people/Mikaël Valton Charette.md': '---\naliases: [Mikaël]\n---\n',
'entities/people/Haro.md': '',
'archives/Haro.md': '',
'entities/businesses/Sécuritech.md': '',
'notes/Securitas.md': '---\naliases: [Sécuritech]\n---\n',
})
find = lambda name: self.cli._find_note(self.test_dir, name).relative_to(self.test_dir).as_posix()
self.assertEqual(find('mikael'), 'entities/people/Mikaël Valton Charette.md')
self.assertEqual(find('securitech'), 'entities/businesses/Sécuritech.md')
self.assertEqual(find('people/haro'), 'entities/people/Haro.md')
with self.assertRaisesRegex(click.UsageError, r'ambiguous[\s\S]*archives/Haro\n entities/people/Haro'):
find('Haro')
with self.assertRaisesRegex(click.UsageError, r'does not exist\. Did you mean: Securitas'):
find('Securitass')
with patch.object(OnyxCLI, '_open_uri') as open_uri:
self.cli.open_note('Mikaël')
open_uri.assert_called_once_with(
'obsidian://open?vault=test_vault&file=entities/people/Mika%C3%ABl%20Valton%20Charette.md')
def test_list_where(self): def test_list_where(self):
self._write_notes({ self._write_notes({
'projects/A.md': '---\ntype: project\nstatus: active\nclient: "[[Symbolitech]]"\n---\n', 'projects/A.md': '---\ntype: project\nstatus: active\nclient: "[[Symbolitech]]"\n---\n',