Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f6b598c4a | ||
|
|
b2f609ec4a | ||
|
|
33544edf07 | ||
|
|
34d28c03fa |
No files matched your search
@@ -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
|
||||
@@ -322,7 +329,7 @@ onyx --version
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python 3.7+
|
||||
- Python 3.9+ (only to run from source; the release binaries bundle Python)
|
||||
- click
|
||||
- pyyaml
|
||||
|
||||
|
||||
+82
-70
@@ -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]')
|
||||
@@ -440,41 +461,18 @@ 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,18 +870,39 @@ 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")
|
||||
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]:
|
||||
"""--key values, also accepting comma/bracket-separated keys (legacy)."""
|
||||
@@ -960,7 +958,15 @@ class OnyxCLI:
|
||||
first item. Each item is taken whole (no comma splitting)."""
|
||||
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||
note_path = self._find_note(vault_path, note_name)
|
||||
existing, _, _ = self._parse_frontmatter(note_path.read_text(encoding='utf-8-sig'))
|
||||
match = _FRONTMATTER.match(note_path.read_text(encoding='utf-8-sig'))
|
||||
try:
|
||||
existing = (yaml.load(match.group(1), Loader=_YAML_LOADER) or {}) if match else {}
|
||||
except yaml.YAMLError as error:
|
||||
# An unreadable frontmatter would look like "key missing" and the splice would
|
||||
# replace the existing (unparsed) items: refuse instead of losing them.
|
||||
raise click.UsageError(f"Frontmatter of {note_name} is not valid YAML; fix it first:\n{error}")
|
||||
if not isinstance(existing, dict):
|
||||
raise click.UsageError(f"Frontmatter of {note_name} is not a key: value mapping; fix it first")
|
||||
|
||||
value = existing.get(key)
|
||||
current = value if isinstance(value, list) else ([] if value in (None, '') else [value])
|
||||
@@ -1214,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.0', 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
|
||||
@@ -1258,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)
|
||||
|
||||
@@ -1559,9 +1570,10 @@ def frontmatter_command(note_name, edit, view, clear, delete, add, remove, key,
|
||||
cli.frontmatter_list_items(note_name, key[0], value, remove=remove, vault=vault)
|
||||
|
||||
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 $(...).
|
||||
# Scripts talk to onyx through pipes (`--content -`, `--print-path`): UTF-8 with LF on
|
||||
# every OS. Without this, Windows pipes use the ANSI code page (é -> 0xE9 out, UTF-8 in
|
||||
# read as "é"; PyInstaller ignores PYTHONUTF8) and CRLF, whose \r survives bash's $(...).
|
||||
sys.stdin.reconfigure(encoding='utf-8')
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
stream.reconfigure(encoding='utf-8', newline='\n')
|
||||
cli()
|
||||
@@ -1,5 +1,7 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
import yaml
|
||||
import shutil
|
||||
@@ -10,6 +12,8 @@ import click
|
||||
from click.testing import CliRunner
|
||||
from datetime import datetime
|
||||
|
||||
SRC = Path(__file__).resolve().parent.parent / 'src' / 'onyx.py'
|
||||
|
||||
class TestOnyxCLI(unittest.TestCase):
|
||||
def setUp(self):
|
||||
# Create temporary test directory and files
|
||||
@@ -245,6 +249,16 @@ Test content"""
|
||||
self.assertEqual([c.args[0] for c in echo.call_args_list],
|
||||
["No change to 'participants' in m", "No change to 'absent' in m"])
|
||||
|
||||
def test_frontmatter_add_refuses_invalid_yaml(self):
|
||||
"""Unparseable frontmatter must not look like 'key missing' and lose existing items"""
|
||||
note = self.test_dir / 'person.md'
|
||||
content = '---\nchildren: "[[Julia]]", "[[Jacob]]"\ntype: person\n---\nCorps\n'
|
||||
note.write_text(content, encoding='utf-8')
|
||||
for remove in (False, True):
|
||||
with self.assertRaises(click.UsageError):
|
||||
self.cli.frontmatter_list_items('person', 'children', ('[[Nouveau]]',), remove=remove)
|
||||
self.assertEqual(note.read_text(encoding='utf-8'), content)
|
||||
|
||||
def test_frontmatter_add_refuses_unquoted_links(self):
|
||||
note = self.test_dir / 'bad.md'
|
||||
content = '---\nrelated:\n - [[Haro]]\n---\n'
|
||||
@@ -344,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',
|
||||
@@ -594,5 +631,20 @@ Test content"""
|
||||
self.assertIn(str(self.test_dir.resolve()), printed)
|
||||
self.assertNotIn('path_prefix', printed)
|
||||
|
||||
def test_pipes_are_utf8_without_utf8_mode(self):
|
||||
"""stdin/stdout are UTF-8 even when Python isn't in UTF-8 mode (frozen exe on Windows)"""
|
||||
note = self.test_dir / 'd.md'
|
||||
note.write_text('## Journal\n', encoding='utf-8')
|
||||
env = {k: v for k, v in os.environ.items() if k not in ('PYTHONUTF8', 'PYTHONIOENCODING')}
|
||||
home = str(self.temp_config_dir.resolve())
|
||||
env.update(PYTHONUTF8='0', USERPROFILE=home, HOME=home)
|
||||
result = subprocess.run([sys.executable, str(SRC), 'section', 'd', '--heading', 'Journal',
|
||||
'--content', '-'], input='Réunion « test »'.encode('utf-8'),
|
||||
capture_output=True, env=env)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(note.read_text(encoding='utf-8'), '## Journal\nRéunion « test »\n')
|
||||
printed = subprocess.run([sys.executable, str(SRC), 'print-note', 'd'], capture_output=True, env=env)
|
||||
self.assertEqual(printed.stdout, '## Journal\nRéunion « test »\n\n'.encode('utf-8'))
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user