diff --git a/src/onyx.py b/src/onyx.py index e3b9e9d..816a70b 100644 --- a/src/onyx.py +++ b/src/onyx.py @@ -960,7 +960,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 +1222,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.1', prog_name='onyx') +@click.version_option(version='0.4.2', prog_name='onyx') @click.group(name='onyx') def cli(): """Onyx - Interact with Obsidian vaults from the command line diff --git a/tests/test_obsidian_cli.py b/tests/test_obsidian_cli.py index 1609464..e93c0bc 100644 --- a/tests/test_obsidian_cli.py +++ b/tests/test_obsidian_cli.py @@ -249,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'