diff --git a/python/mdhtml/fill.py b/python/mdhtml/fill.py index 665e833..331116a 100644 --- a/python/mdhtml/fill.py +++ b/python/mdhtml/fill.py @@ -28,7 +28,7 @@ from fastcore.script import call_parse from fastcore.xtras import strloader -from fastcore.nbio import nb_frontmatter, cell_frontmatter +from fastcore.nbio import nb_frontmatter, cell_frontmatter, deep_merge from aihist.hist import dlg2md from aidialog.ipynb import read_ipynb from fast5ever import parse_fragment @@ -314,7 +314,7 @@ def instantiate( tmpls = _tmpl_args(templates) meta, body = _frontmatter(src) fd = meta.get("formdata") - merged = {**(fd if isinstance(fd, dict) else {}), **(data or {})} + merged = deep_merge(fd if isinstance(fd, dict) else {}, data or {}) norm, _ = _normalize_offsets(body.lstrip("\n")) woven = _weave(norm, merged, tmpls) res = fill_md(woven, merged, strict=strict, filled=filled, templates=templates) @@ -333,7 +333,7 @@ def instantiate_nb( "Instantiate a dialog: run its participating code cells (the `eval` cascade, opt-in by default), weave their outputs, fill tokens" d = read_ipynb(fname) fd = nb_frontmatter(d, strvals=True).get("formdata") - merged = {**(fd if isinstance(fd, dict) else {}), **(data or {})} + merged = deep_merge(fd if isinstance(fd, dict) else {}, data or {}) shell = _capture_shell() shell.user_ns["__data__"] = merged ran = d.execute(default_eval=False, shell=shell) diff --git a/tests/test_fill.py b/tests/test_fill.py index 8cc98e9..142b0a4 100644 --- a/tests/test_fill.py +++ b/tests/test_fill.py @@ -129,3 +129,16 @@ def test_instantiate_nb(tmp_path): bad = Message('#| eval: true\n1/0') with pytest.raises(ZeroDivisionError) as error: instantiate_nb(mk_dlg(tmp_path, [bad])) assert any(bad.id in note for note in error.value.__notes__) + + +def test_nested_formdata_merge(tmp_path): + from aidialog.dialog import Message, snote, sraw + from mdhtml.fill import instantiate_nb + fm = ("---\nformdata:\n company:\n name: ''\n signatory:\n name: ''\n title: CEO\n" + " signature: '`{{signature, r1}}`'\n extra:\n note: keep\n drop: unused\n---\n") + body = "{{company.name}} / {{company.signatory.name}} ({{company.signatory.title}}) {{company.signature}}{{#extra}} {{note}}{{/extra}}\n" + data = dict(company=dict(name="Acme", signatory=dict(name="Rachel")), extra=False, drop=None) + assert instantiate(fm + "\n" + body, data) == "Acme / Rachel (CEO) `{{signature, r1}}`\n" + p = mk_dlg(tmp_path, [Message(fm.strip(), msg_type=sraw), Message(body, msg_type=snote)]) + assert instantiate_nb(p, data).strip() == "Acme / Rachel (CEO) `{{signature, r1}}`" + assert data == dict(company=dict(name="Acme", signatory=dict(name="Rachel")), extra=False, drop=None)