feat(frontmatter): --add/--remove list items; --edit keeps existing list type

- --edit splits on commas for tags and for keys already holding a list
- --add/--remove change single items, matched by wikilink target, no duplicates
- refuse lists with unquoted [[links]] (parsed as nested lists)
This commit is contained in:
olivier committed 2026-10-19 11:48:39 -04:00
1 parent 543ce76207
commit 0f763f98ed
3 files changed
+141 -12

No files matched your search

+12 -2
View File
@@ -231,6 +231,10 @@ onyx frontmatter "note-name" --edit --key "tags" --value "project"
onyx frontmatter "note-name" --edit --key "tags" --value "project,urgent" onyx frontmatter "note-name" --edit --key "tags" --value "project,urgent"
onyx frontmatter "note-name" --edit --key "status" --value "in-progress" onyx frontmatter "note-name" --edit --key "status" --value "in-progress"
# Add / remove single items of a list property (repeat --value for several items)
onyx frontmatter "note-name" --add --key "participants" --value "[[Haro]]" --value "[[Jeffrey]]"
onyx frontmatter "note-name" --remove --key "participants" --value "[[Haro]]"
# Clear frontmatter values # Clear frontmatter values
onyx frontmatter "note-name" --clear --key "tags" onyx frontmatter "note-name" --clear --key "tags"
onyx frontmatter "note-name" --clear --key "date,status,tags" onyx frontmatter "note-name" --clear --key "date,status,tags"
@@ -243,8 +247,14 @@ onyx frontmatter "note-name" --delete --key "date,status,tags"
Edits only touch the targeted keys: key order, quoting, accents and long values elsewhere in the Edits only touch the targeted keys: key order, quoting, accents and long values elsewhere in the
frontmatter stay byte-for-byte identical. Values are written the way Obsidian stores them: plain frontmatter stay byte-for-byte identical. Values are written the way Obsidian stores them: plain
when YAML reads them back unchanged (`done`, `2026-10-19`, `3`), double-quoted otherwise when YAML reads them back unchanged (`done`, `2026-10-19`, `3`), double-quoted otherwise
(`"[[Haro]]"`). `tags` takes a comma-separated list, written as a block list. Cleared keys become (`"[[Haro]]"`). `tags`, and any key that is already a list in the note, take a comma-separated
empty (`status:`), cleared tags `tags: []`. list with `--edit`, written as a block list. Cleared keys become empty (`status:`), cleared tags
`tags: []`.
`--add` and `--remove` change one list without rewriting it: items are taken whole (no comma
splitting) and matched by wikilink target, so `[[Name|Alias]]` and `[[name]]` are the same item.
`--add` skips duplicates, creates the list if the key is missing, and turns a text value into the
first item. A list holding unquoted `[[links]]` (which YAML reads as nested lists) is refused.
### Version ### Version
+71 -10
View File
@@ -678,9 +678,21 @@ class OnyxCLI:
_write_text(note_path, new_content) _write_text(note_path, new_content)
return True return True
@staticmethod
def _split_list(value: Optional[str]) -> List[str]:
return [item.strip() for item in value.split(',') if item.strip()] if value else []
@staticmethod
def _list_item_id(item: str) -> str:
"""Identity of a list item: a wikilink's target (alias and heading ignored), else its text."""
match = _WIKILINK.fullmatch(item.strip())
return (match.group(1).strip() if match else item.strip()).casefold()
def frontmatter_edit(self, note_name: str, keys: tuple, values: tuple = None, vault: str = None): def frontmatter_edit(self, note_name: str, keys: tuple, values: tuple = None, vault: str = None):
"""Set keys. `tags` and keys that are already lists in the note take a comma-separated list."""
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'))
updates = {} updates = {}
@@ -691,14 +703,50 @@ class OnyxCLI:
for i, key in enumerate(keys): for i, key in enumerate(keys):
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 self._split_keys((key,)):
if k == 'tags': if k == 'tags' or isinstance(existing.get(k), list):
updates[k] = [t.strip() for t in value.split(',') if t.strip()] if value else [] updates[k] = self._split_list(value)
else: else:
updates[k] = value if value is not None else "" updates[k] = value if value is not None else ""
self._rewrite_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_list_items(self, note_name: str, key: str, items: tuple, remove: bool = False,
vault: str = None):
"""Add items to, or remove them from, a list property; other items and keys stay as they are.
Items are matched by wikilink target, so "[[Name|Alias]]" and "[[name]]" are the same
item. Adding skips duplicates; a missing key becomes a list, a text value becomes its
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'))
value = existing.get(key)
current = value if isinstance(value, list) else ([] if value in (None, '') else [value])
if any(isinstance(item, (list, dict)) for item in current):
raise click.UsageError(f"'{key}' in {note_name} has nested values (unquoted [[link]]?); "
"fix it by hand: Obsidian needs \"[[link]]\" quoted")
current = [item if isinstance(item, str) else str(item) for item in current if item is not None]
if remove:
dropped = {self._list_item_id(item) for item in items}
new = [item for item in current if self._list_item_id(item) not in dropped]
else:
new, seen = list(current), {self._list_item_id(item) for item in current}
for item in (i.strip() for i in items):
if item and self._list_item_id(item) not in seen:
new.append(item)
seen.add(self._list_item_id(item))
changed = len(new) - len(current)
if not changed:
click.echo(f"No change to '{key}' in {note_name}")
return
self._rewrite_frontmatter(note_path, {key: new})
click.echo(f"{'Removed' if remove else 'Added'} {abs(changed)} item(s) "
f"{'from' if remove else 'to'} '{key}' in {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 = self._find_note(vault_path, note_name) note_path = self._find_note(vault_path, note_name)
@@ -1132,31 +1180,40 @@ def delete(note_path, vault):
@click.option('--view', is_flag=True, help="View frontmatter") @click.option('--view', is_flag=True, help="View frontmatter")
@click.option('--clear', is_flag=True, help="Clear frontmatter values") @click.option('--clear', is_flag=True, help="Clear frontmatter values")
@click.option('--delete', is_flag=True, help="Delete frontmatter keys") @click.option('--delete', is_flag=True, help="Delete frontmatter keys")
@click.option('--add', is_flag=True, help="Add each --value as an item of the list --key (no duplicates)")
@click.option('--remove', is_flag=True, help="Remove each --value from the list --key")
@click.option('--key', required=True, multiple=True, help="Frontmatter key to manage") @click.option('--key', required=True, multiple=True, help="Frontmatter key to manage")
@click.option('--value', multiple=True, help="Value to set or check for") @click.option('--value', multiple=True, help="Value to set or check for")
@click.option('--open', 'open_file', is_flag=True, help="Open the file referenced in the value") @click.option('--open', 'open_file', is_flag=True, help="Open the file referenced in the value")
@click.option('--vault', help="Vault name (if not using default)") @click.option('--vault', help="Vault name (if not using default)")
@click.option('--output-path', is_flag=False, flag_value=True, default=None, help="Resolve relative paths. Can be a flag (uses config prefix) or a string (custom prefix).") @click.option('--output-path', is_flag=False, flag_value=True, default=None, help="Resolve relative paths. Can be a flag (uses config prefix) or a string (custom prefix).")
def frontmatter_command(note_name, edit, view, clear, delete, key, value, open_file, vault, output_path): def frontmatter_command(note_name, edit, view, clear, delete, add, remove, key, value, open_file, vault, output_path):
"""Manage YAML frontmatter in notes """Manage YAML frontmatter in notes
Must specify exactly one action: --edit, --view, --clear, or --delete Must specify exactly one action: --edit, --view, --clear, --delete, --add or --remove
--edit replaces a value; `tags` and keys already holding a list take a
comma-separated list. --add/--remove change single items of a list property;
repeat --value for several items. Items match by wikilink target, so
"[[Name|Alias]]" and "[[name]]" are the same item.
USAGE: USAGE:
onyx frontmatter "my-note" --view --key "tags" onyx frontmatter "my-note" --view --key "tags"
onyx frontmatter "my-note" --edit --key "tags" --value "project,work" onyx frontmatter "my-note" --edit --key "tags" --value "project,work"
onyx frontmatter "my-note" --add --key participants --value "[[Haro]]" --value "[[Jeffrey]]"
onyx frontmatter "my-note" --remove --key participants --value "[[Haro]]"
onyx frontmatter "my-note" --delete --key "date" onyx frontmatter "my-note" --delete --key "date"
""" """
cli = OnyxCLI() cli = OnyxCLI()
if sum([edit, view, clear, delete]) != 1: if sum([edit, view, clear, delete, add, remove]) != 1:
raise click.UsageError("Exactly one of --edit, --view, --clear, or --delete must be specified") raise click.UsageError("Exactly one of --edit, --view, --clear, --delete, --add or --remove must be specified")
if edit: if edit:
if value and len(value) > 1 and len(key) != len(value): if value and len(value) > 1 and len(key) != len(value):
# If we have multiple values, they must match keys count # If we have multiple values, they must match keys count
# Unless we have 1 value, which we apply to all keys (handled in frontmatter_edit) # Unless we have 1 value, which we apply to all keys (handled in frontmatter_edit)
raise click.UsageError(f"Number of values ({len(value)}) must match number of keys ({len(key)})") raise click.UsageError(f"Number of values ({len(value)}) must match number of keys ({len(key)})")
cli.frontmatter_edit(note_name, key, value, vault) cli.frontmatter_edit(note_name, key, value, vault)
elif view: elif view:
# For view, we ignore value unless it's for checking existence, which is complex with multiple keys # For view, we ignore value unless it's for checking existence, which is complex with multiple keys
@@ -1167,6 +1224,10 @@ def frontmatter_command(note_name, edit, view, clear, delete, key, value, open_f
cli.frontmatter_clear(note_name, key, vault) cli.frontmatter_clear(note_name, key, vault)
elif delete: elif delete:
cli.frontmatter_delete(note_name, key, vault) cli.frontmatter_delete(note_name, key, vault)
else:
if len(key) != 1 or not value:
raise click.UsageError("--add/--remove need exactly one --key and at least one --value")
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 read onyx's output (e.g. `--print-path`): emit UTF-8 with LF on every OS.
+58
View File
@@ -256,6 +256,64 @@ Test content"""
self.assertEqual(note.read_text(encoding='utf-8'), self.assertEqual(note.read_text(encoding='utf-8'),
'---\ntags:\n - a\n - b\n---\nCorps\n---\nPas un frontmatter\n') '---\ntags:\n - a\n - b\n---\nCorps\n---\nPas un frontmatter\n')
MEETING = (
'---\n'
'type: meeting\n'
'participants:\n'
' - "[[Stéphane Charbonneau|Stéphane]]"\n'
' - "[[Haro]]"\n'
'summary: "Résumé : décisions."\n'
'---\n'
'Corps\n')
def test_frontmatter_edit_keeps_existing_list_type(self):
"""--edit on a key that is already a list writes a list, not one quoted string"""
note = self.test_dir / 'm.md'
note.write_text(self.MEETING, encoding='utf-8')
self.cli.frontmatter_edit('m', ('participants', 'type'), ('[[Jeffrey]], [[Haro]]', 'réunion, interne'))
self.assertEqual(note.read_text(encoding='utf-8'), self.MEETING
.replace(' - "[[Stéphane Charbonneau|Stéphane]]"\n - "[[Haro]]"\n',
' - "[[Jeffrey]]"\n - "[[Haro]]"\n')
.replace('type: meeting', 'type: réunion, interne'))
def test_frontmatter_add_and_remove_list_items(self):
"""Items match by link target (alias/case ignored); other items and keys untouched"""
note = self.test_dir / 'm.md'
note.write_text(self.MEETING, encoding='utf-8')
self.cli.frontmatter_list_items('m', 'participants', ('[[stéphane charbonneau]]', '[[Jeffrey]]', '[[Jeffrey|Jeff]]'))
self.cli.frontmatter_list_items('m', 'participants', ('[[Haro|H]]',), remove=True)
self.cli.frontmatter_list_items('m', 'mentioned', ('[[Livre, tome 2]]',))
self.cli.frontmatter_list_items('m', 'type', ('log',))
self.assertEqual(note.read_text(encoding='utf-8'),
'---\n'
'type:\n'
' - meeting\n'
' - log\n'
'participants:\n'
' - "[[Stéphane Charbonneau|Stéphane]]"\n'
' - "[[Jeffrey]]"\n'
'summary: "Résumé : décisions."\n'
'mentioned:\n'
' - "[[Livre, tome 2]]"\n'
'---\n'
'Corps\n')
with patch('click.echo') as echo:
self.cli.frontmatter_list_items('m', 'participants', ('[[Jeffrey|J]]',))
self.cli.frontmatter_list_items('m', 'absent', ('x',), remove=True)
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_unquoted_links(self):
note = self.test_dir / 'bad.md'
content = '---\nrelated:\n - [[Haro]]\n---\n'
note.write_text(content, encoding='utf-8')
with self.assertRaises(click.UsageError):
self.cli.frontmatter_list_items('bad', 'related', ('[[Plane]]',))
self.assertEqual(note.read_text(encoding='utf-8'), content)
def test_move_rewrites_every_link_form(self): def test_move_rewrites_every_link_form(self):
"""Aliases, headings, embeds, path links, frontmatter links, regex characters""" """Aliases, headings, embeds, path links, frontmatter links, regex characters"""
(self.test_dir / 'films').mkdir() (self.test_dir / 'films').mkdir()