1panel-toolkit 0.3.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.
Files changed (47) hide show
  1. 1panel_toolkit-0.3.0.dist-info/METADATA +407 -0
  2. 1panel_toolkit-0.3.0.dist-info/RECORD +47 -0
  3. 1panel_toolkit-0.3.0.dist-info/WHEEL +4 -0
  4. 1panel_toolkit-0.3.0.dist-info/entry_points.txt +2 -0
  5. 1panel_toolkit-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. p1toolkit/__init__.py +3 -0
  7. p1toolkit/checks/__init__.py +21 -0
  8. p1toolkit/checks/compose.py +188 -0
  9. p1toolkit/checks/forms.py +129 -0
  10. p1toolkit/checks/hygiene.py +73 -0
  11. p1toolkit/checks/i18n.py +140 -0
  12. p1toolkit/checks/lessons.py +111 -0
  13. p1toolkit/checks/structure.py +140 -0
  14. p1toolkit/checks/substance.py +55 -0
  15. p1toolkit/cli.py +890 -0
  16. p1toolkit/config.py +114 -0
  17. p1toolkit/dependencies.py +218 -0
  18. p1toolkit/deploy.py +302 -0
  19. p1toolkit/depth.py +414 -0
  20. p1toolkit/errors.py +18 -0
  21. p1toolkit/evidence.py +523 -0
  22. p1toolkit/fix.py +394 -0
  23. p1toolkit/gen.py +728 -0
  24. p1toolkit/lifecycle.py +143 -0
  25. p1toolkit/loader.py +110 -0
  26. p1toolkit/logo.py +174 -0
  27. p1toolkit/model.py +71 -0
  28. p1toolkit/net.py +81 -0
  29. p1toolkit/panel.py +154 -0
  30. p1toolkit/patterns/__init__.py +250 -0
  31. p1toolkit/patterns/catalog.py +271 -0
  32. p1toolkit/patterns/data/patterns.json +724 -0
  33. p1toolkit/patterns/extract.py +402 -0
  34. p1toolkit/remote.py +554 -0
  35. p1toolkit/report.py +96 -0
  36. p1toolkit/resolve/__init__.py +554 -0
  37. p1toolkit/resolve/analyze.py +329 -0
  38. p1toolkit/resolve/sources.py +306 -0
  39. p1toolkit/rules/__init__.py +99 -0
  40. p1toolkit/rules/data/decisions.yaml +132 -0
  41. p1toolkit/rules/data/dependencies.yaml +113 -0
  42. p1toolkit/rules/data/envkeys.yaml +19 -0
  43. p1toolkit/rules/data/form-design.yaml +59 -0
  44. p1toolkit/rules/data/i18n.yaml +354 -0
  45. p1toolkit/rules/data/lessons.yaml +84 -0
  46. p1toolkit/rules/data/store.yaml +171 -0
  47. p1toolkit/selftest.py +211 -0
p1toolkit/gen.py ADDED
@@ -0,0 +1,728 @@
1
+ """Generate a 1Panel app package from a spec.
2
+
3
+ The spec is the reviewable artifact; everything else here is derived. Two
4
+ disciplines make the output usable rather than merely valid:
5
+
6
+ * **The form is a decision list, not a config dump.** An upstream variable is
7
+ exposed only when the user must decide it (a port, a public URL) or must
8
+ supply it (a secret). Everything else gets a working default in the compose
9
+ file and is documented in the README instead.
10
+ * **Generated is not the same as hand-written.** Output follows the shapes real
11
+ store apps use, so it survives `p1 check` and `p1 depth`.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import yaml
23
+
24
+ from . import dependencies as dependencies_module
25
+ from . import lifecycle
26
+ from . import rules
27
+ from .checks.forms import is_secret
28
+ from .errors import SpecError
29
+ from .evidence import Audit, audit as audit_spec
30
+
31
+ DEFAULT_PORT = 10000
32
+ DESCRIPTION_LANGUAGES = (
33
+ "en",
34
+ "zh",
35
+ "zh-Hant",
36
+ "ja",
37
+ "ko",
38
+ "ru",
39
+ "ms",
40
+ "pt-br",
41
+ "es-es",
42
+ "tr",
43
+ )
44
+
45
+
46
+ @dataclass
47
+ class GenResult:
48
+ root: Path
49
+ files: list[str] = field(default_factory=list)
50
+ warnings: list[str] = field(default_factory=list)
51
+ hidden_env: list[str] = field(default_factory=list)
52
+ exposed: list[str] = field(default_factory=list)
53
+ audit: Audit | None = None
54
+
55
+ def render(self) -> str:
56
+ lines = [f"生成于 {self.root}"]
57
+ for name in self.files:
58
+ lines.append(f" + {name}")
59
+ lines.append(f"表单字段 {len(self.exposed)} 个: {', '.join(self.exposed)}")
60
+ if self.hidden_env:
61
+ lines.append(
62
+ f"收进默认值 {len(self.hidden_env)} 个(不暴露给用户): "
63
+ + ", ".join(self.hidden_env)
64
+ )
65
+ if self.audit is not None:
66
+ lines.append("证据审计:")
67
+ lines.append(self.audit.render())
68
+ for note in self.warnings:
69
+ lines.append(f" ! {note}")
70
+ return "\n".join(lines)
71
+
72
+
73
+ def _dump(value: Any) -> str:
74
+ return yaml.safe_dump(value, allow_unicode=True, sort_keys=False, width=100)
75
+
76
+
77
+ def _slug(text: str) -> str:
78
+ return re.sub(r"[^a-z0-9-]+", "-", str(text).lower()).strip("-")
79
+
80
+
81
+ def product_of(spec: dict[str, Any]) -> str:
82
+ """The product name, as shown in the store list."""
83
+ return str(spec.get("name") or spec.get("title") or "")
84
+
85
+
86
+ def one_liner_of(spec: dict[str, Any]) -> str:
87
+ """The single sentence the store shows underneath the name."""
88
+ return str(
89
+ spec.get("shortDescZh")
90
+ or spec.get("description")
91
+ or spec.get("one_liner")
92
+ or product_of(spec)
93
+ )
94
+
95
+
96
+ # --------------------------------------------------------------------------
97
+ # labels
98
+ # --------------------------------------------------------------------------
99
+
100
+
101
+ def resolve_label(field: dict[str, Any], warnings: list[str]) -> dict[str, Any]:
102
+ """Fill a complete label map, reusing store translations where possible."""
103
+ dictionary = rules.i18n().get("label_dictionary") or {}
104
+ languages = rules.all_languages()
105
+ env_key = str(field.get("envKey") or "")
106
+
107
+ label = field.get("label")
108
+ if isinstance(label, dict) and len(label) >= 5:
109
+ merged = {lang: str(label.get(lang) or label.get("en") or "") for lang in languages}
110
+ return {
111
+ "label": merged,
112
+ "labelEn": str(field.get("labelEn") or label.get("en") or env_key),
113
+ "labelZh": str(field.get("labelZh") or label.get("zh") or env_key),
114
+ }
115
+
116
+ english = str(field.get("labelEn") or "")
117
+ chinese = str(field.get("labelZh") or "")
118
+ if english in dictionary:
119
+ merged = {lang: dictionary[english].get(lang, english) for lang in languages}
120
+ return {"label": merged, "labelEn": english, "labelZh": chinese or merged["zh"]}
121
+
122
+ if not english:
123
+ warnings.append(f"{env_key}: 没有 labelEn,用 envKey 占位;请补一个用户看得懂的标签")
124
+ english = env_key
125
+ if not chinese:
126
+ warnings.append(f"{env_key}: 没有 labelZh,暂时沿用英文;请补中文标签")
127
+ chinese = english
128
+ warnings.append(
129
+ f"{env_key}: 标签没有可复用的官方翻译,其余语言暂用英文;上线前建议人工确认"
130
+ )
131
+ merged = {lang: english for lang in languages}
132
+ merged["zh"] = chinese
133
+ return {"label": merged, "labelEn": english, "labelZh": chinese}
134
+
135
+
136
+ def build_description(spec: dict[str, Any], warnings: list[str]) -> dict[str, str]:
137
+ chinese = one_liner_of(spec)
138
+ english = str(spec.get("shortDescEn") or spec.get("descriptionEn") or "")
139
+ if not english:
140
+ warnings.append("没有 shortDescEn,其它语言的描述暂用中文;请补一个英文一句话简介")
141
+ english = chinese
142
+ description = {lang: english for lang in DESCRIPTION_LANGUAGES}
143
+ description["zh"] = chinese
144
+ description["zh-Hant"] = chinese
145
+ warnings.append(
146
+ "additionalProperties.description 的 zh-Hant / ja / ko / ru / ms / pt-br / es-es / tr "
147
+ "当前是英文或中文占位,提交前请确认翻译"
148
+ )
149
+ return description
150
+
151
+
152
+ # --------------------------------------------------------------------------
153
+ # form fields
154
+ # --------------------------------------------------------------------------
155
+
156
+
157
+ def _normalise_env(entry: Any) -> dict[str, Any]:
158
+ if isinstance(entry, dict):
159
+ return dict(entry)
160
+ return {"value": "" if entry is None else str(entry)}
161
+
162
+
163
+ def _inline_default(value: str) -> str | None:
164
+ """Prepare a value for ``${VAR:-...}``.
165
+
166
+ ``$`` must be doubled or Compose tries to expand it. A ``}`` would close the
167
+ expression early and there is no escape for it, so that case returns None and
168
+ the caller falls back to an empty default.
169
+ """
170
+ if "}" in value:
171
+ return None
172
+ return value.replace("$", "$$")
173
+
174
+
175
+ def _mount_targets(service: dict[str, Any]) -> list[str]:
176
+ if service.get("mount_targets"):
177
+ return list(service["mount_targets"])
178
+ if service.get("mount_target"):
179
+ return [str(service["mount_target"])]
180
+ return []
181
+
182
+
183
+ def _mount_pairs(service: dict[str, Any]) -> list[tuple[str, str]]:
184
+ """Resolve each container path to its own host path.
185
+
186
+ A service can mount a directory and a file from different places; pairing
187
+ every target with one shared host path silently corrupts the second mount.
188
+ """
189
+ mounts = service.get("mounts")
190
+ if isinstance(mounts, list) and mounts:
191
+ pairs = [
192
+ (str(item.get("host") or "./data"), str(item["target"]))
193
+ for item in mounts
194
+ if isinstance(item, dict) and item.get("target")
195
+ ]
196
+ if pairs:
197
+ return pairs
198
+ host = str(service.get("mount_host") or "./data")
199
+ return [(host, target) for target in _mount_targets(service)]
200
+
201
+
202
+ def build_fields(
203
+ spec: dict[str, Any], warnings: list[str]
204
+ ) -> tuple[list[dict], dict[str, list[str]], dict[str, list[str]]]:
205
+ """Decide what the user must fill in, and what is hidden behind a default.
206
+
207
+ Returns the form fields, the hidden variables per service, and the panel
208
+ dependency wiring (which is rendered literally, not as a default).
209
+ """
210
+ fields: list[dict] = []
211
+ hidden: dict[str, list[str]] = {}
212
+ # Keys the generator adds on its own; they must not be double counted as
213
+ # "hidden upstream variables" when the upstream compose also sets them.
214
+ reserved: set[str] = {"TZ"}
215
+ port_default = int(spec.get("port") or DEFAULT_PORT)
216
+ port_index = 0
217
+
218
+ for service in spec["services"]:
219
+ port = service.get("container_port")
220
+ if port:
221
+ env_key = "PANEL_APP_PORT_HTTP" if port_index == 0 else f"PANEL_APP_PORT_{port_index}"
222
+ fields.append(
223
+ {
224
+ "envKey": env_key,
225
+ "type": "number",
226
+ "required": True,
227
+ "default": port_default + port_index,
228
+ "edit": True,
229
+ "rule": "paramPort",
230
+ "labelEn": "HTTP Port" if port_index == 0 else f"Port {port_index}",
231
+ "labelZh": "HTTP 端口" if port_index == 0 else f"端口 {port_index}",
232
+ }
233
+ )
234
+ port_index += 1
235
+ for key, raw in (service.get("env") or {}).items():
236
+ item = _normalise_env(raw)
237
+ value = str(item.get("value") or "")
238
+ secret = is_secret(key)
239
+ if not (bool(item.get("expose")) or secret):
240
+ hidden.setdefault(str(service["name"]), []).append(key)
241
+ continue
242
+ entry: dict[str, Any] = {
243
+ "envKey": key,
244
+ "type": item.get("type") or ("password" if secret else "text"),
245
+ "required": bool(item.get("required", secret)),
246
+ "default": "" if secret else value,
247
+ }
248
+ for extra in ("labelEn", "labelZh", "label", "rule", "values", "edit", "random"):
249
+ if extra in item:
250
+ entry[extra] = item[extra]
251
+ if item.get("description"):
252
+ entry["description"] = item["description"]
253
+ fields.append(entry)
254
+
255
+ hidden = {
256
+ service: [key for key in keys if key not in reserved]
257
+ for service, keys in hidden.items()
258
+ }
259
+ hidden = {service: keys for service, keys in hidden.items() if keys}
260
+
261
+ for extra_field in spec.get("form_fields") or []:
262
+ fields.append(dict(extra_field))
263
+
264
+ # D10: a panel-managed database or cache. The spec carries the mapping from
265
+ # the panel's variables to the application's own names; only the variables
266
+ # that mapping actually uses become form fields.
267
+ dependency_fields, dependency_env, dependency_notes = dependencies_module.build(spec)
268
+ fields.extend(dependency_fields)
269
+ warnings.extend(dependency_notes)
270
+
271
+ if spec.get("timezone", True):
272
+ fields.append(
273
+ {
274
+ "envKey": "TZ",
275
+ "type": "text",
276
+ "required": True,
277
+ "default": spec.get("timezone_default") or "Asia/Shanghai",
278
+ "edit": True,
279
+ "labelEn": "Timezone",
280
+ "labelZh": "时区",
281
+ }
282
+ )
283
+
284
+ seen: set[str] = set()
285
+ unique: list[dict] = []
286
+ for item in fields:
287
+ env_key = str(item.get("envKey") or "")
288
+ if not env_key or env_key in seen:
289
+ continue
290
+ seen.add(env_key)
291
+ item.update(resolve_label(item, warnings))
292
+ unique.append(item)
293
+
294
+ budget = rules.load("form-design").get("budget") or {}
295
+ limit = int(budget.get("fields_warn") or 11)
296
+ if len(unique) > limit:
297
+ warnings.append(
298
+ f"表单有 {len(unique)} 个字段,超过官方 p90({limit});"
299
+ "把非必填项改成 compose 默认值(env 里写成普通字符串即可)"
300
+ )
301
+ return unique, hidden, dependency_env
302
+
303
+
304
+ # --------------------------------------------------------------------------
305
+ # compose
306
+ # --------------------------------------------------------------------------
307
+
308
+
309
+ def build_compose(
310
+ spec: dict[str, Any],
311
+ fields: list[dict],
312
+ warnings: list[str],
313
+ dependency_env: dict[str, list[str]] | None = None,
314
+ ) -> dict:
315
+ exposed = {str(item["envKey"]) for item in fields}
316
+ port_keys = [
317
+ str(item["envKey"]) for item in fields if str(item["envKey"]).startswith("PANEL_APP_PORT_")
318
+ ]
319
+ dependency_env = dependency_env or {}
320
+ services: dict[str, Any] = {}
321
+ port_index = 0
322
+
323
+ for index, service in enumerate(spec["services"]):
324
+ name = str(service["name"])
325
+ image = str(service.get("image") or "")
326
+ if not image:
327
+ raise SpecError(f"service {name} 没有 image;镜像必须来自上游证据")
328
+ suffix = "" if index == 0 else f"-{_slug(service.get('suffix') or name)}"
329
+ entry: dict[str, Any] = {
330
+ "image": image,
331
+ "container_name": "${CONTAINER_NAME}" + suffix,
332
+ "restart": service.get("restart") or "always",
333
+ }
334
+ if service.get("depends_on"):
335
+ entry["depends_on"] = list(service["depends_on"])
336
+ entry["networks"] = list(service.get("networks") or ["1panel-network"])
337
+ port = service.get("container_port")
338
+ if port and port_index < len(port_keys):
339
+ entry["ports"] = [f"${{{port_keys[port_index]}}}:{port}"]
340
+ port_index += 1
341
+ volumes = [f"{host}:{target}" for host, target in _mount_pairs(service)]
342
+ if volumes:
343
+ entry["volumes"] = volumes
344
+ env_lines: list[str] = []
345
+ for key, raw in (service.get("env") or {}).items():
346
+ item = _normalise_env(raw)
347
+ value = str(item.get("value") or "")
348
+ if key in exposed:
349
+ env_lines.append(f"{key}=${{{key}}}")
350
+ elif value:
351
+ # Hidden on purpose: still overridable, just not a form field.
352
+ inline = _inline_default(value)
353
+ if inline is None:
354
+ env_lines.append(f"{key}=${{{key}:-}}")
355
+ warnings.append(
356
+ f"{key} 的默认值含有 '}}',无法写进 ${{VAR:-}} 表达式,已改为空默认值"
357
+ )
358
+ else:
359
+ env_lines.append(f"{key}=${{{key}:-{inline}}}")
360
+ else:
361
+ env_lines.append(f"{key}=${{{key}:-}}")
362
+ # A TZ form field is only useful if a container actually consumes it;
363
+ # otherwise the install form collects a value nothing reads.
364
+ if "TZ" in exposed and not any(line.startswith("TZ=") for line in env_lines):
365
+ env_lines.append("TZ=${TZ}")
366
+ # Panel-managed dependency wiring: `${PANEL_DB_HOST}` etc. are rendered
367
+ # by the panel, so they are written literally instead of getting a
368
+ # `${VAR:-default}` fallback.
369
+ env_lines.extend(dependency_env.get(name, []))
370
+ if env_lines:
371
+ entry["environment"] = env_lines
372
+ for extra in (
373
+ "healthcheck",
374
+ "security_opt",
375
+ "cap_add",
376
+ "cap_drop",
377
+ "devices",
378
+ "user",
379
+ "sysctls",
380
+ "ulimits",
381
+ "pid",
382
+ "ipc",
383
+ "tmpfs",
384
+ "read_only",
385
+ "network_mode",
386
+ "extra_hosts",
387
+ "dns",
388
+ "shm_size",
389
+ "stop_grace_period",
390
+ "command",
391
+ "entrypoint",
392
+ ):
393
+ if service.get(extra):
394
+ entry[extra] = service[extra]
395
+ entry["labels"] = {"createdBy": "Apps"}
396
+ services[name] = entry
397
+
398
+ compose: dict[str, Any] = {"services": services}
399
+ if spec.get("named_volumes"):
400
+ compose["volumes"] = {name: {"name": name} for name in spec["named_volumes"]}
401
+ warnings.append("使用命名卷时,根 data.yml 的 limit 应为 1,请确认")
402
+ compose["networks"] = {"1panel-network": {"external": True}}
403
+ return compose
404
+
405
+
406
+ def _referenced_panel_keys(dependency_env: dict[str, list[str]]) -> set[str]:
407
+ keys: set[str] = set()
408
+ for lines in dependency_env.values():
409
+ for line in lines:
410
+ keys.update(re.findall(r"\$\{([A-Za-z_][A-Za-z0-9_]*)", line))
411
+ return keys
412
+
413
+
414
+ def hidden_env_map(spec: dict[str, Any], fields: list[dict]) -> dict[str, str]:
415
+ """Environment variables kept out of the form, with the default they carry.
416
+
417
+ They still belong in `.env.sample`: someone running the compose without
418
+ 1Panel needs to see every knob the container reads.
419
+ """
420
+ exposed = {str(item["envKey"]) for item in fields}
421
+ hidden: dict[str, str] = {}
422
+ for service in spec["services"]:
423
+ for key, raw in (service.get("env") or {}).items():
424
+ if key in exposed:
425
+ continue
426
+ item = _normalise_env(raw)
427
+ hidden[key] = str(item.get("value") or "")
428
+ return hidden
429
+
430
+
431
+ def render_compose(
432
+ spec: dict[str, Any],
433
+ fields: list[dict],
434
+ warnings: list[str],
435
+ dependency_env: dict[str, list[str]] | None = None,
436
+ ) -> str:
437
+ text = _dump(build_compose(spec, fields, warnings, dependency_env))
438
+ # The store convention quotes images, container names and port mappings.
439
+ # The lookahead swallows leading whitespace itself; otherwise a greedy
440
+ # `\s*` backtracks and an already-quoted value gets quoted a second time.
441
+ text = re.sub(
442
+ r"(?m)^([ \t]*image:[ \t]*)(?![ \t]*['\"])(.+?)[ \t]*$", r'\1"\2"', text
443
+ )
444
+ text = re.sub(
445
+ r"(?m)^([ \t]*container_name:[ \t]*)(?![ \t]*['\"])(.+?)[ \t]*$", r'\1"\2"', text
446
+ )
447
+ text = re.sub(
448
+ r"(?m)^([ \t]*-[ \t]*)(\$\{[^}]+\}:\d+(?:/\w+)?)[ \t]*$", r'\1"\2"', text
449
+ )
450
+ return text
451
+
452
+
453
+ # --------------------------------------------------------------------------
454
+ # package assembly
455
+ # --------------------------------------------------------------------------
456
+
457
+
458
+ def _root_data(spec: dict[str, Any], warnings: list[str]) -> dict:
459
+ # Store convention (739 of 771 official apps): `name` carries the product
460
+ # name, while `title`, the top-level `description` and `shortDescZh` are all
461
+ # the same one-line summary.
462
+ description = build_description(spec, warnings)
463
+ product_name = product_of(spec)
464
+ one_liner = one_liner_of(spec)
465
+ tags = list(spec.get("tags") or ["Tool"])
466
+ return {
467
+ "name": product_name,
468
+ "tags": tags,
469
+ "title": one_liner,
470
+ "description": one_liner,
471
+ "additionalProperties": {
472
+ "key": spec["key"],
473
+ "name": product_name,
474
+ "tags": tags,
475
+ "type": spec.get("type") or "tool",
476
+ "website": spec.get("website") or "",
477
+ "document": spec.get("document") or "",
478
+ "github": spec.get("github") or "",
479
+ "shortDescZh": one_liner,
480
+ "shortDescEn": spec.get("shortDescEn") or one_liner,
481
+ "crossVersionUpdate": bool(spec.get("crossVersionUpdate", False)),
482
+ "limit": int(spec.get("limit", 0)),
483
+ "architectures": list(spec.get("architectures") or ["amd64"]),
484
+ "description": description,
485
+ },
486
+ }
487
+
488
+
489
+ def _readme(
490
+ spec: dict[str, Any], fields: list[dict], hidden: dict[str, list[str]], english: bool
491
+ ) -> str:
492
+ title = product_of(spec)
493
+ one_liner = one_liner_of(spec)
494
+ port_field = next(
495
+ (item for item in fields if str(item["envKey"]).startswith("PANEL_APP_PORT_")), None
496
+ )
497
+ port = port_field["default"] if port_field else DEFAULT_PORT
498
+ features = spec.get("features") or []
499
+ volumes = [
500
+ f"- `{host}` → 容器内 `{target}`"
501
+ for service in spec["services"]
502
+ for host, target in _mount_pairs(service)
503
+ ]
504
+ advanced = [
505
+ f"- `{service}`: {', '.join(sorted(keys))}"
506
+ for service, keys in hidden.items()
507
+ if keys
508
+ ]
509
+
510
+ if english:
511
+ lines = [f"# {title}", "", "## Introduction", "", one_liner, ""]
512
+ if features:
513
+ lines += ["## Features", ""] + [f"- {item}" for item in features] + [""]
514
+ lines += ["## Access", "", f"- Web entry: `http://<server-ip>:{port}`", ""]
515
+ lines += ["## Data", ""] + (
516
+ volumes or ["- The application keeps no persistent data."]
517
+ ) + [""]
518
+ if spec.get("init_note"):
519
+ lines += ["## First start", "", str(spec["init_note"]), ""]
520
+ if advanced:
521
+ lines += [
522
+ "## Advanced",
523
+ "",
524
+ "These settings ship with working defaults and are deliberately not on",
525
+ "the install form. Override them in the compose file or a `.env` and restart:",
526
+ "",
527
+ ] + advanced + [""]
528
+ if spec.get("github"):
529
+ lines += ["## References", "", f"- {spec['github']}", ""]
530
+ return "\n".join(lines)
531
+
532
+ lines = [f"# {title}", "", "## 产品介绍", "", one_liner, ""]
533
+ if features:
534
+ lines += ["## 主要功能", ""] + [f"- {item}" for item in features] + [""]
535
+ lines += ["## 访问说明", "", f"- Web 入口:`http://<服务器IP>:{port}`", ""]
536
+ lines += ["## 数据持久化", ""] + (volumes or ["- 本应用不保存持久化数据。"]) + [""]
537
+ if spec.get("init_note"):
538
+ lines += ["## 首次启动", "", str(spec["init_note"]), ""]
539
+ if advanced:
540
+ lines += [
541
+ "## 高级配置",
542
+ "",
543
+ "以下配置都有可用默认值,**刻意没有放进安装表单**,避免让你面对一堆"
544
+ "无从判断的输入。需要修改时在 compose 文件里改默认值(或写进 `.env`)后重启:",
545
+ "",
546
+ ] + advanced + [""]
547
+ if spec.get("github"):
548
+ lines += ["## 参考资料", "", f"- {spec['github']}", ""]
549
+ return "\n".join(lines)
550
+
551
+
552
+ def _placeholder_png(path: Path, colour: tuple[int, int, int]) -> None:
553
+ """A deterministic solid PNG, so a package is never missing its logo."""
554
+ import struct
555
+ import zlib
556
+
557
+ width = height = 180
558
+ raw = (b"\x00" + bytes(colour) * width) * height
559
+
560
+ def chunk(tag: bytes, data: bytes) -> bytes:
561
+ return (
562
+ struct.pack(">I", len(data))
563
+ + tag
564
+ + data
565
+ + struct.pack(">I", zlib.crc32(tag + data))
566
+ )
567
+
568
+ header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
569
+ path.write_bytes(
570
+ b"\x89PNG\r\n\x1a\n"
571
+ + chunk(b"IHDR", header)
572
+ + chunk(b"IDAT", zlib.compress(raw))
573
+ + chunk(b"IEND", b"")
574
+ )
575
+
576
+
577
+ def generate(
578
+ spec: dict[str, Any],
579
+ out_dir: Path,
580
+ force: bool = False,
581
+ allow_unresolved: bool = False,
582
+ ) -> GenResult:
583
+ for required in ("key", "version", "services"):
584
+ if not spec.get(required):
585
+ raise SpecError(f"spec 缺少必需字段 {required!r}")
586
+ if not (spec.get("name") or spec.get("title")):
587
+ raise SpecError("spec 缺少必需字段 'name'(产品名)")
588
+
589
+ # Evidence discipline, before a single file is written: a decision without
590
+ # upstream evidence is a question for a human, not a default to fill in.
591
+ preflight = audit_spec(spec, allowed_unresolved=allow_unresolved)
592
+ if not preflight.ok and not allow_unresolved:
593
+ raise SpecError(preflight.violations())
594
+
595
+ key = _slug(spec["key"])
596
+ root = out_dir / key
597
+ if root.exists() and any(root.iterdir()) and not force:
598
+ raise SpecError(f"{root} 已存在且非空;用 --force 覆盖")
599
+
600
+ warnings: list[str] = []
601
+ fields, hidden, dependency_env = build_fields(spec, warnings)
602
+ scripts, extra_files, script_warnings, script_notes = lifecycle.build(spec)
603
+ warnings.extend(script_warnings)
604
+ warnings.extend(script_notes)
605
+ if extra_files and not spec.get("init_note"):
606
+ spec = dict(spec)
607
+ spec["init_note"] = (
608
+ "首次启动前请先编辑 "
609
+ + "、".join(f"`{path}`" for path, _ in extra_files)
610
+ + "(包内已放好模板),填好你自己的配置后再启动。"
611
+ )
612
+ version = str(spec["version"])
613
+ version_dir = root / version
614
+ data_dir = version_dir / "data"
615
+ scripts_dir = version_dir / "scripts"
616
+ data_dir.mkdir(parents=True, exist_ok=True)
617
+ written: list[str] = []
618
+
619
+ (root / "data.yml").write_text(
620
+ _dump(_root_data(spec, warnings)), encoding="utf-8", newline="\n"
621
+ )
622
+ written.append("data.yml")
623
+
624
+ version_data = {"additionalProperties": {"formFields": fields}}
625
+ (version_dir / "data.yml").write_text(
626
+ _dump(version_data), encoding="utf-8", newline="\n"
627
+ )
628
+ written.append(f"{version}/data.yml")
629
+
630
+ (version_dir / "docker-compose.yml").write_text(
631
+ render_compose(spec, fields, warnings, dependency_env),
632
+ encoding="utf-8",
633
+ newline="\n",
634
+ )
635
+ written.append(f"{version}/docker-compose.yml")
636
+
637
+ env_lines = [
638
+ "# 脱离 1Panel 单独 docker compose 时的参考值;1Panel 安装时会自行渲染 .env",
639
+ "CONTAINER_NAME=",
640
+ ]
641
+ sample: dict[str, str] = {}
642
+ for item in fields:
643
+ sample.setdefault(str(item["envKey"]), str(item.get("default", "")))
644
+ # Panel-managed keys the compose references are filled in by the panel at
645
+ # install time; a standalone `docker compose up` needs them listed too.
646
+ for key in sorted(_referenced_panel_keys(dependency_env)):
647
+ sample.setdefault(key, "")
648
+ for key, value in sorted(hidden_env_map(spec, fields).items()):
649
+ sample.setdefault(key, value)
650
+ env_lines.extend(f"{key}={value}" for key, value in sample.items())
651
+ (version_dir / ".env.sample").write_text(
652
+ "\n".join(env_lines) + "\n", encoding="utf-8", newline="\n"
653
+ )
654
+ written.append(f"{version}/.env.sample")
655
+
656
+ (data_dir / ".gitkeep").write_text("", encoding="utf-8", newline="\n")
657
+ written.append(f"{version}/data/.gitkeep")
658
+
659
+ if scripts:
660
+ scripts_dir.mkdir(parents=True, exist_ok=True)
661
+ for name, text in scripts.items():
662
+ (scripts_dir / f"{name}.sh").write_text(text, encoding="utf-8", newline="\n")
663
+ written.append(f"{version}/scripts/{name}.sh")
664
+
665
+ for path, content in extra_files:
666
+ target = version_dir / path
667
+ target.parent.mkdir(parents=True, exist_ok=True)
668
+ target.write_text(content, encoding="utf-8", newline="\n")
669
+ written.append(f"{version}/{path}")
670
+
671
+ (root / "README.md").write_text(
672
+ _readme(spec, fields, hidden, english=False), encoding="utf-8", newline="\n"
673
+ )
674
+ written.append("README.md")
675
+ if spec.get("english_supported", True):
676
+ (root / "README_en.md").write_text(
677
+ _readme(spec, fields, hidden, english=True), encoding="utf-8", newline="\n"
678
+ )
679
+ written.append("README_en.md")
680
+
681
+ logo_source = spec.get("logo")
682
+ logo_target = root / "logo.png"
683
+ if logo_source and Path(str(logo_source)).exists():
684
+ logo_target.write_bytes(Path(str(logo_source)).read_bytes())
685
+ else:
686
+ seed = sum(ord(ch) for ch in key)
687
+ _placeholder_png(logo_target, (40 + seed % 80, 60 + seed % 90, 120 + seed % 100))
688
+ warnings.append("logo.png 是占位图(纯色 180x180),提交前请换成真实图标")
689
+ written.append("logo.png")
690
+
691
+ if spec.get("source_evidence"):
692
+ (root / "source-evidence.json").write_text(
693
+ json.dumps(spec["source_evidence"], ensure_ascii=False, indent=2) + "\n",
694
+ encoding="utf-8",
695
+ newline="\n",
696
+ )
697
+ written.append("source-evidence.json")
698
+
699
+ if preflight.warnings or preflight.ledger:
700
+ # The reviewer needs to see which decisions came from evidence, which
701
+ # were inferred and which were waved through by a human.
702
+ (root / "decision-audit.json").write_text(
703
+ json.dumps(preflight.to_dict(), ensure_ascii=False, indent=2) + "\n",
704
+ encoding="utf-8",
705
+ newline="\n",
706
+ )
707
+ written.append("decision-audit.json")
708
+
709
+ return GenResult(
710
+ root=root,
711
+ files=written,
712
+ warnings=warnings,
713
+ hidden_env=sorted(
714
+ f"{service}:{key}" for service, keys in hidden.items() for key in keys
715
+ ),
716
+ exposed=[str(item["envKey"]) for item in fields],
717
+ audit=preflight,
718
+ )
719
+
720
+
721
+ def load_spec(path: Path) -> dict[str, Any]:
722
+ try:
723
+ data = json.loads(path.read_text(encoding="utf-8"))
724
+ except (OSError, json.JSONDecodeError) as exc:
725
+ raise SpecError(f"{path}: {exc}") from exc
726
+ if not isinstance(data, dict):
727
+ raise SpecError(f"{path}: spec 顶层必须是对象")
728
+ return data