5 Commits
4 changed files with 155 additions and 83 deletions

No files matched your search

+8 -1
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
@@ -322,7 +329,7 @@ onyx --version
## Requirements ## Requirements
- Python 3.7+ - Python 3.9+ (only to run from source; the release binaries bundle Python)
- click - click
- pyyaml - pyyaml
+13 -12
View File
@@ -86,6 +86,11 @@ scratch vault/config — never against the real `~/.onyx-cli/config.yaml`.
> **Windows gotcha**: the plain bash tool can't execute a freshly built > **Windows gotcha**: the plain bash tool can't execute a freshly built
> `.exe` directly (`command not found`) — always invoke it through > `.exe` directly (`command not found`) — always invoke it through
> `cmd.exe /c "onyx.exe ..."`. > `cmd.exe /c "onyx.exe ..."`.
>
> **Linux scratch config**: run the smoke as a script file
> (`wsl -d Ubuntu-24.04 -- bash smoke.sh`), and save the binary path
> (`B=$HOME/onyx-build/dist/onyx`) before pointing `HOME` at a scratch
> directory, so the real config stays untouched.
## 5. Deploy locally (optional) ## 5. Deploy locally (optional)
@@ -129,33 +134,29 @@ git push origin vX.Y.Z
## 7. Create the Gitea release ## 7. Create the Gitea release
`tea` hangs indefinitely under a plain non-interactive shell call, for Use `gt` (gitea-cli 1.0+; `tea` is archived). `gt` never pushes, so step 6
*any* subcommand, including fully local ones. Always launch it as a must be done first; `--verify-tag` refuses a tag the server doesn't have.
supervised process (hub `start`/`wait`/`logs`), never via the bash tool From the bash tool, invoke it through `cmd.exe /c` like the exe above.
directly.
Write release notes to a scratch file, then create the release with both Write release notes to a scratch file, then create the release with both
assets in one call: assets in one call:
``` ```
tea releases create --repo olivier/onyx-cli --tag vX.Y.Z --title vX.Y.Z \ gt release create vX.Y.Z dist/onyx.exe dist/onyx-linux --title vX.Y.Z \
--note-file release-notes-vX.Y.Z.md -a dist/onyx.exe -a dist/onyx-linux --notes-file release-notes-vX.Y.Z.md --verify-tag --no-input
``` ```
If the release already exists and you're adding a platform binary later If the release already exists and you're adding a platform binary later
(e.g. the Linux build wasn't ready yet), attach it separately instead: (e.g. the Linux build wasn't ready yet), attach it separately instead
(`--clobber` replaces an asset with the same name):
``` ```
tea releases assets create --repo olivier/onyx-cli vX.Y.Z dist/<file> gt release upload vX.Y.Z dist/<file>
``` ```
Delete the scratch release-notes file afterward — it's not a repo Delete the scratch release-notes file afterward — it's not a repo
convention file. convention file.
> `tea repos create --owner olivier` fails with `GetOrgByName` — `--owner`
> targets an organization, not your personal account. Omit it entirely
> when creating a repo under your own user.
## 8. Verify the release ## 8. Verify the release
```bash ```bash
+82 -70
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)."""
@@ -960,7 +958,15 @@ class OnyxCLI:
first item. Each item is taken whole (no comma splitting).""" first item. Each item is taken whole (no comma splitting)."""
vault_name, vault_path = self._get_vault_and_path(vault) vault_name, vault_path = self._get_vault_and_path(vault)
note_path = self._find_note(vault_path, note_name) 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) value = existing.get(key)
current = value if isinstance(value, list) else ([] if value in (None, '') else [value]) 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 " 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.0', 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
@@ -1258,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)
@@ -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) cli.frontmatter_list_items(note_name, key[0], value, remove=remove, vault=vault)
if __name__ == '__main__': if __name__ == '__main__':
# Scripts read onyx's output (e.g. `--print-path`): emit UTF-8 with LF on every OS. # Scripts talk to onyx through pipes (`--content -`, `--print-path`): UTF-8 with LF on
# Without this, Windows pipes get the ANSI code page (é -> 0xE9; PyInstaller ignores # every OS. Without this, Windows pipes use the ANSI code page (é -> 0xE9 out, UTF-8 in
# PYTHONUTF8) and CRLF, whose trailing \r survives bash's $(...). # 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): for stream in (sys.stdout, sys.stderr):
stream.reconfigure(encoding='utf-8', newline='\n') stream.reconfigure(encoding='utf-8', newline='\n')
cli() cli()
+52
View File
@@ -1,5 +1,7 @@
import json import json
import os import os
import subprocess
import sys
import unittest import unittest
import yaml import yaml
import shutil import shutil
@@ -10,6 +12,8 @@ import click
from click.testing import CliRunner from click.testing import CliRunner
from datetime import datetime from datetime import datetime
SRC = Path(__file__).resolve().parent.parent / 'src' / 'onyx.py'
class TestOnyxCLI(unittest.TestCase): class TestOnyxCLI(unittest.TestCase):
def setUp(self): def setUp(self):
# Create temporary test directory and files # Create temporary test directory and files
@@ -245,6 +249,16 @@ Test content"""
self.assertEqual([c.args[0] for c in echo.call_args_list], self.assertEqual([c.args[0] for c in echo.call_args_list],
["No change to 'participants' in m", "No change to 'absent' in m"]) ["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): def test_frontmatter_add_refuses_unquoted_links(self):
note = self.test_dir / 'bad.md' note = self.test_dir / 'bad.md'
content = '---\nrelated:\n - [[Haro]]\n---\n' content = '---\nrelated:\n - [[Haro]]\n---\n'
@@ -344,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',
@@ -594,5 +631,20 @@ Test content"""
self.assertIn(str(self.test_dir.resolve()), printed) self.assertIn(str(self.test_dir.resolve()), printed)
self.assertNotIn('path_prefix', 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__': if __name__ == '__main__':
unittest.main() unittest.main()