awexpress 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
awexpress/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """awexpress -- Aither World Expressions.
2
+
3
+ One expression pack (stickers, emoji, caption cards, sound clips, alt text, tags,
4
+ licence) compiled into a bundle for each app that has its own limits: Discord,
5
+ Telegram, Slack, and post-ready images for LinkedIn and X.
6
+ """
7
+ __version__ = "0.1.0"
awexpress/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from awexpress.cli import main
4
+
5
+ sys.exit(main())
awexpress/_doctor.py ADDED
@@ -0,0 +1,195 @@
1
+ """Stack-aware `doctor` for awexpress.
2
+
3
+ GENERATED BY gen_aw_doctor.py -- DO NOT EDIT.
4
+ Regenerate it with the generator named above; a hand-edit here is reverted by
5
+ the next run and fails the parity gate.
6
+
7
+ Why a doctor exists at all: the aw* bricks are designed to COMPOSE, so the
8
+ interesting failures live BETWEEN them. "awexpress is installed" is not the useful
9
+ fact -- "awexpress is installed and the thing it pairs with is not" is. This reports
10
+ the whole stack, not just itself.
11
+
12
+ stdlib only, on purpose: a diagnostic that cannot run because a dependency is
13
+ missing is worthless precisely when you need it.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import importlib.util
18
+ import os
19
+ import shutil
20
+ import sys
21
+
22
+ SELF = 'awexpress'
23
+ #: Frozen from the Aither World registry at generation time. A shipped
24
+ #: package cannot read the registry, and a doctor that guessed at the family
25
+ #: would go stale in silence. Regenerate to update.
26
+ FAMILY = ['awdecide', 'awdiscord']
27
+ FAMILY_ERROR = None
28
+ PAIRS_WITH = ['awdiscord']
29
+
30
+ #: This brick's OWN config, read out of its source at generation time.
31
+ #: ENV_REQUIRED is `os.environ["X"]` -- absent, that is a KeyError the moment
32
+ #: the line runs. ENV_OPTIONAL is `os.getenv("X")`, which returns None and lets
33
+ #: the caller cope. Only this brick's namespace is listed: reporting the
34
+ #: platform-wide vars it also touches would be noise, and a doctor that floods
35
+ #: gets ignored.
36
+ ENV_REQUIRED = []
37
+ ENV_OPTIONAL = ['AWEXPRESS_HOME']
38
+
39
+
40
+ def _installed(mod: str) -> "str | None":
41
+ """Version if importable, else None. Never raises -- a broken sibling must
42
+ not take the diagnostic down with it."""
43
+ try:
44
+ if importlib.util.find_spec(mod) is None:
45
+ return None
46
+ except (ImportError, ValueError):
47
+ return None
48
+ try:
49
+ from importlib.metadata import PackageNotFoundError, version
50
+ try:
51
+ return version(mod)
52
+ except PackageNotFoundError:
53
+ return "installed"
54
+ except Exception:
55
+ return "installed"
56
+
57
+
58
+ def report(out=None) -> int:
59
+ """Print the stack picture. 0 = this brick and its pairs are present."""
60
+ out = out or sys.stdout
61
+ print(f"{SELF} doctor", file=out)
62
+
63
+ mine = _installed(SELF)
64
+ print(f" self {SELF} {mine or 'NOT IMPORTABLE'}", file=out)
65
+ shim = shutil.which(SELF)
66
+ print(f" command {shim or 'not on PATH'}", file=out)
67
+ if FAMILY_ERROR:
68
+ # Never an empty stack: "0/0 installed" reads as a clean machine.
69
+ print(f"\nverdict: UNJUDGED -- {FAMILY_ERROR}", file=out)
70
+ return 2
71
+
72
+ # The stack. Siblings this brick pairs with are called out separately,
73
+ # because a missing pair is a REASON, while a missing unrelated brick is
74
+ # just a fact about your machine.
75
+ missing_pairs, present = [], []
76
+ for name in FAMILY:
77
+ v = _installed(name)
78
+ if v:
79
+ present.append(name)
80
+ elif name in PAIRS_WITH:
81
+ missing_pairs.append(name)
82
+ print(f" stack {len(present)}/{len(FAMILY)} aw* packages installed",
83
+ file=out)
84
+ if present:
85
+ print(f" {' '.join(sorted(present))}", file=out)
86
+
87
+ missing_req = [v for v in ENV_REQUIRED if not os.environ.get(v)]
88
+ if ENV_REQUIRED or ENV_OPTIONAL:
89
+ have = sum(1 for v in ENV_REQUIRED + ENV_OPTIONAL if os.environ.get(v))
90
+ total = len(ENV_REQUIRED) + len(ENV_OPTIONAL)
91
+ print(f" config {have}/{total} of this brick's own vars set", file=out)
92
+ if missing_req:
93
+ # Not a preference. os.environ[...] raises the moment it runs.
94
+ print(f" MISSING REQUIRED: {' '.join(missing_req)}", file=out)
95
+
96
+ local = _local_checks()
97
+ for line in local:
98
+ print(f" {line}", file=out)
99
+ problems, unjudged = _local_verdict()
100
+
101
+ if mine is None:
102
+ print(f"\nverdict: {SELF} itself is not importable. Reinstall it before "
103
+ f"anything else here means much.", file=out)
104
+ return 1
105
+ if missing_req:
106
+ print(f"\nverdict: {SELF} is missing required config "
107
+ f"({', '.join(missing_req)}). Those are read with os.environ[...], "
108
+ f"so the code path that needs them raises rather than degrades.",
109
+ file=out)
110
+ return 1
111
+ # A measured NO outranks a missing optional pair: awrise printed
112
+ # "nothing wakes run-due" and still exited 0 because the missing-pairs
113
+ # branch returned first (measured 2026-09-20).
114
+ if problems:
115
+ for p in problems:
116
+ print(f"\nverdict: {p}", file=out)
117
+ return 1
118
+ if unjudged:
119
+ for u in unjudged:
120
+ print(f"\nverdict: UNJUDGED -- could not judge: {u}", file=out)
121
+ return 2
122
+ if missing_pairs:
123
+ print(f"\nverdict: {SELF} works, but pairs with "
124
+ f"{', '.join(sorted(missing_pairs))} which "
125
+ f"{'is' if len(missing_pairs) == 1 else 'are'} not installed. "
126
+ f"That is a capability you are missing, not an error.", file=out)
127
+ return 0
128
+ print(f"\nverdict: {SELF} and everything it pairs with are present.", file=out)
129
+ return 0
130
+
131
+
132
+ def _local_verdict() -> tuple:
133
+ """The brick's OWN verdict, folded into the exit code.
134
+
135
+ Without this the local lines are DECORATION. Measured 2026-09-20: awrise
136
+ printed "hostclock NOT INSTALLED -- nothing wakes run-due" and "last tick
137
+ never", then exited 0 -- teaching an operator that a doctor exit code
138
+ carries no information. A brick opts in with `_doctor_local_verdict()`
139
+ returning (problems, unjudged); a brick without one is unaffected.
140
+ """
141
+ try:
142
+ mod = importlib.import_module(f"{SELF}.doctor_local")
143
+ problems, unjudged = mod._doctor_local_verdict()
144
+ except Exception: # noqa: BLE001
145
+ return [], []
146
+ return list(problems or []), list(unjudged or [])
147
+
148
+
149
+ def _local_checks() -> "list[str]":
150
+ """Per-brick checks, if this package defines them.
151
+
152
+ Kept as a HOOK rather than generated guesses: the generator knows the family
153
+ from the registry, but it does not know what awexpress needs at runtime, and a
154
+ doctor that invented config requirements would be confidently wrong. A
155
+ package supplies `_doctor_local()` returning display lines; absent, the
156
+ stack picture above still stands on its own.
157
+ """
158
+ try:
159
+ mod = importlib.import_module(f"{SELF}.doctor_local")
160
+ except Exception:
161
+ return []
162
+ try:
163
+ return list(mod._doctor_local())
164
+ except Exception as exc: # noqa: BLE001
165
+ return [f"local checks raised {type(exc).__name__}: {exc}"]
166
+
167
+
168
+ def main(argv: "list[str] | None" = None) -> int:
169
+ # --self-test delegates to a SIBLING module when one exists.
170
+ #
171
+ # This file is generated and a fresh run replaces it, so a self-test
172
+ # written HERE is deleted by the next regeneration. awdelphi learned that
173
+ # the expensive way: 125 lines exercising four real failure paths --
174
+ # convergence, roster anonymization, resume, gateway-down -- lived in this
175
+ # file and were destroyed by a routine regeneration, silently, leaving a
176
+ # --self-test flag that reported PASS while asserting nothing.
177
+ #
178
+ # So the seam is a separate module the generator never writes. A package
179
+ # with real machinery to prove puts it in _selftest.py; everything else
180
+ # keeps the honest answer below rather than a self-test that only ever
181
+ # passes.
182
+ argv = list(argv if argv is not None else __import__("sys").argv[1:])
183
+ if "--self-test" in argv:
184
+ try:
185
+ from . import _selftest as _st
186
+ except Exception:
187
+ print("no _selftest module: this doctor reports the stack, and has",
188
+ "no machinery of its own to prove")
189
+ return 0
190
+ return int(_st.run())
191
+ return report()
192
+
193
+
194
+ if __name__ == "__main__":
195
+ raise SystemExit(main())
awexpress/cli.py ADDED
@@ -0,0 +1,212 @@
1
+ """awexpress -- Aither World Expressions.
2
+
3
+ awexpress validate <pack>
4
+ awexpress build <pack> --target discord|telegram|slack|post|all [--out DIR]
5
+ awexpress import <discord-asset-dir> [--id ID] [--name NAME]
6
+ awexpress install <pack-dir | https://git-url[#subdir]>
7
+ awexpress pick <query> [--target x|linkedin|discord|telegram|slack] [--alt] [--print]
8
+ awexpress list [--target T]
9
+ awexpress targets
10
+ awexpress --self-test
11
+
12
+ Exit codes: 0 done, 1 a file is over its limit / nothing matched / invalid pack,
13
+ 2 could not judge (missing tool, unreadable input).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ from pathlib import Path
24
+
25
+ from . import __version__, compilers, picker
26
+ from .importer import import_dir
27
+ from .manifest import PackError, load
28
+ from .targets import table
29
+
30
+
31
+ def _out(pack_root: Path, out: str | None) -> Path:
32
+ return Path(out).expanduser().resolve() if out else pack_root / "dist"
33
+
34
+
35
+ def cmd_validate(a) -> int:
36
+ pack = load(a.pack)
37
+ kinds: dict[str, int] = {}
38
+ for i in pack.items:
39
+ kinds[i.kind] = kinds.get(i.kind, 0) + 1
40
+ print(f"{pack.id} {pack.version}: {len(pack.items)} items "
41
+ + ", ".join(f"{n} {k}" for k, n in sorted(kinds.items()))
42
+ + f"; {sum(1 for i in pack.items if not i.public)} private")
43
+ return 0
44
+
45
+
46
+ def cmd_build(a) -> int:
47
+ pack = load(a.pack)
48
+ out = _out(pack.root, a.out)
49
+ report = compilers.build(pack, a.target, out, include_private=a.include_private)
50
+ picker.record(pack.id, pack.root, out)
51
+ by: dict[str, list[int]] = {}
52
+ for r in report["rows"]:
53
+ t = by.setdefault(r["target"], [0, 0, 0])
54
+ if r["ok"] is True:
55
+ t[0] += 1
56
+ elif r["ok"] is False:
57
+ t[1] += 1
58
+ elif r["reason"].startswith("not judged"):
59
+ t[2] += 1
60
+ for target, (ok, over, unj) in by.items():
61
+ print(f"{target:9} {ok:4} fit {over:3} over {unj:3} not judged")
62
+ for r in report["rows"]:
63
+ if r["ok"] is False:
64
+ print(f" OVER {r['target']}/{r['kind']}/{r['item']}: {r['reason']}")
65
+ print(f"report: {out / 'report.json'}")
66
+ if report["over"]:
67
+ return 1
68
+ return 2 if report["unjudged"] else 0
69
+
70
+
71
+ def cmd_import(a) -> int:
72
+ path = import_dir(Path(a.src).expanduser(), pack_id=a.id, name=a.name, license=a.license,
73
+ attribution=a.attribution, force=a.force)
74
+ pack = load(path)
75
+ print(f"wrote {path}: {len(pack.items)} items")
76
+ return 0
77
+
78
+
79
+ def cmd_install(a) -> int:
80
+ dest_root = picker.home() / "packs"
81
+ with tempfile.TemporaryDirectory(prefix="awexpress-install-") as tmp:
82
+ src = a.src
83
+ if src.startswith(("https://", "git@")):
84
+ url, _, sub = src.partition("#")
85
+ clone = Path(tmp) / "clone"
86
+ r = subprocess.run(["git", "clone", "--depth", "1", "-q", url, str(clone)],
87
+ capture_output=True, timeout=180)
88
+ if r.returncode != 0:
89
+ print(f"could not clone {url}", file=sys.stderr)
90
+ return 2
91
+ path = clone / sub if sub else clone
92
+ else:
93
+ path = Path(src).expanduser()
94
+ pack = load(path)
95
+ dest = dest_root / pack.id
96
+ if dest.exists():
97
+ if not a.force:
98
+ print(f"{pack.id} already installed at {dest} (use --force)", file=sys.stderr)
99
+ return 1
100
+ shutil.rmtree(dest)
101
+ shutil.copytree(path, dest, ignore=shutil.ignore_patterns(".git", "dist"))
102
+ pack = load(dest)
103
+ report = compilers.build(pack, ["all"], dest / "dist")
104
+ picker.record(pack.id, dest, dest / "dist")
105
+ print(f"installed {pack.id} {pack.version} -> {dest} ({report['files']} files, "
106
+ f"{report['over']} over)")
107
+ if report["over"]:
108
+ return 1
109
+ return 2 if report["unjudged"] else 0
110
+
111
+
112
+ def cmd_pick(a) -> int:
113
+ hits = picker.search(" ".join(a.query), target=a.target, limit=a.limit)
114
+ if not hits:
115
+ print(f"nothing matches {' '.join(a.query)!r} for {a.target}", file=sys.stderr)
116
+ return 1
117
+ if a.print or a.limit > 1 and a.all:
118
+ print(json.dumps(hits, indent=2, ensure_ascii=False))
119
+ return 0
120
+ best = hits[0]
121
+ how = picker.copy(text=best["alt"]) if a.alt else picker.copy(Path(best["file"]))
122
+ print(f"copied {how}: {best['file']}")
123
+ if best["alt"] and not a.alt:
124
+ print(f"alt: {best['alt']}")
125
+ return 0
126
+
127
+
128
+ def cmd_list(a) -> int:
129
+ for e in picker.search("", target=a.target, limit=10_000):
130
+ print(f"{e['pack']:20} {e['item']:36} {e['file']}")
131
+ return 0
132
+
133
+
134
+ def main(argv: list[str] | None = None) -> int:
135
+ # GENERATED doctor intercept (gen_aw_doctor.py) -- do not edit
136
+ _dv = locals().get("argv")
137
+ if (_dv if _dv is not None else __import__("sys").argv[1:])[:1] == ["doctor"]:
138
+ from ._doctor import report
139
+ return report()
140
+ # GENERATED repo-state intercept (gen_aw_doctor.py) -- do not edit
141
+ try:
142
+ from awgit import state as _aw_state
143
+ except Exception:
144
+ _aw_state = None
145
+ if _aw_state is not None:
146
+ _sv = locals().get("argv")
147
+ if _aw_state.cli_banner(_sv if _sv is not None else __import__("sys").argv[1:]):
148
+ return 0
149
+ p = argparse.ArgumentParser(prog="awexpress", description=__doc__.split("\n")[0])
150
+ p.add_argument("--version", action="version", version=f"awexpress {__version__}")
151
+ p.add_argument("--self-test", action="store_true", help="prove the compilers and judge")
152
+ sub = p.add_subparsers(dest="cmd")
153
+ v = sub.add_parser("validate")
154
+ v.add_argument("pack")
155
+ b = sub.add_parser("build")
156
+ b.add_argument("pack")
157
+ b.add_argument("--target", action="append", default=None,
158
+ help="discord, telegram, slack, post (linkedin + x) or all; repeatable")
159
+ b.add_argument("--out")
160
+ b.add_argument("--include-private", action="store_true")
161
+ i = sub.add_parser("import")
162
+ i.add_argument("src")
163
+ i.add_argument("--id", default="")
164
+ i.add_argument("--name", default="")
165
+ i.add_argument("--license", default="")
166
+ i.add_argument("--attribution", default="")
167
+ i.add_argument("--force", action="store_true")
168
+ n = sub.add_parser("install")
169
+ n.add_argument("src")
170
+ n.add_argument("--force", action="store_true")
171
+ k = sub.add_parser("pick")
172
+ k.add_argument("query", nargs="+")
173
+ k.add_argument("--target", default="x")
174
+ k.add_argument("--alt", action="store_true", help="copy the alt text, not the file")
175
+ k.add_argument("--print", action="store_true", help="print matches, copy nothing")
176
+ k.add_argument("--all", action="store_true")
177
+ k.add_argument("--limit", type=int, default=1)
178
+ ls = sub.add_parser("list")
179
+ ls.add_argument("--target", default="x")
180
+ sub.add_parser("targets")
181
+ a = p.parse_args(argv)
182
+ for stream in (sys.stdout, sys.stderr):
183
+ if hasattr(stream, "reconfigure"):
184
+ stream.reconfigure(encoding="utf-8", errors="replace")
185
+ if a.self_test:
186
+ from .selftest import run
187
+ code, lines = run()
188
+ print("\n".join(lines))
189
+ print("self-test " + ("PASSED" if code == 0 else "FAILED"))
190
+ return code
191
+ if a.cmd == "targets":
192
+ print(json.dumps(table(), indent=2))
193
+ return 0
194
+ if a.cmd == "build" and not a.target:
195
+ a.target = ["all"]
196
+ handlers = {"validate": cmd_validate, "build": cmd_build, "import": cmd_import,
197
+ "install": cmd_install, "pick": cmd_pick, "list": cmd_list}
198
+ if a.cmd not in handlers:
199
+ p.print_help()
200
+ return 2
201
+ try:
202
+ return handlers[a.cmd](a)
203
+ except PackError as exc:
204
+ print(f"invalid pack: {exc}", file=sys.stderr)
205
+ return 1
206
+ except (OSError, RuntimeError, ValueError) as exc:
207
+ print(f"could not judge: {type(exc).__name__}: {exc}", file=sys.stderr)
208
+ return 2
209
+
210
+
211
+ if __name__ == "__main__":
212
+ sys.exit(main())