Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1598-create-template-kb-fields.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **`pyrite create -k <kb> -t <type> --template` now shows the fields a create of that type in that KB would write (#1598).** The skeleton used to come from the core types only, so a `backlog_item` skeleton had none of the fields a real create writes, and a type the KB does not declare was not refused. Without `-k`, the skeleton is unchanged.
45 changes: 34 additions & 11 deletions pyrite/cli/entry_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,17 +354,40 @@ def create_entry(
"title": title or "Your Title Here",
"tags": [],
}
# Add type-specific fields as empty values
type_info = CORE_TYPES.get(entry_type, {})
for field_name, field_type in type_info.get("fields", {}).items():
if field_name in ("tags", "links"):
continue
if "list" in field_type:
fm[field_name] = []
elif field_type == "int":
fm[field_name] = 0
else:
fm[field_name] = ""
if kb_name is not None:
# A KB's skeleton shows the fields a create of this type in
# this KB would write, read from the same place (#1598).
# Opening the context refuses a -k that names no KB the way
# a create does (KB_NOT_FOUND).
with cli_context(kbs=(kb_name,)) as (config, db, svc):
kb_config = config.get_kb(kb_name)
assert kb_config is not None # cli_context resolved -k above
try:
fm.update(
svc.create_template_fields(
entry_type, kb_config, allow_undeclared=allow_undeclared
)
)
except ValidationError as e:
raise _with_cli_hint(e) from None
# The preview's own base fields, not the built entry's.
fm["id"] = ""
fm["type"] = entry_type
fm["title"] = title or "Your Title Here"
fm["tags"] = []
fm["importance"] = importance
else:
# Add type-specific fields as empty values
type_info = CORE_TYPES.get(entry_type, {})
for field_name, field_type in type_info.get("fields", {}).items():
if field_name in ("tags", "links"):
continue
if "list" in field_type:
fm[field_name] = []
elif field_type == "int":
fm[field_name] = 0
else:
fm[field_name] = ""
skeleton = f"---\n{dump_yaml(fm)}\n---\n\nYour content here."

def raw(console: Console, data: dict) -> None:
Expand Down
24 changes: 24 additions & 0 deletions pyrite/services/kb_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -1720,6 +1720,30 @@ def _with_declared_fields(
attributes[field] = None
return {**fields, **added}, attributes

def create_template_fields(
self, entry_type: str, kb_config: KBConfig, *, allow_undeclared: bool = False
) -> dict[str, Any]:
"""The fields a create of this type in this KB would write, with their values (#1598).

Read-only: the entry is built the way :meth:`_prepare` builds one
(:meth:`_with_declared_fields` + :func:`build_entry`), but nothing is
checked against the filesystem and nothing is written, so a preview
never refuses an id that already exists and never runs a validator
on placeholder values. The base fields the skeleton sets itself
(``id``, ``title``, ``type``, ``tags``, ``importance``) are left
out; the caller adds those. An undeclared type is refused exactly
as a create refuses it, unless `allow_undeclared` says otherwise.
"""
if not allow_undeclared:
self._refuse_undeclared_type(entry_type, kb_config.name, kb_config)
fields, attributes = self._with_declared_fields(entry_type, kb_config, {})
entry = build_entry(entry_type, entry_id="", title="Your Title Here", body="", **fields)
entry._create_fields = attributes
meta = entry.declared_frontmatter()
for key in ("id", "title", "type", "tags", "importance"):
meta.pop(key, None)
return meta

def _prepare_and_save(
self,
kb_name: str,
Expand Down
231 changes: 231 additions & 0 deletions tests/test_create_template_kb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
"""Tests for `create --template` with a KB (#1598).

The skeleton for a type in a KB shows the fields a create of that type in
that KB would write, read from the same place a create reads them; without
`-k` it stays the core-types skeleton it always was.
"""

import contextlib
import json
import tempfile
from pathlib import Path
from unittest.mock import patch

import pytest
import typer
from typer.testing import CliRunner

from pyrite.cli import app
from pyrite.cli.init_command import init_kb
from pyrite.config import PyriteConfig, Settings
from pyrite.utils.yaml import load_yaml

runner = CliRunner()

init_app = typer.Typer()
init_app.command("init")(init_kb)


@pytest.fixture
def software_kb():
"""A KB made by `pyrite init -t software`, with a config that knows it."""
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir = Path(tmpdir)
config = PyriteConfig(knowledge_bases=[], settings=Settings(index_path=tmpdir / "index.db"))
kb_path = tmpdir / "proj"
with (
patch("pyrite.config.load_config", return_value=config),
patch("pyrite.config.save_config"),
):
result = runner.invoke(
init_app,
[
"--template",
"software",
"--path",
str(kb_path),
"--name",
"proj",
"--no-examples",
],
)
assert result.exit_code == 0, result.output
yield {"config": config, "tmpdir": tmpdir, "kb_path": kb_path}


@contextlib.contextmanager
def _patch_config(config):
"""Patch load_config to return the test config in all CLI modules."""
with patch("pyrite.cli.load_config", return_value=config):
with patch("pyrite.cli.context.load_config", return_value=config):
yield


def _template_frontmatter(result):
"""The skeleton's frontmatter as a dict, from a --format json run."""
assert result.exit_code == 0, result.output
data = json.loads(result.output)
text = data["template"]
assert text.startswith("---\n")
assert text.endswith("\n---\n\nYour content here.")
return load_yaml(text[len("---\n") : -len("\n---\n\nYour content here.")])


def _read_frontmatter(path):
"""A written file's frontmatter as a dict."""
text = path.read_text(encoding="utf-8")
assert text.startswith("---\n")
end = text.index("\n---", len("---\n"))
return load_yaml(text[len("---\n") : end])


@pytest.mark.cli
class TestCreateTemplateWithKb:
def test_template_backlog_item_matches_real_create(self, software_kb):
"""The skeleton has the keys and defaults a create writes."""
kb_path = software_kb["kb_path"]
with _patch_config(software_kb["config"]):
created = runner.invoke(
app,
[
"create",
"-k",
"proj",
"-t",
"backlog_item",
"--title",
"x",
"--format",
"json",
],
)
assert created.exit_code == 0, created.output
written = _read_frontmatter(kb_path / "backlog" / "x.md")

result = runner.invoke(
app,
["create", "-k", "proj", "-t", "backlog_item", "--template", "--format", "json"],
)
skeleton = _template_frontmatter(result)

# id and title are the preview's placeholders; tags is the
# skeleton's own empty list (the create wrote no tags).
assert skeleton["id"] == ""
assert skeleton["title"] == "Your Title Here"
assert skeleton["tags"] == []
template_fields = {k: v for k, v in skeleton.items() if k not in ("id", "title", "tags")}
written_fields = {k: v for k, v in written.items() if k not in ("id", "title")}
assert template_fields == written_fields
assert template_fields == {
"type": "backlog_item",
"importance": 5,
"kind": "",
"status": "proposed",
"priority": "medium",
"rank": 0,
"effort": "",
"assignee": "",
}

def test_template_kb_yaml_field_with_declared_default(self, software_kb):
"""A field a KB adds to a core type in kb.yaml appears, at its default."""
kb_path = software_kb["kb_path"]
kb_yaml = kb_path / "kb.yaml"
text = kb_yaml.read_text(encoding="utf-8")
assert "\n note:\n" not in text
kb_yaml.write_text(
text.replace(
"\npolicies:",
"\n note:\n"
" description: Plain note\n"
" required:\n"
" - title\n"
" optional:\n"
" - severity\n"
" fields:\n"
" severity:\n"
" type: select\n"
" options:\n"
" - low\n"
" - high\n"
" default: low\n"
"policies:",
1,
),
encoding="utf-8",
)
software_kb["config"].get_kb("proj").invalidate_schema_cache()
with _patch_config(software_kb["config"]):
result = runner.invoke(
app,
["create", "-k", "proj", "-t", "note", "--template", "--format", "json"],
)
skeleton = _template_frontmatter(result)
assert skeleton["severity"] == "low"
assert skeleton["importance"] == 5

def test_template_undeclared_type_refuses_like_create(self, software_kb):
"""An undeclared type is refused with the create's error."""
with _patch_config(software_kb["config"]):
template = runner.invoke(
app,
["create", "-k", "proj", "-t", "nosuch", "--template", "--format", "json"],
)
assert template.exit_code == 1
template_error = json.loads(template.output)

created = runner.invoke(
app,
["create", "-k", "proj", "-t", "nosuch", "--title", "y", "--format", "json"],
)
assert created.exit_code == 1
created_error = json.loads(created.output)
assert template_error["error_code"] == "UNDECLARED_TYPE"
assert template_error == created_error

def test_template_undeclared_type_allowed_with_flag(self, software_kb):
"""--allow-undeclared lets the skeleton through, as it lets a create through."""
with _patch_config(software_kb["config"]):
result = runner.invoke(
app,
[
"create",
"-k",
"proj",
"-t",
"nosuch",
"--template",
"--allow-undeclared",
"--format",
"json",
],
)
skeleton = _template_frontmatter(result)
assert skeleton["type"] == "nosuch"
assert skeleton["importance"] == 5

def test_template_unknown_kb_refuses(self, software_kb):
"""A -k that names no KB is refused, as a create is."""
with _patch_config(software_kb["config"]):
result = runner.invoke(
app,
["create", "-k", "nope", "-t", "note", "--template", "--format", "json"],
)
assert result.exit_code == 1
assert json.loads(result.output)["error_code"] == "KB_NOT_FOUND"

def test_template_without_kb_is_unchanged(self, software_kb):
"""Without -k, the skeleton is today's core-types one."""
with _patch_config(software_kb["config"]):
result = runner.invoke(
app, ["create", "-t", "person", "--template", "--format", "json"]
)
skeleton = _template_frontmatter(result)
assert skeleton == {
"id": "",
"type": "person",
"title": "Your Title Here",
"tags": [],
"role": "",
"affiliations": [],
}
Loading