From 7f6b598c4a6f9d708b7416a0124f94c345ca5e4b Mon Sep 17 00:00:00 2001 From: Olivier Date: Thu, 5 Nov 2026 11:21:55 -0500 Subject: [PATCH] =?UTF-8?q?feat:=20v0.4.3=20=E2=80=94=20open/print-note=20?= =?UTF-8?q?resolve=20by=20filename=20or=20alias,=20refuse=20ambiguous=20na?= =?UTF-8?q?mes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 ++ src/onyx.py | 139 +++++++++++++++++++------------------ tests/test_obsidian_cli.py | 23 ++++++ 3 files changed, 101 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index 73dd82b..f198ee4 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,13 @@ onyx open "note-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 ```bash diff --git a/src/onyx.py b/src/onyx.py index 816a70b..d13acec 100644 --- a/src/onyx.py +++ b/src/onyx.py @@ -10,6 +10,7 @@ import builtins from pathlib import Path import re import unicodedata +import difflib from collections import Counter from typing import List, Union, Optional, Dict, Any from urllib.parse import quote @@ -91,6 +92,26 @@ def _iter_notes(vault_path: 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]*$') _FENCE = re.compile(r'^[ \t]*(`{3,}|~{3,})') _LIST_ITEM = re.compile(r'^[ \t]*([-*+]|\d+[.)])[ \t]') @@ -439,42 +460,19 @@ class OnyxCLI: 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 + # A folder opens in the system file explorer + folder_path = vault_path / note_name + if folder_path.is_dir(): if sys.platform == 'win32': - os.startfile(note_path) + os.startfile(folder_path) elif sys.platform == 'darwin': - subprocess.run(['open', note_path]) + subprocess.run(['open', folder_path]) else: - subprocess.run(['xdg-open', note_path]) + subprocess.run(['xdg-open', folder_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 + note_path = self._find_note(vault_path, note_name) 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) @@ -700,30 +698,16 @@ class OnyxCLI: """Print notes whose filename or one of whose aliases equals `name` (case and accents ignored, no fuzzy matching). Returns the number of matches.""" vault_name, vault_path = self._get_vault_and_path(vault) - notes = list(_iter_notes(vault_path)) - stems = Counter(p.stem.casefold() for p in notes) - wanted = _fold(name) - 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 + matches = _match_notes(vault_path, name, folder) + stems = Counter(p.stem.casefold() for p in _iter_notes(vault_path)) if link else None + for note, alias in matches: rel = note.relative_to(vault_path).with_suffix('').as_posix() if link: 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: click.echo(rel) - return matches + return len(matches) def _notes_in(self, vault_path: Path, folder: Optional[str]) -> List[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): 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')) + click.echo(self._find_note(vault_path, note_name).read_text(encoding='utf-8-sig')) 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. @@ -893,17 +870,38 @@ class OnyxCLI: return {}, content, 0 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 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") - return note_path + if note_path.is_file(): + 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 def _split_keys(keys: tuple) -> List[str]: @@ -1222,7 +1220,7 @@ def _periodic_output_options(command): help="Don't open Obsidian; a newly created note keeps raw Templater syntax " "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') def cli(): """Onyx - Interact with Obsidian vaults from the command line @@ -1266,11 +1264,16 @@ def print_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. - + 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: onyx open "my-note" onyx open "folder/my-note" + onyx open "an alias" """ OnyxCLI().open_note(note_name, vault) diff --git a/tests/test_obsidian_cli.py b/tests/test_obsidian_cli.py index e93c0bc..04e5ab3 100644 --- a/tests/test_obsidian_cli.py +++ b/tests/test_obsidian_cli.py @@ -358,6 +358,29 @@ Test content""" (['[[entities/businesses/Haro]]'], 1)) 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): self._write_notes({ 'projects/A.md': '---\ntype: project\nstatus: active\nclient: "[[Symbolitech]]"\n---\n',