acceptbox 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.
acceptbox/cli.py ADDED
@@ -0,0 +1,1008 @@
1
+ """Командная строка AcceptBox: --version, --installation, pin, accept, calibrate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import sys
10
+ import uuid
11
+ from pathlib import Path
12
+ from tempfile import TemporaryDirectory, mkdtemp
13
+
14
+ from . import __version__
15
+ from .command import run_commit as run_command_commit
16
+ from .config import (CONFIG_FILENAME, ConfigError, ProjectConfig,
17
+ load_config_from_commit)
18
+ from .git import (GitError, add_worktree, base_env, changed_paths, clone_no_checkout,
19
+ ensure_commit, fetch_ref, is_ancestor, probe_git,
20
+ resolve_repo_head, rev_parse_tree)
21
+ from .inputs import (InputError, build_runtime_env, parse_env_entry, parse_invariants,
22
+ validate_commit_sha, validate_pathspec, validate_ref,
23
+ validate_repo_source, validate_sha256, validate_timeout)
24
+ from .pin import EbtPathMissing, tree_sha256, tree_sha256_in_repo
25
+ from .report import (OutDirLock, OutNotEmptyError, atomic_write_json, completed_run,
26
+ skipped_run, utc_now_iso)
27
+ from .verdict import (RunOutcome, Verdict, ancestry_verdict, coverage,
28
+ evaluate_runs, inputs_untrusted, no_invariants,
29
+ protected_paths_verdict, repro_tests_verdict, run_verdict)
30
+ from .verdict import error as error_verdict
31
+ from .witnessbox import (WITNESSBOX_SUPPORTED_TEXT, check_witnessbox_installation,
32
+ read_findings_inv, run_commit as run_witnessbox_commit)
33
+
34
+ DEFAULT_TIMEOUT_SEC = 600.0
35
+ BASE_SKIP_REASON = "в режиме command базовый коммит не прогоняется"
36
+ NOT_RUN_REASON = "прогон не выполнялся"
37
+
38
+
39
+ class _EbtUntrusted(Exception):
40
+ """Нарушение доверия к ebt/ (L10) → inputs-untrusted, код 1."""
41
+
42
+
43
+ def _dedupe_preserve_order(items: list[str]) -> list[str]:
44
+ return list(dict.fromkeys(items))
45
+
46
+
47
+ def _config_summary(project_config: ProjectConfig | None) -> dict | None:
48
+ if project_config is None:
49
+ return None
50
+ return {
51
+ "path": CONFIG_FILENAME,
52
+ "commit": project_config.source_commit,
53
+ "sha256": project_config.sha256,
54
+ }
55
+
56
+
57
+ def _config_error_summary(cfg_error: ConfigError) -> dict | None:
58
+ """Отпечаток отклонённого .acceptbox.toml для отчёта config-invalid."""
59
+ if cfg_error.commit is None:
60
+ return None
61
+ return {"path": CONFIG_FILENAME, "commit": cfg_error.commit, "sha256": cfg_error.sha256}
62
+
63
+
64
+ def _remove_empty_dir(path: Path) -> None:
65
+ try:
66
+ path.rmdir()
67
+ except OSError:
68
+ pass
69
+
70
+
71
+ def _reject_mode_mixing(args: argparse.Namespace, mode: str,
72
+ cmd_argv: list[str] | None) -> None:
73
+ """Флаги чужого режима — ошибка CLI (код 2)."""
74
+ if mode == "command":
75
+ for flag, value in (("--inv", args.inv), ("--ebt-repo", args.ebt_repo),
76
+ ("--ebt-ref", args.ebt_ref), ("--ebt-sha", args.ebt_sha),
77
+ ("--approved-tree", args.approved_tree)):
78
+ if value is not None:
79
+ raise InputError(f"{flag} не используется в режиме command")
80
+ else:
81
+ if getattr(args, "tests", None):
82
+ raise InputError("--tests не используется в режиме witnessbox")
83
+ if cmd_argv is not None:
84
+ raise InputError("разделитель -- (команда) не используется в режиме witnessbox")
85
+
86
+
87
+ def _reject_cli_cross_mode_mixing(args: argparse.Namespace,
88
+ cmd_argv: list[str] | None) -> None:
89
+ """Явное смешивание command- и witnessbox-флагов на CLI, даже когда --mode опущен."""
90
+ has_command_flags = bool(getattr(args, "tests", None)) or cmd_argv is not None
91
+ has_witnessbox_flags = any(
92
+ value is not None
93
+ for value in (args.inv, args.ebt_repo, args.ebt_ref,
94
+ args.ebt_sha, args.approved_tree)
95
+ )
96
+ if has_command_flags and has_witnessbox_flags:
97
+ raise InputError("нельзя смешивать флаги режимов command и witnessbox")
98
+
99
+
100
+ def _prepare_ebt(temp: Path, git_env: dict[str, str], ebt_repo: str, ebt_ref: str,
101
+ ebt_sha: str, approved_tree: str) -> tuple[Path, str, str]:
102
+ """Доверенные входы EBT (L10): клон, явный fetch --ebt-ref и --ebt-sha,
103
+ проверка предка, сверка дерева и чистый checkout ebt/ из --ebt-sha.
104
+
105
+ Возвращает (ebt_dir, actual_tree_sha256, spec_sha256). Кидает _EbtUntrusted
106
+ (→ inputs-untrusted, код 1) и GitError (→ gate-error, код 2).
107
+ """
108
+ ebt_clone = temp / "ebt-repo"
109
+ clone_no_checkout(ebt_repo, ebt_clone, git_env)
110
+ ref_commit = fetch_ref(ebt_clone, git_env, ebt_repo, ebt_ref)
111
+ if ref_commit is None:
112
+ raise _EbtUntrusted(f"ссылка --ebt-ref {ebt_ref!r} не найдена в --ebt-repo")
113
+ if not ensure_commit(ebt_clone, git_env, ebt_repo, ebt_sha):
114
+ raise _EbtUntrusted(f"коммит --ebt-sha {ebt_sha} не найден в --ebt-repo")
115
+ if not is_ancestor(ebt_clone, git_env, ebt_sha, ref_commit):
116
+ raise _EbtUntrusted(f"--ebt-sha {ebt_sha} не является предком --ebt-ref")
117
+ try:
118
+ actual_tree = tree_sha256_in_repo(ebt_clone, ebt_sha, git_env)
119
+ except EbtPathMissing as missing:
120
+ raise _EbtUntrusted(str(missing)) from missing
121
+ if actual_tree != approved_tree:
122
+ raise _EbtUntrusted(
123
+ f"хеш дерева ebt/ ({actual_tree}) не совпадает с --approved-tree ({approved_tree})")
124
+ ebt_worktree = temp / "ebt-worktree"
125
+ add_worktree(ebt_clone, git_env, ebt_sha, ebt_worktree)
126
+ ebt_dir = ebt_worktree / "ebt"
127
+ spec_path = ebt_dir / "spec.toml"
128
+ if not spec_path.is_file():
129
+ raise _EbtUntrusted(f"ebt/spec.toml отсутствует в --ebt-sha {ebt_sha}")
130
+ return ebt_dir, actual_tree, hashlib.sha256(spec_path.read_bytes()).hexdigest()
131
+
132
+
133
+ def _relative_artifacts(run_name: str, outcome: RunOutcome) -> dict | None:
134
+ """Пути артефактов прогона относительно --out (spec_sha256 — не путь)."""
135
+ if not outcome.artifacts:
136
+ return outcome.artifacts
137
+ result: dict = {}
138
+ for key, value in outcome.artifacts.items():
139
+ if isinstance(value, dict) and isinstance(value.get("path"), str):
140
+ entry = dict(value)
141
+ entry["path"] = f"runs/{run_name}/{value['path']}"
142
+ result[key] = entry
143
+ else:
144
+ result[key] = value
145
+ return result
146
+
147
+
148
+ def _installation() -> int:
149
+ """Диагностика окружения: код 0, если git и acceptbox доступны, независимо от witnessbox."""
150
+ git_block = probe_git()
151
+ witnessbox = check_witnessbox_installation()
152
+ payload = {
153
+ "format": 1,
154
+ "report_format": 1,
155
+ "distribution": "acceptbox",
156
+ "version": __version__,
157
+ "git": git_block,
158
+ "witnessbox": {
159
+ "path": witnessbox.path,
160
+ "version": witnessbox.version,
161
+ "supported": WITNESSBOX_SUPPORTED_TEXT,
162
+ "status": witnessbox.status,
163
+ },
164
+ }
165
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
166
+ return 0 if git_block["status"] == "ok" else 2
167
+
168
+
169
+ def _cmd_pin(args: argparse.Namespace) -> int:
170
+ try:
171
+ repo = validate_repo_source(args.ebt_repo, flag="--ebt-repo")
172
+ sha = validate_commit_sha(args.ebt_sha, flag="--ebt-sha")
173
+ print(tree_sha256(repo, sha))
174
+ except (GitError, ValueError) as failure:
175
+ print(f"acceptbox: {failure}", file=sys.stderr)
176
+ return 2
177
+ return 0
178
+
179
+
180
+ def _cmd_accept(args: argparse.Namespace, cmd_argv: list[str] | None) -> int:
181
+ """Приёмка цепочки base → repro → head; стадии 1–10 с поддержкой L22–L24."""
182
+ started_at = utc_now_iso()
183
+ run_id = str(uuid.uuid4())
184
+ git_env = base_env()
185
+
186
+ # Стадия 1: валидация синтаксиса CLI и немедленный резолв HEAD при опущенном --head (L22).
187
+ try:
188
+ repo = validate_repo_source(args.repo, flag="--repo")
189
+ base = validate_commit_sha(args.base, flag="--base")
190
+ repro = validate_commit_sha(args.repro, flag="--repro")
191
+ # Опущенный --head резолвится после проверки git (стадия 3a), чтобы сбой
192
+ # стал gate-error с accept.json, а не ошибкой CLI.
193
+ head: str | None = (validate_commit_sha(args.head, flag="--head")
194
+ if args.head is not None else None)
195
+
196
+ auto_out = args.out is None
197
+ out_path: Path | None = None
198
+ if not auto_out:
199
+ if not args.out.strip():
200
+ raise InputError("--out: укажите пустой каталог для отчёта")
201
+ out_path = Path(args.out)
202
+
203
+ cli_timeout = (validate_timeout(args.timeout)
204
+ if args.timeout is not None else None)
205
+ cli_protect = [validate_pathspec(item, flag="--protect")
206
+ for item in args.protect or []]
207
+ cli_env_entries = [parse_env_entry(item) for item in args.env or []]
208
+ cli_tests = [validate_pathspec(item, flag="--tests")
209
+ for item in args.tests or []]
210
+ if cmd_argv is not None and not cmd_argv:
211
+ raise InputError("после -- обязательна непустая команда")
212
+ cli_inv_list = (parse_invariants(args.inv)
213
+ if args.inv is not None else None)
214
+ cli_ebt_repo = (validate_repo_source(args.ebt_repo, flag="--ebt-repo")
215
+ if args.ebt_repo is not None else None)
216
+ cli_ebt_ref = (validate_ref(args.ebt_ref, flag="--ebt-ref")
217
+ if args.ebt_ref is not None else None)
218
+ cli_ebt_sha = (validate_commit_sha(args.ebt_sha, flag="--ebt-sha")
219
+ if args.ebt_sha is not None else None)
220
+ cli_approved_tree = (validate_sha256(args.approved_tree, flag="--approved-tree")
221
+ if args.approved_tree is not None else None)
222
+
223
+ if args.mode is not None:
224
+ _reject_mode_mixing(args, args.mode, cmd_argv)
225
+ else:
226
+ _reject_cli_cross_mode_mixing(args, cmd_argv)
227
+ except InputError as invalid:
228
+ print(f"acceptbox: {invalid}", file=sys.stderr)
229
+ return 2
230
+
231
+ # Общее состояние отчёта, наполняется стадиями 3–10 (дополняется после чтения .acceptbox.toml).
232
+ mode = args.mode or "command"
233
+ scope = "command-only" if mode == "command" else "ebt-only"
234
+ timeout = cli_timeout if cli_timeout is not None else DEFAULT_TIMEOUT_SEC
235
+ protect = list(cli_protect)
236
+ env_keys = sorted({key for key, _ in cli_env_entries})
237
+ cmd: list[str] | None = list(cmd_argv) if cmd_argv is not None else None
238
+ tests: list[str] | None = cli_tests if cli_tests else None
239
+ inv_list: list[str] | None = cli_inv_list
240
+ ebt_repo: str | None = cli_ebt_repo
241
+ ebt_ref: str | None = cli_ebt_ref
242
+ ebt_sha: str | None = cli_ebt_sha
243
+ approved_tree: str | None = cli_approved_tree
244
+ project_config: ProjectConfig | None = None
245
+ config_summary: dict | None = None
246
+
247
+ witnessbox_block = None
248
+ wb_info: dict | None = None
249
+ wb_bin = "witnessbox"
250
+ head_tree = None
251
+ actual_tree = spec_sha = None
252
+ findings_inv: list[str] = []
253
+ runs = {"base": skipped_run(base, BASE_SKIP_REASON if mode == "command" else NOT_RUN_REASON),
254
+ "repro": skipped_run(repro, NOT_RUN_REASON),
255
+ "head": skipped_run(head, NOT_RUN_REASON)}
256
+ checks = {"ebt_trust": {"status": "skipped" if mode == "command" else "not-run"},
257
+ "ancestry": {"status": "not-run"},
258
+ "protected_paths": {"status": "not-run"},
259
+ "repro_tests": {"status": "skipped" if mode == "witnessbox" else "not-run"}}
260
+
261
+ def finish(verdict: Verdict, coverage_override: dict | None = None) -> int:
262
+ assert out_path is not None
263
+ finished_at = utc_now_iso()
264
+ inputs_block: dict = {
265
+ "timeout_sec": timeout,
266
+ "protect": protect,
267
+ "env_keys": env_keys,
268
+ "config": config_summary,
269
+ }
270
+ if mode == "command":
271
+ inputs_block["command"] = cmd
272
+ inputs_block["tests"] = tests
273
+ else:
274
+ inputs_block["inv"] = inv_list
275
+ inputs_block["ebt"] = {
276
+ "repo": ebt_repo, "ref": ebt_ref, "sha": ebt_sha,
277
+ "approved_tree_sha256": approved_tree,
278
+ "actual_tree_sha256": actual_tree, "spec_sha256": spec_sha,
279
+ }
280
+ payload = {
281
+ "format": 1,
282
+ "run_id": run_id,
283
+ "started_at": started_at,
284
+ "finished_at": finished_at,
285
+ "acceptbox_version": __version__,
286
+ "mode": mode,
287
+ "scope": scope,
288
+ "witnessbox": witnessbox_block,
289
+ "repo": {"source": repo, "base": base, "repro": repro, "head": head,
290
+ "head_tree": head_tree},
291
+ "inputs": inputs_block,
292
+ "checks": checks,
293
+ "runs": runs,
294
+ "result": verdict.result,
295
+ "exit_code": verdict.exit_code,
296
+ "reason_code": verdict.reason_code,
297
+ "message": verdict.message,
298
+ "coverage": coverage_override or coverage(mode, inv_list or [], findings_inv),
299
+ }
300
+ report_path = atomic_write_json(out_path, "accept.json", payload)
301
+ stream = sys.stdout if verdict.exit_code == 0 else sys.stderr
302
+ print(f"acceptbox: {verdict.result}"
303
+ + (f" ({verdict.reason_code})" if verdict.reason_code else "")
304
+ + f": {verdict.message} (отчёт: {report_path})", file=stream)
305
+ return verdict.exit_code
306
+
307
+ # Стадия 2: атомарный захват --out (или создание нового пустого каталога в TMPDIR, L22).
308
+ if auto_out:
309
+ try:
310
+ out_path = Path(mkdtemp(prefix="acceptbox-accept-"))
311
+ except OSError as io_failure:
312
+ print(f"acceptbox: сбой окружения: {io_failure}", file=sys.stderr)
313
+ return 2
314
+ assert out_path is not None
315
+ lock = OutDirLock(out_path)
316
+ remove_unused_out = False
317
+ try:
318
+ try:
319
+ with lock:
320
+ # Стадия 3a: git, затем резолв опущенного --head в полный SHA (L22).
321
+ if probe_git()["status"] != "ok":
322
+ return finish(error_verdict("gate-error", "git недоступен или сломан"))
323
+ if head is None:
324
+ try:
325
+ head = validate_commit_sha(resolve_repo_head(repo, git_env),
326
+ flag="--head")
327
+ except (GitError, InputError) as head_error:
328
+ return finish(error_verdict(
329
+ "gate-error", f"не удалось разрешить HEAD из --repo: {head_error}"))
330
+ runs["head"] = skipped_run(head, NOT_RUN_REASON)
331
+
332
+ try:
333
+ with TemporaryDirectory(prefix="acceptbox-run-",
334
+ ignore_cleanup_errors=True) as temp_name:
335
+ temp = Path(temp_name)
336
+ # Стадия 5a: клон --repo и чтение .acceptbox.toml строго из base (L23).
337
+ clone = temp / "repo"
338
+ clone_no_checkout(repo, clone, git_env)
339
+ if not ensure_commit(clone, git_env, repo, base):
340
+ return finish(error_verdict(
341
+ "gate-error", f"коммит {base} отсутствует в --repo"))
342
+ try:
343
+ project_config = load_config_from_commit(clone, git_env, base)
344
+ except ConfigError as cfg_error:
345
+ config_summary = _config_error_summary(cfg_error)
346
+ return finish(error_verdict("config-invalid", str(cfg_error)))
347
+ config_summary = _config_summary(project_config)
348
+
349
+ # Слияние CLI + .acceptbox.toml + дефолты L22.
350
+ mode = (args.mode
351
+ or (project_config.mode
352
+ if project_config and project_config.mode else None)
353
+ or "command")
354
+ scope = "command-only" if mode == "command" else "ebt-only"
355
+ runs["base"] = skipped_run(
356
+ base, BASE_SKIP_REASON if mode == "command" else NOT_RUN_REASON)
357
+ checks["ebt_trust"] = {
358
+ "status": "skipped" if mode == "command" else "not-run"}
359
+ checks["repro_tests"] = {
360
+ "status": "skipped" if mode == "witnessbox" else "not-run"}
361
+
362
+ timeout = (cli_timeout if cli_timeout is not None
363
+ else (project_config.timeout
364
+ if project_config and project_config.timeout is not None
365
+ else DEFAULT_TIMEOUT_SEC))
366
+ protect = _dedupe_preserve_order(
367
+ [*(project_config.protect if project_config else ()),
368
+ *cli_protect])
369
+ merged_env_entries = [
370
+ *(project_config.env if project_config else ()),
371
+ *cli_env_entries,
372
+ ]
373
+
374
+ try:
375
+ _reject_mode_mixing(args, mode, cmd_argv)
376
+ if mode == "command":
377
+ tests = (cli_tests if cli_tests
378
+ else (list(project_config.command_tests)
379
+ if project_config and project_config.command_tests
380
+ else None))
381
+ cmd = (list(cmd_argv) if cmd_argv is not None
382
+ else (list(project_config.command_argv)
383
+ if project_config and project_config.command_argv
384
+ else None))
385
+ if not tests:
386
+ raise InputError(
387
+ "в режиме command обязателен --tests <pathspec> "
388
+ "(или [command].tests в .acceptbox.toml)")
389
+ if not cmd:
390
+ raise InputError(
391
+ "в режиме command обязательна команда после -- "
392
+ "(или [command].argv в .acceptbox.toml)")
393
+ else:
394
+ if cli_inv_list is None:
395
+ raise InputError("в режиме witnessbox обязателен флаг --inv")
396
+ inv_list = cli_inv_list
397
+ ebt_repo = (cli_ebt_repo
398
+ or (project_config.witnessbox_ebt_repo
399
+ if project_config else None)
400
+ or repo)
401
+ ebt_ref = (cli_ebt_ref
402
+ or (project_config.witnessbox_ebt_ref
403
+ if project_config else None))
404
+ if ebt_ref is None:
405
+ raise InputError(
406
+ "в режиме witnessbox обязателен --ebt-ref "
407
+ "(или [witnessbox].ebt_ref в .acceptbox.toml)")
408
+ if cli_ebt_sha is None:
409
+ raise InputError(
410
+ "в режиме witnessbox обязателен флаг --ebt-sha")
411
+ if cli_approved_tree is None:
412
+ raise InputError(
413
+ "в режиме witnessbox обязателен флаг --approved-tree")
414
+ ebt_sha = cli_ebt_sha
415
+ approved_tree = cli_approved_tree
416
+ except InputError as invalid:
417
+ remove_unused_out = auto_out or lock.created_dir
418
+ print(f"acceptbox: {invalid}", file=sys.stderr)
419
+ return 2
420
+
421
+ env, env_keys = build_runtime_env(
422
+ os.environ, merged_env_entries,
423
+ base_sha=base if mode == "witnessbox" else None,
424
+ inv_csv=",".join(inv_list) if mode == "witnessbox" else None,
425
+ )
426
+
427
+ # Стадия 3b: witnessbox --installation (только для witnessbox).
428
+ if mode == "witnessbox":
429
+ witnessbox_status = check_witnessbox_installation(env=env)
430
+ if witnessbox_status.info is not None:
431
+ wb_info = witnessbox_status.info
432
+ wb_bin = witnessbox_status.path
433
+ witnessbox_block = {
434
+ "version": witnessbox_status.info["version"],
435
+ "gate_sha256": witnessbox_status.info["gate_sha256"],
436
+ "checker_sha256": witnessbox_status.info["checker_sha256"],
437
+ }
438
+ if witnessbox_status.status == "missing":
439
+ return finish(error_verdict("witnessbox-missing",
440
+ witnessbox_status.message))
441
+ if witnessbox_status.status == "incompatible":
442
+ return finish(error_verdict("witnessbox-incompatible",
443
+ witnessbox_status.message))
444
+ if witnessbox_status.status == "error":
445
+ return finish(error_verdict("gate-error",
446
+ witnessbox_status.message))
447
+
448
+ # Стадия 4: пустой --inv → no-invariants (код 1, прогоны не запускаются).
449
+ if mode == "witnessbox" and not inv_list:
450
+ checks["ebt_trust"] = {"status": "skipped", "reason": "no-invariants"}
451
+ return finish(no_invariants(),
452
+ {"checked": [], "skipped": [],
453
+ "unchecked": ["no-invariants"]})
454
+
455
+ # Стадия 5b: наличие repro и head, SHA дерева head.
456
+ for sha in (repro, head):
457
+ if not ensure_commit(clone, git_env, repo, sha):
458
+ return finish(error_verdict(
459
+ "gate-error", f"коммит {sha} отсутствует в --repo"))
460
+ head_tree = rev_parse_tree(clone, git_env, head)
461
+
462
+ # Стадия 6: доверенные входы EBT (L10) → inputs-untrusted.
463
+ ebt_dir = None
464
+ if mode == "witnessbox":
465
+ try:
466
+ ebt_dir, actual_tree, spec_sha = _prepare_ebt(
467
+ temp, git_env, ebt_repo, ebt_ref, ebt_sha, approved_tree)
468
+ except _EbtUntrusted as untrusted:
469
+ checks["ebt_trust"] = {
470
+ "status": "failed", "reason": str(untrusted)}
471
+ return finish(inputs_untrusted(str(untrusted)))
472
+ checks["ebt_trust"] = {
473
+ "status": "ok", "actual_tree_sha256": actual_tree,
474
+ "spec_sha256": spec_sha}
475
+
476
+ # Стадия 7: ancestry → прогоны не запускаются при отказе.
477
+ ancestry = {
478
+ "base_ancestor_of_repro": is_ancestor(clone, git_env, base, repro),
479
+ "repro_ancestor_of_head": is_ancestor(clone, git_env, repro, head),
480
+ }
481
+ verdict = ancestry_verdict(**ancestry)
482
+ checks["ancestry"] = {"status": "ok" if verdict is None else "failed",
483
+ **ancestry}
484
+ if verdict is not None:
485
+ return finish(verdict)
486
+
487
+ # Стадия 8: защищённые пути на base..repro и base..head.
488
+ # .acceptbox.toml защищается автоматически всегда (L23).
489
+ protected_specs = _dedupe_preserve_order(
490
+ list(protect)
491
+ + [CONFIG_FILENAME]
492
+ + (["ebt", "tool/ebt_check"] if mode == "witnessbox" else [])
493
+ )
494
+ changed_base_repro = changed_paths(clone, git_env, base, repro,
495
+ protected_specs)
496
+ changed_base_head = changed_paths(clone, git_env, base, head,
497
+ protected_specs)
498
+ verdict = protected_paths_verdict(
499
+ changed_base_repro=changed_base_repro,
500
+ changed_base_head=changed_base_head)
501
+ checks["protected_paths"] = {
502
+ "status": "ok" if verdict is None else "failed",
503
+ "specs": protected_specs,
504
+ "changed_base_repro": changed_base_repro,
505
+ "changed_base_head": changed_base_head,
506
+ }
507
+ if verdict is not None:
508
+ return finish(verdict)
509
+
510
+ # Стадия 9 (только command): репро-тесты.
511
+ if mode == "command":
512
+ repro_changed = changed_paths(clone, git_env, base, repro)
513
+ tests_changed = changed_paths(clone, git_env, base, repro, tests)
514
+ head_changed = changed_paths(clone, git_env, repro, head)
515
+ modified = sorted(set(repro_changed) & set(head_changed))
516
+ verdict = repro_tests_verdict(
517
+ repro_changed=repro_changed, tests_changed=tests_changed,
518
+ modified_after_repro=modified)
519
+ checks["repro_tests"] = {
520
+ "status": "ok" if verdict is None else "failed",
521
+ "changed_base_repro": repro_changed,
522
+ "outside_tests": sorted(
523
+ set(repro_changed) - set(tests_changed)),
524
+ "modified_after_repro": modified,
525
+ }
526
+ if verdict is not None:
527
+ return finish(verdict)
528
+
529
+ # Стадия 10: последовательные fail-fast прогоны.
530
+ executed: list[tuple[str, RunOutcome]] = []
531
+ order = ("base", "repro", "head") if mode == "witnessbox" \
532
+ else ("repro", "head")
533
+ shas = {"base": base, "repro": repro, "head": head}
534
+ for name in order:
535
+ worktree = temp / f"worktree-{name}"
536
+ add_worktree(clone, git_env, shas[name], worktree)
537
+ run_dir = out_path / "runs" / name
538
+ if mode == "command":
539
+ outcome = run_command_commit(worktree, shas[name], run_dir,
540
+ env, timeout, cmd_argv=cmd)
541
+ else:
542
+ outcome = run_witnessbox_commit(
543
+ worktree, shas[name], run_dir, env, timeout,
544
+ ebt_dir=ebt_dir, approved_spec_sha256=spec_sha,
545
+ expected_invariants=inv_list, installation_info=wb_info,
546
+ witnessbox_bin=wb_bin)
547
+ runs[name] = completed_run(
548
+ shas[name], outcome,
549
+ log_path=f"runs/{name}/{outcome.log_path}",
550
+ artifacts=_relative_artifacts(name, outcome))
551
+ executed.append((name, outcome))
552
+ if outcome.status == "red":
553
+ findings_inv.extend(read_findings_inv(run_dir))
554
+ step = run_verdict(name, outcome)
555
+ if step is not None:
556
+ return finish(step)
557
+ return finish(evaluate_runs(executed))
558
+ except GitError as git_failure:
559
+ return finish(error_verdict("gate-error", f"сбой git: {git_failure}"))
560
+ except EbtPathMissing as missing:
561
+ return finish(inputs_untrusted(str(missing)))
562
+ except OSError as io_failure:
563
+ return finish(error_verdict("gate-error", f"сбой окружения: {io_failure}"))
564
+ except OutNotEmptyError as occupied:
565
+ print(f"acceptbox: {occupied}", file=sys.stderr)
566
+ return 2
567
+ except OSError as io_failure:
568
+ remove_unused_out = auto_out or lock.created_dir
569
+ print(f"acceptbox: сбой окружения: {io_failure}", file=sys.stderr)
570
+ return 2
571
+ finally:
572
+ if remove_unused_out:
573
+ _remove_empty_dir(out_path)
574
+ return 2
575
+
576
+
577
+ def _cmd_calibrate(args: argparse.Namespace, cmd_argv: list[str] | None) -> int:
578
+ """Калибровка чувствительности (L18): calibrate.json, никогда accept.json.
579
+
580
+ Проверки ancestry и base..repro диффа не выполняются. При переданном
581
+ ``--base`` может читать ``.acceptbox.toml`` строго из базового коммита (L23).
582
+ """
583
+ started_at = utc_now_iso()
584
+ run_id = str(uuid.uuid4())
585
+ git_env = base_env()
586
+
587
+ # Стадия 1: валидация CLI (код 2).
588
+ try:
589
+ repo = validate_repo_source(args.repo, flag="--repo")
590
+ auto_out = args.out is None
591
+ out_path: Path | None = None
592
+ if not auto_out:
593
+ if not args.out.strip():
594
+ raise InputError("--out: укажите пустой каталог для отчёта")
595
+ out_path = Path(args.out)
596
+ cli_timeout = (validate_timeout(args.timeout)
597
+ if args.timeout is not None else None)
598
+ cli_env_entries = [parse_env_entry(item) for item in args.env or []]
599
+ base = validate_commit_sha(args.base, flag="--base") if args.base else None
600
+ if not args.green and not args.red:
601
+ raise InputError("укажите хотя бы один --green <sha> или --red <sha>")
602
+ greens = [validate_commit_sha(sha, flag="--green") for sha in args.green or []]
603
+ reds = [validate_commit_sha(sha, flag="--red") for sha in args.red or []]
604
+ if cmd_argv is not None and not cmd_argv:
605
+ raise InputError("после -- обязательна непустая команда")
606
+ cli_inv_list = (parse_invariants(args.inv)
607
+ if args.inv is not None else None)
608
+ cli_ebt_repo = (validate_repo_source(args.ebt_repo, flag="--ebt-repo")
609
+ if args.ebt_repo is not None else None)
610
+ cli_ebt_ref = (validate_ref(args.ebt_ref, flag="--ebt-ref")
611
+ if args.ebt_ref is not None else None)
612
+ cli_ebt_sha = (validate_commit_sha(args.ebt_sha, flag="--ebt-sha")
613
+ if args.ebt_sha is not None else None)
614
+ cli_approved_tree = (validate_sha256(args.approved_tree, flag="--approved-tree")
615
+ if args.approved_tree is not None else None)
616
+
617
+ if args.mode is not None:
618
+ _reject_mode_mixing(args, args.mode, cmd_argv)
619
+ else:
620
+ _reject_cli_cross_mode_mixing(args, cmd_argv)
621
+
622
+ # Без --base конфиг .acceptbox.toml не читается (L23) — проверяем полноту CLI сразу.
623
+ if base is None:
624
+ resolved_mode = args.mode or "command"
625
+ _reject_mode_mixing(args, resolved_mode, cmd_argv)
626
+ if resolved_mode == "command":
627
+ if not cmd_argv:
628
+ raise InputError("в режиме command после -- обязательна непустая команда")
629
+ else:
630
+ if cli_inv_list is None:
631
+ raise InputError("в режиме witnessbox обязателен флаг --inv")
632
+ if cli_ebt_ref is None:
633
+ raise InputError("в режиме witnessbox обязателен флаг --ebt-ref")
634
+ if cli_ebt_sha is None:
635
+ raise InputError("в режиме witnessbox обязателен флаг --ebt-sha")
636
+ if cli_approved_tree is None:
637
+ raise InputError("в режиме witnessbox обязателен флаг --approved-tree")
638
+ except InputError as invalid:
639
+ print(f"acceptbox: {invalid}", file=sys.stderr)
640
+ return 2
641
+
642
+ mode = args.mode or "command"
643
+ scope = "command-only" if mode == "command" else "ebt-only"
644
+ timeout = cli_timeout if cli_timeout is not None else DEFAULT_TIMEOUT_SEC
645
+ env_keys = sorted({key for key, _ in cli_env_entries})
646
+ cmd: list[str] | None = list(cmd_argv) if cmd_argv is not None else None
647
+ inv_list: list[str] | None = cli_inv_list
648
+ ebt_repo: str | None = cli_ebt_repo
649
+ ebt_ref: str | None = cli_ebt_ref
650
+ ebt_sha: str | None = cli_ebt_sha
651
+ approved_tree: str | None = cli_approved_tree
652
+ project_config: ProjectConfig | None = None
653
+ config_summary: dict | None = None
654
+
655
+ witnessbox_block = None
656
+ wb_info: dict | None = None
657
+ wb_bin = "witnessbox"
658
+ actual_tree = spec_sha = None
659
+ results: list[dict] = []
660
+
661
+ def finish(result: str, exit_code: int, reason_code: str | None, message: str) -> int:
662
+ assert out_path is not None
663
+ finished_at = utc_now_iso()
664
+ inputs_block: dict = {
665
+ "timeout_sec": timeout,
666
+ "env_keys": env_keys,
667
+ "config": config_summary,
668
+ }
669
+ if mode == "command":
670
+ inputs_block["command"] = cmd
671
+ else:
672
+ inputs_block["inv"] = inv_list
673
+ inputs_block["ebt"] = {
674
+ "repo": ebt_repo, "ref": ebt_ref, "sha": ebt_sha,
675
+ "approved_tree_sha256": approved_tree,
676
+ "actual_tree_sha256": actual_tree, "spec_sha256": spec_sha,
677
+ }
678
+ payload = {
679
+ "format": 1,
680
+ "run_id": run_id,
681
+ "started_at": started_at,
682
+ "finished_at": finished_at,
683
+ "acceptbox_version": __version__,
684
+ "mode": mode,
685
+ "scope": scope,
686
+ "witnessbox": witnessbox_block,
687
+ "repo": {"source": repo, "base": base},
688
+ "inputs": inputs_block,
689
+ "results": results,
690
+ "result": result,
691
+ "exit_code": exit_code,
692
+ "reason_code": reason_code,
693
+ "message": message,
694
+ }
695
+ report_path = atomic_write_json(out_path, "calibrate.json", payload)
696
+ stream = sys.stdout if exit_code == 0 else sys.stderr
697
+ print(f"acceptbox: {result}"
698
+ + (f" ({reason_code})" if reason_code else "")
699
+ + f": {message} (отчёт: {report_path})", file=stream)
700
+ return exit_code
701
+
702
+ if auto_out:
703
+ try:
704
+ out_path = Path(mkdtemp(prefix="acceptbox-calibrate-"))
705
+ except OSError as io_failure:
706
+ print(f"acceptbox: сбой окружения: {io_failure}", file=sys.stderr)
707
+ return 2
708
+ assert out_path is not None
709
+ lock = OutDirLock(out_path)
710
+ remove_unused_out = False
711
+ try:
712
+ try:
713
+ with lock:
714
+ if probe_git()["status"] != "ok":
715
+ return finish("ERROR", 2, "gate-error", "git недоступен или сломан")
716
+
717
+ try:
718
+ with TemporaryDirectory(prefix="acceptbox-calibrate-",
719
+ ignore_cleanup_errors=True) as temp_name:
720
+ temp = Path(temp_name)
721
+ clone = temp / "repo"
722
+ clone_no_checkout(repo, clone, git_env)
723
+ if base is not None:
724
+ if not ensure_commit(clone, git_env, repo, base):
725
+ return finish("ERROR", 2, "gate-error",
726
+ f"коммит --base {base} отсутствует в --repo")
727
+ try:
728
+ project_config = load_config_from_commit(clone, git_env, base)
729
+ except ConfigError as cfg_error:
730
+ config_summary = _config_error_summary(cfg_error)
731
+ return finish("ERROR", 2, "config-invalid", str(cfg_error))
732
+ config_summary = _config_summary(project_config)
733
+
734
+ mode = (args.mode
735
+ or (project_config.mode
736
+ if project_config and project_config.mode else None)
737
+ or "command")
738
+ scope = "command-only" if mode == "command" else "ebt-only"
739
+ timeout = (cli_timeout if cli_timeout is not None
740
+ else (project_config.timeout
741
+ if project_config and project_config.timeout is not None
742
+ else DEFAULT_TIMEOUT_SEC))
743
+ merged_env_entries = [
744
+ *(project_config.env if project_config else ()),
745
+ *cli_env_entries,
746
+ ]
747
+
748
+ try:
749
+ _reject_mode_mixing(args, mode, cmd_argv)
750
+ if mode == "command":
751
+ cmd = (list(cmd_argv) if cmd_argv is not None
752
+ else (list(project_config.command_argv)
753
+ if project_config and project_config.command_argv
754
+ else None))
755
+ if not cmd:
756
+ raise InputError(
757
+ "в режиме command обязательна команда после -- "
758
+ "(или [command].argv в .acceptbox.toml при --base)")
759
+ else:
760
+ if cli_inv_list is None:
761
+ raise InputError("в режиме witnessbox обязателен флаг --inv")
762
+ inv_list = cli_inv_list
763
+ ebt_repo = (cli_ebt_repo
764
+ or (project_config.witnessbox_ebt_repo
765
+ if project_config else None)
766
+ or repo)
767
+ ebt_ref = (cli_ebt_ref
768
+ or (project_config.witnessbox_ebt_ref
769
+ if project_config else None))
770
+ if ebt_ref is None:
771
+ raise InputError(
772
+ "в режиме witnessbox обязателен --ebt-ref "
773
+ "(или [witnessbox].ebt_ref в .acceptbox.toml при --base)")
774
+ if cli_ebt_sha is None:
775
+ raise InputError(
776
+ "в режиме witnessbox обязателен флаг --ebt-sha")
777
+ if cli_approved_tree is None:
778
+ raise InputError(
779
+ "в режиме witnessbox обязателен флаг --approved-tree")
780
+ ebt_sha = cli_ebt_sha
781
+ approved_tree = cli_approved_tree
782
+ except InputError as invalid:
783
+ remove_unused_out = auto_out or lock.created_dir
784
+ print(f"acceptbox: {invalid}", file=sys.stderr)
785
+ return 2
786
+
787
+ env, env_keys = build_runtime_env(
788
+ os.environ, merged_env_entries,
789
+ base_sha=base if mode == "witnessbox" else None,
790
+ inv_csv=",".join(inv_list) if mode == "witnessbox" else None,
791
+ )
792
+
793
+ if mode == "witnessbox":
794
+ witnessbox_status = check_witnessbox_installation(env=env)
795
+ if witnessbox_status.info is not None:
796
+ wb_info = witnessbox_status.info
797
+ wb_bin = witnessbox_status.path
798
+ witnessbox_block = {
799
+ "version": witnessbox_status.info["version"],
800
+ "gate_sha256": witnessbox_status.info["gate_sha256"],
801
+ "checker_sha256": witnessbox_status.info["checker_sha256"],
802
+ }
803
+ if witnessbox_status.status == "missing":
804
+ return finish("ERROR", 2, "witnessbox-missing",
805
+ witnessbox_status.message)
806
+ if witnessbox_status.status == "incompatible":
807
+ return finish("ERROR", 2, "witnessbox-incompatible",
808
+ witnessbox_status.message)
809
+ if witnessbox_status.status == "error":
810
+ return finish("ERROR", 2, "gate-error",
811
+ witnessbox_status.message)
812
+ if not inv_list:
813
+ return finish("FAILED", 1, "no-invariants",
814
+ "--inv не содержит ни одного инварианта")
815
+
816
+ ebt_dir = None
817
+ if mode == "witnessbox":
818
+ ebt_dir, actual_tree, spec_sha = _prepare_ebt(
819
+ temp, git_env, ebt_repo, ebt_ref, ebt_sha, approved_tree)
820
+ targets = ([("green", sha) for sha in greens]
821
+ + [("red", sha) for sha in reds])
822
+ for index, (kind, sha) in enumerate(targets, start=1):
823
+ if not ensure_commit(clone, git_env, repo, sha):
824
+ return finish("ERROR", 2, "gate-error",
825
+ f"коммит {sha} отсутствует в --repo")
826
+ worktree = temp / f"worktree-{index}"
827
+ add_worktree(clone, git_env, sha, worktree)
828
+ run_dir = out_path / "runs" / f"{kind}-{index}"
829
+ if mode == "command":
830
+ outcome = run_command_commit(worktree, sha, run_dir,
831
+ env, timeout, cmd_argv=cmd)
832
+ else:
833
+ outcome = run_witnessbox_commit(
834
+ worktree, sha, run_dir, env, timeout,
835
+ ebt_dir=ebt_dir, approved_spec_sha256=spec_sha,
836
+ expected_invariants=inv_list,
837
+ installation_info=wb_info, witnessbox_bin=wb_bin)
838
+ run_name = f"{kind}-{index}"
839
+ results.append({
840
+ "commit": sha,
841
+ "expected": kind,
842
+ "status": outcome.status,
843
+ "matched": outcome.status == kind,
844
+ "exit_code": outcome.exit_code,
845
+ "reason": outcome.reason,
846
+ "duration_ms": outcome.duration_ms,
847
+ "log_path": f"runs/{run_name}/{outcome.log_path}",
848
+ "artifacts": _relative_artifacts(run_name, outcome),
849
+ })
850
+ except GitError as git_failure:
851
+ return finish("ERROR", 2, "gate-error", f"сбой git: {git_failure}")
852
+ except _EbtUntrusted as untrusted:
853
+ return finish("FAILED", 1, "inputs-untrusted", str(untrusted))
854
+ except EbtPathMissing as missing:
855
+ return finish("FAILED", 1, "inputs-untrusted", str(missing))
856
+ except OSError as io_failure:
857
+ return finish("ERROR", 2, "gate-error", f"сбой окружения: {io_failure}")
858
+
859
+ if any(item["status"] == "error" for item in results):
860
+ return finish("ERROR", 2, "gate-error",
861
+ "хотя бы один прогон завершился ошибкой")
862
+ mismatches = [item for item in results if not item["matched"]]
863
+ if mismatches:
864
+ detail = ", ".join(
865
+ f"{item['commit']} ({item['expected']} → {item['status']})"
866
+ for item in mismatches)
867
+ return finish("FAILED", 1, "mismatch", f"исход не совпал: {detail}")
868
+ return finish("CALIBRATED", 0, None, "все коммиты дали ожидаемые исходы")
869
+ except OutNotEmptyError as occupied:
870
+ print(f"acceptbox: {occupied}", file=sys.stderr)
871
+ return 2
872
+ except OSError as io_failure:
873
+ remove_unused_out = auto_out or lock.created_dir
874
+ print(f"acceptbox: сбой окружения: {io_failure}", file=sys.stderr)
875
+ return 2
876
+ finally:
877
+ if remove_unused_out:
878
+ _remove_empty_dir(out_path)
879
+ return 2
880
+
881
+
882
+ def _build_parser() -> argparse.ArgumentParser:
883
+ parser = argparse.ArgumentParser(
884
+ prog="acceptbox",
885
+ description="Независимая приёмка коммитов: base → repro → head "
886
+ "(багфиксы и утверждённые инварианты).",
887
+ )
888
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
889
+ parser.add_argument("--installation", action="store_true",
890
+ help="проверить окружение (git, witnessbox) и выйти")
891
+ commands = parser.add_subparsers(dest="command")
892
+
893
+ pin = commands.add_parser(
894
+ "pin", help="вычислить SHA-256 дерева ebt/ из Git-коммита")
895
+ pin.add_argument("--ebt-repo", required=True, help="путь или URL репозитория с ebt/")
896
+ pin.add_argument("--ebt-sha", required=True, help="полный SHA коммита Git")
897
+
898
+ accept = commands.add_parser(
899
+ "accept",
900
+ help="приёмка цепочки base → repro → head (багфиксы и утверждённые инварианты)",
901
+ )
902
+ _add_accept_flags(accept)
903
+
904
+ calibrate = commands.add_parser(
905
+ "calibrate", help="калибровка чувствительности прогонщиков (L18)")
906
+ _add_calibrate_flags(calibrate)
907
+ return parser
908
+
909
+
910
+ def _add_accept_flags(subparser: argparse.ArgumentParser) -> None:
911
+ subparser.add_argument(
912
+ "--mode", default=None, choices=("command", "witnessbox"),
913
+ help="режим приёмки (по умолчанию из .acceptbox.toml или command)")
914
+ subparser.add_argument(
915
+ "--repo", default=".",
916
+ help="путь или URL проверяемого репозитория (по умолчанию .)")
917
+ subparser.add_argument("--base", required=True, help="полный SHA базового коммита")
918
+ subparser.add_argument("--repro", required=True, help="полный SHA репро-коммита")
919
+ subparser.add_argument(
920
+ "--head", default=None,
921
+ help="полный SHA головного коммита (по умолчанию HEAD из --repo)")
922
+ subparser.add_argument(
923
+ "--out", default=None,
924
+ help="пустой каталог для отчёта accept.json (по умолчанию создаётся в TMPDIR)")
925
+ subparser.add_argument(
926
+ "--timeout", default=None,
927
+ help="таймаут одного прогона в секундах (по умолчанию из .acceptbox.toml или 600)")
928
+ subparser.add_argument("--protect", action="append",
929
+ help="pathspec защищённых путей (повторяемый; суммируется с конфигом)")
930
+ subparser.add_argument("--env", action="append",
931
+ help="переменная окружения KEY[=VAL] (повторяемый)")
932
+ subparser.add_argument("--tests", action="append",
933
+ help="pathspec репро-теста (повторяемый, только command)")
934
+ subparser.add_argument("--inv", help="инварианты через запятую (только witnessbox)")
935
+ subparser.add_argument(
936
+ "--ebt-repo",
937
+ help="репозиторий EBT (только witnessbox; по умолчанию из .acceptbox.toml или --repo)")
938
+ subparser.add_argument(
939
+ "--ebt-ref",
940
+ help="ветка основной ветки EBT (только witnessbox; можно задать в .acceptbox.toml)")
941
+ subparser.add_argument("--ebt-sha", help="полный SHA коммита EBT (только witnessbox)")
942
+ subparser.add_argument("--approved-tree",
943
+ help="утверждённый SHA-256 дерева ebt/ (только witnessbox)")
944
+
945
+
946
+ def _add_calibrate_flags(subparser: argparse.ArgumentParser) -> None:
947
+ subparser.add_argument(
948
+ "--mode", default=None, choices=("command", "witnessbox"),
949
+ help="режим калибровки (по умолчанию из .acceptbox.toml при --base или command)")
950
+ subparser.add_argument(
951
+ "--repo", default=".",
952
+ help="путь или URL проверяемого репозитория (по умолчанию .)")
953
+ subparser.add_argument(
954
+ "--out", default=None,
955
+ help="пустой каталог для отчёта calibrate.json (по умолчанию создаётся в TMPDIR)")
956
+ subparser.add_argument("--green", action="append",
957
+ help="коммит, ожидающий green (повторяемый)")
958
+ subparser.add_argument("--red", action="append",
959
+ help="коммит, ожидающий red (повторяемый)")
960
+ subparser.add_argument(
961
+ "--base",
962
+ help="полный SHA базового коммита (BASE в witnessbox и источник .acceptbox.toml)")
963
+ subparser.add_argument(
964
+ "--timeout", default=None,
965
+ help="таймаут одного прогона в секундах (по умолчанию из .acceptbox.toml или 600)")
966
+ subparser.add_argument("--env", action="append",
967
+ help="переменная окружения KEY[=VAL] (повторяемый)")
968
+ subparser.add_argument("--inv", help="инварианты через запятую (только witnessbox)")
969
+ subparser.add_argument(
970
+ "--ebt-repo",
971
+ help="репозиторий EBT (только witnessbox; по умолчанию из .acceptbox.toml или --repo)")
972
+ subparser.add_argument(
973
+ "--ebt-ref",
974
+ help="ветка основной ветки EBT (только witnessbox; можно задать в .acceptbox.toml)")
975
+ subparser.add_argument("--ebt-sha", help="полный SHA коммита EBT (только witnessbox)")
976
+ subparser.add_argument("--approved-tree",
977
+ help="утверждённый SHA-256 дерева ebt/ (только witnessbox)")
978
+
979
+
980
+ def main(argv: list[str] | None = None) -> int:
981
+ raw = list(sys.argv[1:] if argv is None else argv)
982
+ # Команда после -- не разбирается argparse: её флаги принадлежат ей, не acceptbox.
983
+ cmd_argv: list[str] | None = None
984
+ if "--" in raw:
985
+ separator = raw.index("--")
986
+ cmd_argv = raw[separator + 1:]
987
+ raw = raw[:separator]
988
+ parser = _build_parser()
989
+ args = parser.parse_args(raw)
990
+
991
+ if args.installation:
992
+ if args.command or cmd_argv is not None:
993
+ parser.error("--installation используется отдельно от команд")
994
+ return _installation()
995
+ if args.command == "pin":
996
+ if cmd_argv is not None:
997
+ parser.error("pin не принимает аргументы после --")
998
+ return _cmd_pin(args)
999
+ if args.command == "accept":
1000
+ return _cmd_accept(args, cmd_argv)
1001
+ if args.command == "calibrate":
1002
+ return _cmd_calibrate(args, cmd_argv)
1003
+ parser.print_help()
1004
+ return 0
1005
+
1006
+
1007
+ if __name__ == "__main__":
1008
+ sys.exit(main())