Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
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
7It creates `packages/app-tickets/` (or `--dir`/app-tickets) holding a manifest,
8one collection schema (`tickets`: a required title, notes, an owner), the
9permission rules that let each signed-in person manage only their own rows, a
10seeded list page at `/tickets` (a `views` row and a `site_routes` row) and a
11menu entry. It installs as it stands and passes the checks in
12tests/test_dron_schema.py; then you change it. The workflow it starts is in
13docs/package-authoring.md ("Start From A Scaffold").
14
15The collection name is the package id without a leading `app-`, with dashes
16turned into underscores. `--collection NAME` overrides it. This refuses to
17write over a directory that exists.
18
19Standard library only; it writes nothing outside the new directory.
20"""
21
22from __future__ import annotations
23
24import argparse
25import json
26import re
27import sys
28from pathlib import Path
29
30REPO = Path(__file__).resolve().parent.parent
31ID_PATTERN = re.compile(r"^[a-z][a-z0-9]*(-[a-z0-9]+)*$")
32NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*$")
33
34
35class ScaffoldError(Exception):
36 """A problem with what was asked for, said in a sentence."""
37
38
39def 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
44def _dump(value: object) -> str:
45 return json.dumps(value, indent=2) + "\n"
46
47
48def 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
107def 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
127def 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
148if __name__ == "__main__":
149 sys.exit(main())