askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
new_package.py · 6.3 KB · 149 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """Write a minimal working package: the first step of authoring one. |
| 3 | |
| 4 | python scripts/new_package.py app-tickets |
| 5 | python scripts/new_package.py app-tickets --dir /tmp/my-packages |
| 6 | |
| 7 | It creates `packages/app-tickets/` (or `--dir`/app-tickets) holding a manifest, |
| 8 | one collection schema (`tickets`: a required title, notes, an owner), the |
| 9 | permission rules that let each signed-in person manage only their own rows, a |
| 10 | seeded list page at `/tickets` (a `views` row and a `site_routes` row) and a |
| 11 | menu entry. It installs as it stands and passes the checks in |
| 12 | tests/test_dron_schema.py; then you change it. The workflow it starts is in |
| 13 | docs/package-authoring.md ("Start From A Scaffold"). |
| 14 | |
| 15 | The collection name is the package id without a leading `app-`, with dashes |
| 16 | turned into underscores. `--collection NAME` overrides it. This refuses to |
| 17 | write over a directory that exists. |
| 18 | |
| 19 | Standard library only; it writes nothing outside the new directory. |
| 20 | """ |
| 21 | |
| 22 | from __future__ import annotations |
| 23 | |
| 24 | import argparse |
| 25 | import json |
| 26 | import re |
| 27 | import sys |
| 28 | from pathlib import Path |
| 29 | |
| 30 | REPO = Path(__file__).resolve().parent.parent |
| 31 | ID_PATTERN = re.compile(r"^[a-z][a-z0-9]*(-[a-z0-9]+)*$") |
| 32 | NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*$") |
| 33 | |
| 34 | |
| 35 | class ScaffoldError(Exception): |
| 36 | """A problem with what was asked for, said in a sentence.""" |
| 37 | |
| 38 | |
| 39 | def collection_for(package_id: str) -> str: |
| 40 | name = package_id[4:] if package_id.startswith("app-") else package_id |
| 41 | return name.replace("-", "_") |
| 42 | |
| 43 | |
| 44 | def _dump(value: object) -> str: |
| 45 | return json.dumps(value, indent=2) + "\n" |
| 46 | |
| 47 | |
| 48 | def files_for(package_id: str, collection: str) -> dict[str, str]: |
| 49 | """Relative path -> file text, for the whole package.""" |
| 50 | title = collection.replace("_", " ").title() |
| 51 | manifest = { |
| 52 | "dron": "0.2", |
| 53 | "id": package_id, |
| 54 | "name": title, |
| 55 | "version": "0.1.0", |
| 56 | "description": f"{title}, each owned by one person", |
| 57 | "compatibility": {"dbbasic_object_server": ">=0.1.0"}, |
| 58 | "dependencies": ["app-nav", "app-views"], |
| 59 | "objects": [], |
| 60 | "schemas": [{"collection": collection, "path": f"schemas/{collection}.json"}], |
| 61 | "permissions": [{"path": "permissions/rules.json"}], |
| 62 | "seed": [ |
| 63 | {"collection": "views", "path": "seed/views.tsv"}, |
| 64 | {"collection": "site_routes", "path": "seed/site_routes.tsv"}, |
| 65 | ], |
| 66 | "migrations": [], |
| 67 | "nav": [{"id": collection, "label": title, "path": f"/{collection}", "group": "Work"}], |
| 68 | } |
| 69 | schema = { |
| 70 | "name": collection, |
| 71 | "title": title, |
| 72 | "version": 1, |
| 73 | "fields": [ |
| 74 | {"name": "id"}, |
| 75 | {"name": "title", "type": "text", "required": True}, |
| 76 | {"name": "notes", "type": "textarea"}, |
| 77 | {"name": "owner_id", "type": "text"}, |
| 78 | ], |
| 79 | "forms": {"default": {"fields": ["title", "notes"]}}, |
| 80 | "views": {"list_fields": ["title"]}, |
| 81 | "search": {"fields": ["title", "notes"]}, |
| 82 | } |
| 83 | rules = { |
| 84 | "rules": [ |
| 85 | {"effect": "allow", "principal": "registered", |
| 86 | "actions": ["create", "read", "update", "delete"], |
| 87 | "collection": collection, "row_filter": {"owner_id": "$user_id"}, |
| 88 | "reason": "people manage their own rows"}, |
| 89 | ] |
| 90 | } |
| 91 | blocks = json.dumps([{"kind": "list", "collection": collection, "search": True, |
| 92 | "sort": True, "add": True, "owner_scoped": True, |
| 93 | "title_field": "title", "subtitle_field": "notes"}]) |
| 94 | views = ("id\ttitle\troute\tlayout\tblocks\towner_id\tis_public\tpinned\tcreated_at\n" |
| 95 | f"view_{collection}\t{title}\t/{collection}\tsingle\t{blocks}\t\ttrue\tfalse\t2026-01-01T00:00:00\n") |
| 96 | routes = ("id\tpattern\tobject_id\tpriority\n" |
| 97 | f"route_{collection}\t/{collection}\tsite_view_render\t20\n") |
| 98 | return { |
| 99 | "dbbasic-package.json": _dump(manifest), |
| 100 | f"schemas/{collection}.json": _dump(schema), |
| 101 | "permissions/rules.json": _dump(rules), |
| 102 | "seed/views.tsv": views, |
| 103 | "seed/site_routes.tsv": routes, |
| 104 | } |
| 105 | |
| 106 | |
| 107 | def create_package(package_id: str, *, packages_dir: Path | str | None = None, |
| 108 | collection: str | None = None) -> Path: |
| 109 | """Write the package and return its directory.""" |
| 110 | if not ID_PATTERN.match(package_id): |
| 111 | raise ScaffoldError( |
| 112 | f"{package_id!r} is not a package id: lower-case words joined by dashes, such as app-tickets") |
| 113 | collection = collection or collection_for(package_id) |
| 114 | if not NAME_PATTERN.match(collection): |
| 115 | raise ScaffoldError(f"{collection!r} is not a collection name: lower-case letters, digits and underscores") |
| 116 | root = Path(packages_dir) if packages_dir else REPO / "packages" |
| 117 | target = root / package_id |
| 118 | if target.exists(): |
| 119 | raise ScaffoldError(f"{target} already exists; pick another id or remove it") |
| 120 | for relative, text in files_for(package_id, collection).items(): |
| 121 | path = target / relative |
| 122 | path.parent.mkdir(parents=True, exist_ok=True) |
| 123 | path.write_text(text, encoding="utf-8") |
| 124 | return target |
| 125 | |
| 126 | |
| 127 | def main(argv: list[str] | None = None) -> int: |
| 128 | parser = argparse.ArgumentParser(description="Write a minimal working package. See the top of this file.") |
| 129 | parser.add_argument("package_id", help="the new package's id, such as app-tickets") |
| 130 | parser.add_argument("--dir", type=Path, default=None, help="the packages directory (default: packages/ here)") |
| 131 | parser.add_argument("--collection", default=None, help="the collection's name (default: from the id)") |
| 132 | args = parser.parse_args(argv) |
| 133 | try: |
| 134 | target = create_package(args.package_id, packages_dir=args.dir, collection=args.collection) |
| 135 | except ScaffoldError as exc: |
| 136 | print(f"error: {exc}", file=sys.stderr) |
| 137 | return 2 |
| 138 | collection = args.collection or collection_for(args.package_id) |
| 139 | print(f"wrote {target}") |
| 140 | print("try it (from this repository, with the packages directory it was written to):") |
| 141 | print(f" python scripts/try_package.py {args.package_id} --user ann --brief \\") |
| 142 | print(f" --call 'ann POST /collections/{collection}/records " |
| 143 | f"{{\"title\": \"first\", \"owner_id\": \"ann\"}}' \\") |
| 144 | print(f" --call 'ann GET /collections/{collection}/records' --rows 'ann /{collection}'") |
| 145 | return 0 |
| 146 | |
| 147 | |
| 148 | if __name__ == "__main__": |
| 149 | sys.exit(main()) |