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

+71 -10
View File
@@ -678,9 +678,21 @@ class OnyxCLI:
_write_text(note_path, new_content)
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):
"""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)
note_path = self._find_note(vault_path, note_name)
existing, _, _ = self._parse_frontmatter(note_path.read_text(encoding='utf-8-sig'))
updates = {}
@@ -691,14 +703,50 @@ class OnyxCLI:
for i, key in enumerate(keys):
value = values[i] if values and i < len(values) else None
for k in self._split_keys((key,)):
if k == 'tags':
updates[k] = [t.strip() for t in value.split(',') if t.strip()] if value else []
if k == 'tags' or isinstance(existing.get(k), list):
updates[k] = self._split_list(value)
else:
updates[k] = value if value is not None else ""
self._rewrite_frontmatter(note_path, updates)
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):
vault_name, vault_path = self._get_vault_and_path(vault)
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('--clear', is_flag=True, help="Clear frontmatter values")
@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('--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('--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).")
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
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:
onyx frontmatter "my-note" --view --key "tags"
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"
"""
cli = OnyxCLI()
if sum([edit, view, clear, delete]) != 1:
raise click.UsageError("Exactly one of --edit, --view, --clear, or --delete must be specified")
if sum([edit, view, clear, delete, add, remove]) != 1:
raise click.UsageError("Exactly one of --edit, --view, --clear, --delete, --add or --remove must be specified")
if edit:
if value and len(value) > 1 and len(key) != len(value):
# 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)
raise click.UsageError(f"Number of values ({len(value)}) must match number of keys ({len(key)})")
cli.frontmatter_edit(note_name, key, value, vault)
elif view:
# 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)
elif delete:
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__':
# Scripts read onyx's output (e.g. `--print-path`): emit UTF-8 with LF on every OS.