Skip to content
Merged
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
19 changes: 19 additions & 0 deletions docs/cpa-config-schema.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
# `cpa.config.json` schema

Mirrors `cna.config.json` from Create-Node-App with Python-oriented fields.

```json
{
"name": "fastapi-starter",
"customOptions": [
{
"key": "projectName",
"type": "string",
"message": "Project name",
"default": "my-app"
}
]
}
```

Parse errors raise `CPA_CONFIG_PARSE`.
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,10 @@
"merge_layers",
"load_layer",
"get_template_dir_path",
"CpaConfig",
"CpaCustomOption",
"load_cpa_config",
"assert_directory_is_empty",
"CPA_USER_AGENT",
"check_for_latest_version",
"check_python_version",
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
"""cpa.config.json schema and loaders."""

from __future__ import annotations

import json
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

from create_python_app_core.errors import (
ConfigParseError,
NonEmptyTargetDirectoryError,
)


@dataclass
class CpaCustomOption:
key: str
type: str = "string"
message: str = ""
default: Any = None


@dataclass
class CpaConfig:
name: str | None = None
custom_options: list[CpaCustomOption] = field(default_factory=list)
raw: dict[str, Any] = field(default_factory=dict)


def load_cpa_config(path: Path) -> CpaConfig:
if not path.is_file():
return CpaConfig()
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ConfigParseError(f"Invalid cpa.config.json: {exc}") from exc
if not isinstance(data, dict):
raise ConfigParseError("cpa.config.json must be a JSON object")
options: list[CpaCustomOption] = []
for item in data.get("customOptions") or data.get("custom_options") or []:
if not isinstance(item, dict) or "key" not in item:
raise ConfigParseError("custom option missing key")
options.append(
CpaCustomOption(
key=str(item["key"]),
type=str(item.get("type", "string")),
message=str(item.get("message", "")),
default=item.get("default"),
)
)
return CpaConfig(
name=data.get("name"),
custom_options=options,
raw=data,
)


def assert_directory_is_empty(path: Path, *, force: bool = False) -> None:
if force:
return
if path.exists() and any(path.iterdir()):
raise NonEmptyTargetDirectoryError(f"Target directory is not empty: {path}")
35 changes: 35 additions & 0 deletions packages/create-python-app-core/tests/test_config.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
import json
from pathlib import Path

import pytest
from create_python_app_core.config import assert_directory_is_empty, load_cpa_config
from create_python_app_core.errors import ConfigParseError, NonEmptyTargetDirectoryError


def test_load_config(tmp_path: Path) -> None:
path = tmp_path / "cpa.config.json"
path.write_text(
json.dumps(
{
"name": "demo",
"customOptions": [{"key": "projectName", "default": "x"}],
}
)
)
cfg = load_cpa_config(path)
assert cfg.name == "demo"
assert cfg.custom_options[0].key == "projectName"


def test_bad_json(tmp_path: Path) -> None:
path = tmp_path / "cpa.config.json"
path.write_text("{")
with pytest.raises(ConfigParseError):
load_cpa_config(path)


def test_non_empty(tmp_path: Path) -> None:
(tmp_path / "f").write_text("x")
with pytest.raises(NonEmptyTargetDirectoryError):
assert_directory_is_empty(tmp_path)
assert_directory_is_empty(tmp_path, force=True)