fix: make frontmatter plugin read string and numeric tags and edit only its own front matter keys

This commit is contained in:
randogoth 2026-10-24 21:37:30 +03:00
parent 633012d1ef
commit 3277e5b323
5 changed files with 176 additions and 35 deletions

72
tests/test_frontmatter.py Normal file
View file

@ -0,0 +1,72 @@
import pytest
import orvanitag.orvani as orvani
from orvanitag.orvani import OrvaniTag
@pytest.fixture
def cwd(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
return tmp_path
def scanned(cwd):
OrvaniTag().scan('.', False)
return (cwd / orvani.CONTEXT_FILE).read_text()
def test_reads_lists_strings_and_plain_scalars(cwd):
(cwd / 'a.md').write_text('---\ntags: lofi\nprojects: album\nnote: first take\n---\n')
(cwd / 'b.md').write_text('---\ntags: "blog, lo fi"\n---\n')
(cwd / 'c.md').write_text('---\ntags: [2023, yes]\ncontexts:\n - desk\n---\n')
assert scanned(cwd) == (
'a.md --- +album #lofi first take\n'
'b.md --- #blog #lo-fi\n'
'c.md --- @desk #2023 #yes\n'
)
def test_write_changes_only_its_own_keys(cwd):
post = '---\ntitle: Post\n# my comment\ndate: 2024-01-05\ntags:\n - blog\n - lo-fi\nlayout: post\n---\nBody text.\n'
(cwd / 'post.md').write_text(post)
o = OrvaniTag()
o.add('post.md', '#blog', '#lo-fi', '#new')
assert o.write_metadata('post.md', 'frontmatter')[0] == 0
assert (cwd / 'post.md').read_text() == (
'---\ntitle: Post\n# my comment\ndate: 2024-01-05\ntags: [blog, lo-fi, new]\nlayout: post\n---\nBody text.\n'
)
def test_write_adds_missing_keys_and_quotes_when_needed(cwd):
(cwd / 'a.md').write_text('---\ntitle: A\n---\ntext\n')
o = OrvaniTag()
o.add('a.md', '+c++', '#yes', 'a: note')
o.write_metadata('a.md', 'frontmatter')
assert (cwd / 'a.md').read_text() == '---\ntitle: A\nprojects: ["c++"]\ntags: ["yes"]\nnote: "a: note"\n---\ntext\n'
(cwd / orvani.CONTEXT_FILE).unlink()
assert scanned(cwd) == 'a.md --- +c++ #yes a: note\n'
def test_write_creates_front_matter_and_keeps_crlf(cwd):
(cwd / 'a.md').write_bytes(b'# Heading\r\n')
o = OrvaniTag()
o.add('a.md', '#lofi')
o.write_metadata('a.md', 'frontmatter')
assert (cwd / 'a.md').read_bytes() == b'---\r\ntags: [lofi]\r\n---\r\n# Heading\r\n'
def test_empty_categories_leave_existing_keys_alone(cwd):
(cwd / 'a.md').write_text('---\nprojects: [old]\n---\n')
o = OrvaniTag()
o.add('a.md', '#lofi')
o.write_metadata('a.md', 'frontmatter')
assert (cwd / 'a.md').read_text() == '---\nprojects: [old]\ntags: [lofi]\n---\n'
def test_rst_is_not_handled(cwd):
(cwd / 'doc.rst').write_text('Title\n=====\n')
o = OrvaniTag()
o.add('doc.rst', '#x')
assert o.write_metadata('doc.rst', 'frontmatter')[0] == 4
assert (cwd / 'doc.rst').read_text() == 'Title\n=====\n'