xharness 0.1.0__tar.gz

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.
@@ -0,0 +1,6 @@
1
+ **/.venv/
2
+ **/node_modules/
3
+ **/__pycache__/
4
+ **/.pytest_cache/
5
+ **/dist/
6
+ *.egg-info/
xharness-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kip Yin
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.5
2
+ Name: xharness
3
+ Version: 0.1.0
4
+ Summary: Shared operational harness library: Windows executable packaging, release deployment, configuration, environment, and logging (Python).
5
+ Author-email: Kip Yin <28321392+kipyin@users.noreply.github.com>
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+
11
+ # xharness
12
+
13
+ 面向 Python 和 TypeScript 的共享基础库,提供 Windows 应用打包、发布部署、配置与日志等运维支持。
14
+
15
+ 最低环境要求:Python 3.12 与 Node.js 22。
16
+
17
+ ## 安装
18
+
19
+ ### Python (uv)
20
+
21
+ ```sh
22
+ uv add xharness
23
+ ```
24
+
25
+ ### TypeScript / Node.js (npm)
26
+
27
+ ```sh
28
+ npm i @lightxlab/xharness
29
+ ```
30
+
31
+ ## 快速上手
32
+
33
+ xharness 核心用于产品的打包与发布部署。
34
+
35
+ ### 1. 本地打包 Windows 可执行文件
36
+
37
+ 支持 `.py`(基于 PyInstaller)和 `.js`(基于 Node pkg)入口,默认打包输出至 `dist/`。
38
+
39
+ #### Python
40
+
41
+ ```python
42
+ from xharness import deploy
43
+
44
+ request = deploy.BuildRequest(entrypoint="app.py")
45
+ output_path = deploy.build(request)
46
+
47
+ print(f"可执行文件已生成: {output_path}")
48
+ ```
49
+
50
+ 也可以直接通过 CLI 打包:
51
+
52
+ ```sh
53
+ uv run xharness-build --entrypoint app.py
54
+ ```
55
+
56
+ #### TypeScript
57
+
58
+ ```ts
59
+ import { deploy } from "@lightxlab/xharness";
60
+
61
+ const { artifactPath } = await deploy.build({
62
+ entrypoint: "app.js",
63
+ });
64
+
65
+ console.log(`可执行文件已生成: ${artifactPath}`);
66
+ ```
67
+
68
+ ### 2. 打包配置 (xharness.toml)
69
+
70
+ 如果需要自定义打包名称、输出目录或打包工具参数,可在产品根目录创建 `xharness.toml`:
71
+
72
+ ```toml
73
+ product = "my-product"
74
+ output = "dist"
75
+
76
+ [pyinstaller]
77
+ hidden-imports = ["uvicorn"]
78
+ resources = [
79
+ { source = "assets", destination = "assets" }
80
+ ]
81
+
82
+ [pkg]
83
+ compress = "GZip"
84
+ ```
85
+
86
+ ### 3. 运行时配置与日志(占位接口)
87
+
88
+ ```python
89
+ from xharness import config, env, logging
90
+
91
+ logging.configure()
92
+ runtime = env.runtime_name()
93
+ settings = config.load()
94
+ ```
95
+
96
+ > 当前 `config.load`、`env.runtime_name` / `runtimeName` 和 `logging.configure` 为接口占位桩函数(调用抛出 `NotImplementedError` / `Error`),后续版本开放具体实现。
97
+
98
+ ## 许可
99
+
100
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,90 @@
1
+ # xharness
2
+
3
+ 面向 Python 和 TypeScript 的共享基础库,提供 Windows 应用打包、发布部署、配置与日志等运维支持。
4
+
5
+ 最低环境要求:Python 3.12 与 Node.js 22。
6
+
7
+ ## 安装
8
+
9
+ ### Python (uv)
10
+
11
+ ```sh
12
+ uv add xharness
13
+ ```
14
+
15
+ ### TypeScript / Node.js (npm)
16
+
17
+ ```sh
18
+ npm i @lightxlab/xharness
19
+ ```
20
+
21
+ ## 快速上手
22
+
23
+ xharness 核心用于产品的打包与发布部署。
24
+
25
+ ### 1. 本地打包 Windows 可执行文件
26
+
27
+ 支持 `.py`(基于 PyInstaller)和 `.js`(基于 Node pkg)入口,默认打包输出至 `dist/`。
28
+
29
+ #### Python
30
+
31
+ ```python
32
+ from xharness import deploy
33
+
34
+ request = deploy.BuildRequest(entrypoint="app.py")
35
+ output_path = deploy.build(request)
36
+
37
+ print(f"可执行文件已生成: {output_path}")
38
+ ```
39
+
40
+ 也可以直接通过 CLI 打包:
41
+
42
+ ```sh
43
+ uv run xharness-build --entrypoint app.py
44
+ ```
45
+
46
+ #### TypeScript
47
+
48
+ ```ts
49
+ import { deploy } from "@lightxlab/xharness";
50
+
51
+ const { artifactPath } = await deploy.build({
52
+ entrypoint: "app.js",
53
+ });
54
+
55
+ console.log(`可执行文件已生成: ${artifactPath}`);
56
+ ```
57
+
58
+ ### 2. 打包配置 (xharness.toml)
59
+
60
+ 如果需要自定义打包名称、输出目录或打包工具参数,可在产品根目录创建 `xharness.toml`:
61
+
62
+ ```toml
63
+ product = "my-product"
64
+ output = "dist"
65
+
66
+ [pyinstaller]
67
+ hidden-imports = ["uvicorn"]
68
+ resources = [
69
+ { source = "assets", destination = "assets" }
70
+ ]
71
+
72
+ [pkg]
73
+ compress = "GZip"
74
+ ```
75
+
76
+ ### 3. 运行时配置与日志(占位接口)
77
+
78
+ ```python
79
+ from xharness import config, env, logging
80
+
81
+ logging.configure()
82
+ runtime = env.runtime_name()
83
+ settings = config.load()
84
+ ```
85
+
86
+ > 当前 `config.load`、`env.runtime_name` / `runtimeName` 和 `logging.configure` 为接口占位桩函数(调用抛出 `NotImplementedError` / `Error`),后续版本开放具体实现。
87
+
88
+ ## 许可
89
+
90
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "xharness"
7
+ version = "0.1.0"
8
+ description = "Shared operational harness library: Windows executable packaging, release deployment, configuration, environment, and logging (Python)."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Kip Yin", email = "28321392+kipyin@users.noreply.github.com" }]
13
+ requires-python = ">=3.12"
14
+ dependencies = []
15
+
16
+ [project.scripts]
17
+ xharness-build = "xharness.deploy.build:main"
18
+
19
+ [dependency-groups]
20
+ dev = [
21
+ "pytest>=8.0",
22
+ "pyinstaller>=6.0",
23
+ ]
24
+
25
+ [tool.uv]
26
+ package = true
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/xharness"]
30
+
31
+ [tool.hatch.build.targets.sdist]
32
+ include = ["src/xharness", "pyproject.toml"]
33
+ ignore-vcs = true
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
37
+ pythonpath = ["src"]
38
+ addopts = "-ra -m 'not live'"
39
+ markers = [
40
+ "live: package-manager install outside the default suite",
41
+ ]
@@ -0,0 +1,5 @@
1
+ """Shared light* coding harness library (Python)."""
2
+
3
+ from . import config, deploy, env, logging
4
+
5
+ __all__ = ["config", "deploy", "env", "logging"]
@@ -0,0 +1,6 @@
1
+ """Configuration loading for light* apps (stub)."""
2
+
3
+
4
+ def load() -> dict[str, object]:
5
+ """Load harness configuration from the environment."""
6
+ raise NotImplementedError("xharness.config.load is not implemented yet")
@@ -0,0 +1,5 @@
1
+ """Unified light* packaging surface (Windows executables today; Docker later)."""
2
+
3
+ from xharness.deploy.build import BuildError, BuildRequest, build
4
+
5
+ __all__ = ["BuildError", "BuildRequest", "build"]
@@ -0,0 +1,802 @@
1
+ """Build the dev executable, or the release trio on the single product tag."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import platform
10
+ import re
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ import tomllib
15
+ import uuid
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass
18
+ from datetime import datetime, timedelta, timezone
19
+ from importlib.metadata import PackageNotFoundError, version as distribution_version
20
+ from pathlib import Path, PurePosixPath, PureWindowsPath
21
+
22
+ type _Package = Callable[[Path, Path, Path, str], Path]
23
+
24
+ _PRODUCT_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}")
25
+ _CALVER = re.compile(r"(\d{4})\.(\d{1,2})\.(\d+)")
26
+ _HARNESS_CLOCK_OFFSET = timedelta(hours=8)
27
+ _NODE_MAJOR = "22"
28
+ _PKG_TARGET = f"node{_NODE_MAJOR}-win-x64"
29
+ _PKG_HOSTS = {"linux", "darwin", "win32"}
30
+ _WINDOWS_X64 = {"amd64", "x86_64"}
31
+ _CMD_SUFFIXES = {".cmd", ".bat"}
32
+ _MANIFEST_FIELDS = (
33
+ "artifact",
34
+ "backend",
35
+ "backend_version",
36
+ "build_host_architecture",
37
+ "build_host_platform",
38
+ "checksum_sha256",
39
+ "commit",
40
+ "product",
41
+ "signature",
42
+ "tag",
43
+ "target",
44
+ "target_architecture",
45
+ "target_platform",
46
+ "tool_versions",
47
+ "version",
48
+ )
49
+ _HOST_ARCHITECTURES = {
50
+ "amd64": "amd64",
51
+ "x86_64": "amd64",
52
+ "arm64": "arm64",
53
+ "aarch64": "arm64",
54
+ "x86": "x86",
55
+ "i386": "x86",
56
+ "i686": "x86",
57
+ }
58
+ _BACKDOOR_TOP_KEYS = {"product", "output", "pyinstaller", "pkg"}
59
+ _PYINSTALLER_KEYS = {"pin", "hidden-imports", "resources"}
60
+ _PKG_KEYS = {"pin", "public-packages", "bytecode", "public", "compress", "config"}
61
+ _COMPRESSIONS = {"Brotli", "GZip", "Zstd", "None"}
62
+ _MODULE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*")
63
+ _BACKDOOR_CALL_KEYS = {
64
+ "entrypoint",
65
+ "target",
66
+ "backend",
67
+ "architecture",
68
+ "runner",
69
+ "signing",
70
+ "signing-command",
71
+ "pre-ship",
72
+ "pre-ship-command",
73
+ }
74
+
75
+
76
+ class BuildError(Exception):
77
+ """The build stopped before an executable was published."""
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class _Release:
82
+ """The release identity read from a clean HEAD carrying only the product v* tag."""
83
+
84
+ tag: str
85
+ version: str
86
+ commit: str
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class _Packager:
91
+ """The gated packaging backend: the packaging step and its installed tool version."""
92
+
93
+ package: _Package
94
+ tool_version: Callable[[], str]
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class _Backdoor:
99
+ """Overrides from the optional xharness.toml at the product root."""
100
+
101
+ product: str | None = None
102
+ output: Path | None = None
103
+ hidden_imports: tuple[str, ...] = ()
104
+ resources: tuple[tuple[str, str], ...] = ()
105
+ pkg_args: tuple[str, ...] = ()
106
+
107
+
108
+ def _read_backdoor(root: Path) -> _Backdoor:
109
+ path = root / "xharness.toml"
110
+ if not path.is_file():
111
+ return _Backdoor()
112
+ text = path.read_text(encoding="utf-8")
113
+ if text.strip() == "":
114
+ return _Backdoor()
115
+ try:
116
+ parsed = tomllib.loads(text)
117
+ except tomllib.TOMLDecodeError as error:
118
+ raise BuildError(f"xharness.toml is not valid TOML: {error}") from error
119
+ _check_backdoor_keys(parsed, _BACKDOOR_TOP_KEYS)
120
+ pyinstaller = _backdoor_table(parsed, "pyinstaller", _PYINSTALLER_KEYS)
121
+ pkg = _backdoor_table(parsed, "pkg", _PKG_KEYS)
122
+ # A dev build ignores tool pins; the release workflow honors them.
123
+ _backdoor_text(pyinstaller, "pin")
124
+ _backdoor_text(pkg, "pin")
125
+ output = _backdoor_text(parsed, "output")
126
+ return _Backdoor(
127
+ product=_backdoor_text(parsed, "product"),
128
+ output=None if output is None else Path(output),
129
+ hidden_imports=_backdoor_hidden_imports(pyinstaller),
130
+ resources=_backdoor_resources(root, pyinstaller),
131
+ pkg_args=_backdoor_pkg_args(root, pkg),
132
+ )
133
+
134
+
135
+ def _backdoor_hidden_imports(table: dict[str, object]) -> tuple[str, ...]:
136
+ value = table.get("hidden-imports")
137
+ if value is None:
138
+ return ()
139
+ if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
140
+ raise BuildError("xharness.toml hidden-imports must be a list of Python module names.")
141
+ for item in value:
142
+ if not _MODULE_NAME.fullmatch(item):
143
+ raise BuildError(f"xharness.toml hidden-imports entry {item!r} is not a Python module name.")
144
+ return tuple(value)
145
+
146
+
147
+ def _backdoor_resources(root: Path, table: dict[str, object]) -> tuple[tuple[str, str], ...]:
148
+ value = table.get("resources")
149
+ if value is None:
150
+ return ()
151
+ if not isinstance(value, list):
152
+ raise BuildError("xharness.toml resources must be a list of source/destination pairs.")
153
+ pairs: list[tuple[str, str]] = []
154
+ for item in value:
155
+ fields = item if isinstance(item, dict) else {}
156
+ source, destination = fields.get("source"), fields.get("destination")
157
+ if (
158
+ set(fields) != {"source", "destination"}
159
+ or not isinstance(source, str)
160
+ or source.strip() == ""
161
+ or not isinstance(destination, str)
162
+ or destination.strip() == ""
163
+ ):
164
+ raise BuildError("An xharness.toml resource must name a source and a destination.")
165
+ source_path = _inside_file(root, source, "resource")
166
+ _target_relative_path(destination, "resource destination")
167
+ if os.pathsep in f"{source_path}{destination}":
168
+ raise BuildError(
169
+ f"Resource {source!r} cannot be passed to PyInstaller because its path contains {os.pathsep!r}."
170
+ )
171
+ pairs.append((source, destination))
172
+ return tuple(pairs)
173
+
174
+
175
+ def _backdoor_pkg_args(root: Path, table: dict[str, object]) -> tuple[str, ...]:
176
+ args: list[str] = []
177
+ if _backdoor_flag(table, "bytecode") is False:
178
+ args.append("--no-bytecode")
179
+ if _backdoor_flag(table, "public") is True:
180
+ args.append("--public")
181
+ public_packages = _backdoor_text(table, "public-packages")
182
+ if public_packages is not None:
183
+ args.extend(["--public-packages", public_packages])
184
+ compress = _backdoor_text(table, "compress")
185
+ if compress is not None:
186
+ if compress not in _COMPRESSIONS:
187
+ raise BuildError(f"xharness.toml compress {compress!r} is not one of Brotli, GZip, Zstd, None.")
188
+ args.extend(["--compress", compress])
189
+ config = _backdoor_text(table, "config")
190
+ if config is not None:
191
+ args.extend(["--config", str(_inside_file(root, config, "pkg config"))])
192
+ return tuple(args)
193
+
194
+
195
+ def _backdoor_flag(table: dict[str, object], key: str) -> bool | None:
196
+ value = table.get(key)
197
+ if value is None:
198
+ return None
199
+ if not isinstance(value, bool):
200
+ raise BuildError(f"xharness.toml key {key!r} must be true or false.")
201
+ return value
202
+
203
+
204
+ def _backdoor_table(parsed: dict[str, object], key: str, allowed: set[str]) -> dict[str, object]:
205
+ value = parsed.get(key)
206
+ if value is None:
207
+ return {}
208
+ if not isinstance(value, dict):
209
+ raise BuildError(f"xharness.toml section {key!r} must be a table.")
210
+ _check_backdoor_keys(value, allowed)
211
+ return value
212
+
213
+
214
+ def _check_backdoor_keys(table: dict[str, object], allowed: set[str]) -> None:
215
+ for key in table:
216
+ if key.lower().replace("_", "-") in _BACKDOOR_CALL_KEYS:
217
+ raise BuildError(
218
+ f"xharness.toml cannot set {key!r}. The entrypoint, target, backend, architecture, "
219
+ "runner, signing command, and pre-ship command stay on the call."
220
+ )
221
+ if key not in allowed:
222
+ raise BuildError(f"Unknown xharness.toml key {key!r}.")
223
+
224
+
225
+ def _backdoor_text(table: dict[str, object], key: str) -> str | None:
226
+ value = table.get(key)
227
+ if value is None:
228
+ return None
229
+ if not isinstance(value, str) or value.strip() == "":
230
+ raise BuildError(f"xharness.toml key {key!r} must be a non-empty string.")
231
+ return value
232
+
233
+
234
+ @dataclass(frozen=True)
235
+ class BuildRequest:
236
+ """A Windows build: an entrypoint, an optional output directory, an optional signing command."""
237
+
238
+ entrypoint: str
239
+ output: Path | None = None
240
+ signing_command: tuple[str, ...] | None = None
241
+
242
+ def __post_init__(self) -> None:
243
+ if self.output is not None:
244
+ if str(self.output).strip() == "":
245
+ raise BuildError("The output directory must be a non-empty path.")
246
+ object.__setattr__(self, "output", Path(self.output).expanduser())
247
+ if self.signing_command is not None:
248
+ object.__setattr__(self, "signing_command", tuple(self.signing_command))
249
+
250
+
251
+ def build(request: BuildRequest) -> Path:
252
+ """Build the Windows executable named by the source state and return its path.
253
+
254
+ The current directory is the product root. A ``.py`` entrypoint takes the
255
+ product name from ``pyproject.toml`` and packages with PyInstaller, which
256
+ runs on 64-bit Windows only. Any other entrypoint takes the ``package.json``
257
+ name without a single leading scope and packages with an installed ``pkg``.
258
+ An optional ``xharness.toml`` at the product root overrides the product
259
+ name, the output directory, Python hidden imports and resource pairs, and
260
+ the documented ``pkg`` options; a tool pin in the file stays with the
261
+ release workflow, and an output directory on the call wins over the file.
262
+
263
+ A clean ``HEAD`` whose only tag is ``v`` plus the product CalVer publishes
264
+ the release trio: ``{product}-{version}-win-windows-x64.exe``, its
265
+ manifest, and its SHA-256 checksum, where the version is the tag without
266
+ the ``v``. The trio appears together; a failure removes any partial set.
267
+ Any other source state writes ``{product}-win-x64-{YYYYMMDDTHHMMSS}-dev.exe``
268
+ on the harness clock, UTC+08:00. The dev build writes no manifest and no
269
+ checksum, keeps older dev executables, and downloads neither a packaging
270
+ tool nor the Windows Node base binary.
271
+ """
272
+
273
+ if request.signing_command is not None:
274
+ _validate_signing(request.signing_command)
275
+ root = Path.cwd().resolve()
276
+ entrypoint = _inside_file(root, request.entrypoint, "entrypoint")
277
+ backend = "pyinstaller" if entrypoint.name.lower().endswith(".py") else "pkg"
278
+ backdoor = _read_backdoor(root)
279
+ product = _check_product_name(
280
+ backdoor.product if backdoor.product is not None else _product_name(root, backend)
281
+ )
282
+ output = _output_path(root, request.output if request.output is not None else backdoor.output)
283
+ release = _release_identity(root)
284
+ stem = (
285
+ f"{product}-{release.version}-win-windows-x64"
286
+ if release is not None
287
+ else f"{product}-win-x64-{_dev_timestamp()}-dev"
288
+ )
289
+ packager: _Packager = (
290
+ _gate_pyinstaller(backdoor.hidden_imports, backdoor.resources)
291
+ if backend == "pyinstaller"
292
+ else _gate_pkg(backdoor.pkg_args)
293
+ )
294
+ output.mkdir(parents=True, exist_ok=True)
295
+ stage = output / f".xharness-stage-{uuid.uuid4().hex}"
296
+ stage.mkdir()
297
+ try:
298
+ executable = packager.package(root, entrypoint, stage, stem)
299
+ if request.signing_command is not None:
300
+ _run_signing_command(request.signing_command, executable)
301
+ if release is None:
302
+ destination = output / f"{stem}.exe"
303
+ os.replace(executable, destination)
304
+ else:
305
+ destination = _publish_release(
306
+ stage,
307
+ output,
308
+ stem,
309
+ executable,
310
+ release=release,
311
+ product=product,
312
+ backend=backend,
313
+ tool_version=packager.tool_version(),
314
+ signed=request.signing_command is not None,
315
+ )
316
+ except BuildError:
317
+ raise
318
+ except OSError as error:
319
+ raise BuildError(str(error)) from error
320
+ finally:
321
+ shutil.rmtree(stage, ignore_errors=True)
322
+ if release is not None and stage.exists():
323
+ _remove_output_names(output, _release_filenames(stem))
324
+ raise BuildError("The build stage could not be removed. Partial outputs were removed.")
325
+ return destination
326
+
327
+
328
+ def main(argv: list[str] | None = None) -> None:
329
+ """CLI entry for the `xharness-build` script."""
330
+
331
+ parser = argparse.ArgumentParser(description="Build the Windows product executable named by the source state.")
332
+ parser.add_argument("--entrypoint", required=True)
333
+ parser.add_argument("--output", type=Path)
334
+ parser.add_argument(
335
+ "--signing-arg",
336
+ action="append",
337
+ dest="signing_command",
338
+ help="Repeat for each argument of a product-owned signing command. The executable path is appended.",
339
+ )
340
+ args = parser.parse_args(argv)
341
+ try:
342
+ path = build(
343
+ BuildRequest(
344
+ entrypoint=args.entrypoint,
345
+ output=args.output,
346
+ signing_command=None if args.signing_command is None else tuple(args.signing_command),
347
+ )
348
+ )
349
+ except BuildError as error:
350
+ print(error, file=sys.stderr)
351
+ raise SystemExit(1) from error
352
+ print(path)
353
+
354
+
355
+ def _relative_path(value: str, label: str) -> Path:
356
+ path = Path(value)
357
+ if value == "" or path.is_absolute() or ".." in path.parts:
358
+ raise BuildError(f"The {label} {value!r} must be a relative path inside the product root.")
359
+ return path
360
+
361
+
362
+ def _target_relative_path(value: str, label: str) -> None:
363
+ # A resource destination is consumed on the Windows target, so check both path dialects.
364
+ # Python 3.13 treats a drive without a root, such as C:assets, as not absolute.
365
+ windows = PureWindowsPath(value)
366
+ if (
367
+ windows.drive
368
+ or windows.root
369
+ or PurePosixPath(value).is_absolute()
370
+ or ".." in value.replace("\\", "/").split("/")
371
+ ):
372
+ raise BuildError(f"The {label} {value!r} must be a relative path inside the product root.")
373
+
374
+
375
+ def _is_inside(root: Path, path: Path) -> bool:
376
+ try:
377
+ path.relative_to(root)
378
+ except ValueError:
379
+ return False
380
+ return True
381
+
382
+
383
+ def _inside_file(root: Path, value: str, label: str) -> Path:
384
+ relative = _relative_path(value, label)
385
+ path = (root / relative).resolve()
386
+ if not _is_inside(root, path) or not path.is_file():
387
+ raise BuildError(f"The {label} {value!r} must be a file inside the product root.")
388
+ return path
389
+
390
+
391
+ def _validate_signing(command: tuple[str, ...]) -> None:
392
+ if not command or any(argument == "" for argument in command):
393
+ raise BuildError("Signing is unsigned by default. Provide a product-owned signing command, or omit it.")
394
+
395
+
396
+ def _product_name(root: Path, backend: str) -> str:
397
+ if backend == "pyinstaller":
398
+ text = _manifest_text(root, "pyproject.toml")
399
+ try:
400
+ parsed = tomllib.loads(text)
401
+ except tomllib.TOMLDecodeError as error:
402
+ raise BuildError(f"pyproject.toml is not valid TOML: {error}") from error
403
+ project = parsed.get("project")
404
+ name = project.get("name") if isinstance(project, dict) else None
405
+ if not isinstance(name, str) or name.strip() == "":
406
+ raise BuildError("pyproject.toml is missing [project] name.")
407
+ return name
408
+ text = _manifest_text(root, "package.json")
409
+ try:
410
+ parsed = json.loads(text)
411
+ except json.JSONDecodeError as error:
412
+ raise BuildError(f"package.json is not valid JSON: {error}") from error
413
+ name = parsed.get("name") if isinstance(parsed, dict) else None
414
+ if not isinstance(name, str) or name.strip() == "":
415
+ raise BuildError("package.json is missing a name.")
416
+ return re.sub(r"^@[^/]+/", "", name, count=1)
417
+
418
+
419
+ def _manifest_text(root: Path, name: str) -> str:
420
+ manifest = root / name
421
+ if not manifest.is_file():
422
+ raise BuildError(f"{name} is missing. The current directory is the product root.")
423
+ return manifest.read_text(encoding="utf-8")
424
+
425
+
426
+ def _check_product_name(name: str) -> str:
427
+ if not _PRODUCT_NAME.fullmatch(name):
428
+ raise BuildError(
429
+ f"Product {name!r} must be a file-safe identity "
430
+ "of letters, digits, dots, underscores, or hyphens."
431
+ )
432
+ return name
433
+
434
+
435
+ def _output_path(root: Path, value: Path | None) -> Path:
436
+ output = value if value is not None else Path("dist")
437
+ if not output.is_absolute():
438
+ output = root / output
439
+ output = output.resolve()
440
+ if output.exists() and not output.is_dir():
441
+ raise BuildError(f"Output directory {output} is not a directory.")
442
+ return output
443
+
444
+
445
+ def _dev_timestamp() -> str:
446
+ shifted = datetime.now(timezone.utc) + _HARNESS_CLOCK_OFFSET
447
+ return shifted.strftime("%Y%m%dT%H%M%S")
448
+
449
+
450
+ def _gate_pyinstaller(hidden_imports: tuple[str, ...], resources: tuple[tuple[str, str], ...]) -> _Packager:
451
+ if sys.platform != "win32" or platform.machine().lower() not in _WINDOWS_X64:
452
+ raise BuildError(
453
+ "PyInstaller packaging runs on 64-bit Windows. "
454
+ f"This host is {sys.platform} ({platform.machine()})."
455
+ )
456
+ version = _installed_pyinstaller_version()
457
+
458
+ def package(root: Path, entrypoint: Path, stage: Path, stem: str) -> Path:
459
+ return _run_pyinstaller(root, entrypoint, stage, stem, hidden_imports, resources)
460
+
461
+ return _Packager(package=package, tool_version=lambda: version)
462
+
463
+
464
+ def _installed_pyinstaller_version() -> str:
465
+ try:
466
+ installed = distribution_version("pyinstaller")
467
+ except PackageNotFoundError as error:
468
+ raise BuildError(
469
+ "PyInstaller is not installed in this environment. "
470
+ "Install PyInstaller 6 or newer. "
471
+ "Packaging tools are not downloaded."
472
+ ) from error
473
+ major = _version_major(installed)
474
+ if major is None or major < 6:
475
+ raise BuildError(
476
+ f"PyInstaller {installed} is not supported. Install PyInstaller 6 or newer. "
477
+ "Packaging tools are not downloaded."
478
+ )
479
+ return installed
480
+
481
+
482
+ def _version_major(installed: str) -> int | None:
483
+ match = re.match(r"(\d+)", installed)
484
+ if match is None:
485
+ return None
486
+ return int(match.group(1))
487
+
488
+
489
+ def _gate_pkg(pkg_args: tuple[str, ...]) -> _Packager:
490
+ if sys.platform not in _PKG_HOSTS:
491
+ raise BuildError(
492
+ f"Unsupported build host {sys.platform!r}. "
493
+ "Node pkg builds the Windows target on linux, darwin, and win32."
494
+ )
495
+ tool = shutil.which("pkg")
496
+ if tool is None:
497
+ raise BuildError("pkg is not installed. Install pkg explicitly. xharness does not download it.")
498
+ _require_base_binary()
499
+
500
+ def package(root: Path, entrypoint: Path, stage: Path, stem: str) -> Path:
501
+ return _run_pkg(root, entrypoint, stage, Path(tool), stem, pkg_args)
502
+
503
+ return _Packager(package=package, tool_version=lambda: _pkg_version(Path(tool)))
504
+
505
+
506
+ def _pkg_version(tool: Path) -> str:
507
+ completed = subprocess.run(
508
+ _tool_command(tool, ["--version"]),
509
+ text=True,
510
+ encoding="utf-8",
511
+ errors="replace",
512
+ capture_output=True,
513
+ check=False,
514
+ )
515
+ match = re.search(r"(\d+\.\d+\.\d+)", completed.stdout)
516
+ if completed.returncode != 0 or match is None:
517
+ detail = (completed.stderr or completed.stdout).strip()
518
+ raise BuildError(f"pkg did not report a version.\n{detail[-400:]}")
519
+ return match.group(1)
520
+
521
+
522
+ def _require_base_binary() -> None:
523
+ binary = f"node{_NODE_MAJOR} win-x64"
524
+ cache = os.environ.get("PKG_CACHE_PATH", "").strip()
525
+ if cache == "":
526
+ raise BuildError(
527
+ f"Node base binary for {binary} is not installed. "
528
+ "Set PKG_CACHE_PATH to a directory that already contains it. xharness does not download it."
529
+ )
530
+ marker = f"fetched-v{_NODE_MAJOR}."
531
+ suffix = "-win-x64"
532
+ root = Path(cache)
533
+ found = root.is_dir() and any(
534
+ path.is_file() and path.name.startswith(marker) and path.name.endswith(suffix)
535
+ for path in root.rglob("*")
536
+ )
537
+ if not found:
538
+ raise BuildError(
539
+ f"Node base binary for {binary} is not in {cache}. "
540
+ "Prefetch it with the pinned pkg-fetch before building. xharness does not download it."
541
+ )
542
+
543
+
544
+ def _run_pyinstaller(
545
+ root: Path,
546
+ entrypoint: Path,
547
+ stage: Path,
548
+ stem: str,
549
+ hidden_imports: tuple[str, ...],
550
+ resources: tuple[tuple[str, str], ...],
551
+ ) -> Path:
552
+ dist = stage / "dist"
553
+ work = stage / "work"
554
+ dist.mkdir()
555
+ work.mkdir()
556
+ command = [
557
+ sys.executable,
558
+ "-m",
559
+ "PyInstaller",
560
+ "--noconfirm",
561
+ "--clean",
562
+ "--noupx",
563
+ "--onefile",
564
+ "--name",
565
+ stem,
566
+ "--distpath",
567
+ str(dist),
568
+ "--workpath",
569
+ str(work),
570
+ "--specpath",
571
+ str(work),
572
+ ]
573
+ for hidden_import in hidden_imports:
574
+ command.extend(["--hidden-import", hidden_import])
575
+ for source, destination in resources:
576
+ command.extend(["--add-data", f"{(root / source).resolve()}{os.pathsep}{destination}"])
577
+ command.append(str(entrypoint))
578
+ completed = subprocess.run(
579
+ command,
580
+ cwd=root,
581
+ text=True,
582
+ encoding="utf-8",
583
+ errors="replace",
584
+ capture_output=True,
585
+ check=False,
586
+ )
587
+ executable = dist / f"{stem}.exe"
588
+ if completed.returncode != 0 or not executable.is_file():
589
+ detail = (completed.stderr or completed.stdout).strip()
590
+ raise BuildError(f"PyInstaller failed to build {stem}.exe.\n{detail[-2000:]}")
591
+ return executable
592
+
593
+
594
+ def _run_pkg(root: Path, entrypoint: Path, stage: Path, tool: Path, stem: str, pkg_args: tuple[str, ...]) -> Path:
595
+ artifact = f"{stem}.exe"
596
+ executable = stage / artifact
597
+ command = _tool_command(
598
+ tool, [str(entrypoint), "--targets", _PKG_TARGET, "--output", str(executable), *pkg_args]
599
+ )
600
+ completed = subprocess.run(
601
+ command,
602
+ cwd=root,
603
+ text=True,
604
+ encoding="utf-8",
605
+ errors="replace",
606
+ capture_output=True,
607
+ check=False,
608
+ )
609
+ if completed.returncode != 0 or not executable.is_file():
610
+ detail = (completed.stderr or completed.stdout).strip()
611
+ raise BuildError(f"pkg failed to build {artifact}.\n{detail[-2000:]}")
612
+ return executable
613
+
614
+
615
+ def _tool_command(tool: Path, args: list[str]) -> list[str]:
616
+ if sys.platform == "win32" and tool.suffix.lower() in _CMD_SUFFIXES:
617
+ command = " ".join(_cmd_quote(value) for value in [str(tool), *args])
618
+ return [os.environ.get("ComSpec") or "cmd.exe", "/d", "/s", "/c", f'"{command}"']
619
+ return [str(tool), *args]
620
+
621
+
622
+ def _cmd_quote(value: str) -> str:
623
+ return '"' + value.replace("%", "%%").replace('"', '""') + '"'
624
+
625
+
626
+ def _run_signing_command(command: tuple[str, ...], executable: Path) -> None:
627
+ completed = subprocess.run(
628
+ [*command, str(executable)],
629
+ text=True,
630
+ encoding="utf-8",
631
+ errors="replace",
632
+ capture_output=True,
633
+ check=False,
634
+ )
635
+ if completed.returncode != 0:
636
+ raise BuildError(
637
+ "The product signing command failed. "
638
+ "No signing credential is stored. "
639
+ f"The command exited {completed.returncode}."
640
+ )
641
+
642
+
643
+ def _release_identity(root: Path) -> _Release | None:
644
+ try:
645
+ probe = _git_optional(root, ["rev-parse", "--is-inside-work-tree"])
646
+ if probe is None or probe.strip() != "true":
647
+ return None
648
+ status = _git(root, ["status", "--porcelain", "--untracked-files=all", "--", "."])
649
+ if status.strip():
650
+ return None
651
+ commit = _git(root, ["rev-parse", "HEAD"]).strip()
652
+ names = [line.strip() for line in _git(root, ["tag", "--points-at", "HEAD"]).splitlines() if line.strip()]
653
+ except BuildError:
654
+ return None
655
+ if len(names) != 1:
656
+ return None
657
+ tag = names[0]
658
+ if not tag.startswith("v") or not _is_calver(tag[1:]):
659
+ return None
660
+ return _Release(tag=tag, version=tag[1:], commit=commit)
661
+
662
+
663
+ def _is_calver(version: str) -> bool:
664
+ match = _CALVER.fullmatch(version)
665
+ if match is None:
666
+ return False
667
+ month, counter = match.group(2), match.group(3)
668
+ if str(int(month)) != month or str(int(counter)) != counter:
669
+ return False
670
+ return 1 <= int(month) <= 12
671
+
672
+
673
+ def _publish_release(
674
+ stage: Path,
675
+ output: Path,
676
+ stem: str,
677
+ executable: Path,
678
+ *,
679
+ release: _Release,
680
+ product: str,
681
+ backend: str,
682
+ tool_version: str,
683
+ signed: bool,
684
+ ) -> Path:
685
+ publish = stage / "publish"
686
+ publish.mkdir()
687
+ artifact = f"{stem}.exe"
688
+ destination = publish / artifact
689
+ os.replace(executable, destination)
690
+ digest = _sha256(destination)
691
+ manifest = {
692
+ "artifact": artifact,
693
+ "backend": backend,
694
+ "backend_version": tool_version,
695
+ "build_host_architecture": _host_architecture(),
696
+ "build_host_platform": "win" if sys.platform == "win32" else sys.platform,
697
+ "checksum_sha256": digest,
698
+ "commit": release.commit,
699
+ "product": product,
700
+ "signature": "signed" if signed else "unsigned",
701
+ "tag": release.tag,
702
+ "target": "win",
703
+ "target_architecture": "amd64",
704
+ "target_platform": "win",
705
+ "tool_versions": {backend: tool_version},
706
+ "version": release.version,
707
+ }
708
+ manifest_path = publish / f"{stem}.manifest.json"
709
+ checksum_path = publish / f"{stem}.sha256"
710
+ manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
711
+ checksum_path.write_text(f"{digest} {artifact}\n", encoding="utf-8", newline="\n")
712
+ _verify_evidence(publish, stem, digest)
713
+ _publish(publish, output, _release_filenames(stem))
714
+ return output / artifact
715
+
716
+
717
+ def _host_architecture() -> str:
718
+ machine = platform.machine().lower()
719
+ return _HOST_ARCHITECTURES.get(machine, machine)
720
+
721
+
722
+ def _verify_evidence(publish: Path, stem: str, digest: str) -> None:
723
+ artifact = f"{stem}.exe"
724
+ if _sha256(publish / artifact) != digest:
725
+ raise BuildError("The executable checksum does not match the evidence. Nothing was published.")
726
+ checksum_text = (publish / f"{stem}.sha256").read_text(encoding="utf-8")
727
+ if checksum_text != f"{digest} {artifact}\n":
728
+ raise BuildError("The checksum file does not match the executable. Nothing was published.")
729
+ loaded = json.loads((publish / f"{stem}.manifest.json").read_text(encoding="utf-8"))
730
+ if set(loaded) != set(_MANIFEST_FIELDS):
731
+ raise BuildError("The manifest is missing release evidence. Nothing was published.")
732
+ if loaded["artifact"] != artifact or loaded["checksum_sha256"] != digest:
733
+ raise BuildError("The manifest does not match the executable. Nothing was published.")
734
+ if loaded["signature"] not in {"signed", "unsigned"}:
735
+ raise BuildError("The manifest signature status is not signed or unsigned. Nothing was published.")
736
+
737
+
738
+ def _release_filenames(stem: str) -> tuple[str, str, str]:
739
+ return (f"{stem}.exe", f"{stem}.manifest.json", f"{stem}.sha256")
740
+
741
+
742
+ def _publish(publish: Path, output: Path, names: tuple[str, ...]) -> None:
743
+ incoming: list[Path] = []
744
+ try:
745
+ for name in names:
746
+ temporary = output / f".{name}.incoming"
747
+ os.replace(publish / name, temporary)
748
+ incoming.append(temporary)
749
+ for temporary, name in zip(incoming, names, strict=True):
750
+ os.replace(temporary, output / name)
751
+ except OSError as error:
752
+ _remove_output_names(output, names)
753
+ raise BuildError("Publishing the verified set failed. Partial outputs were removed.") from error
754
+
755
+
756
+ def _remove_output_names(output: Path, names: tuple[str, ...]) -> None:
757
+ for name in names:
758
+ (output / name).unlink(missing_ok=True)
759
+ (output / f".{name}.incoming").unlink(missing_ok=True)
760
+
761
+
762
+ def _sha256(path: Path) -> str:
763
+ digest = hashlib.sha256()
764
+ with path.open("rb") as handle:
765
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
766
+ digest.update(chunk)
767
+ return digest.hexdigest()
768
+
769
+
770
+ def _git(root: Path, args: list[str]) -> str:
771
+ completed = _git_command(root, args)
772
+ if completed.returncode != 0:
773
+ detail = (completed.stderr or completed.stdout).strip() or f"git {' '.join(args)} failed"
774
+ raise BuildError(detail)
775
+ return completed.stdout
776
+
777
+
778
+ def _git_optional(root: Path, args: list[str]) -> str | None:
779
+ completed = _git_command(root, args)
780
+ if completed.returncode != 0:
781
+ return None
782
+ return completed.stdout
783
+
784
+
785
+ def _git_command(root: Path, args: list[str]) -> subprocess.CompletedProcess[str]:
786
+ env = os.environ.copy()
787
+ env["GIT_TERMINAL_PROMPT"] = "0"
788
+ for variable in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_PREFIX"):
789
+ env.pop(variable, None)
790
+ try:
791
+ return subprocess.run(
792
+ ["git", "-c", "color.ui=false", "-c", "safe.directory=*", "-c", "core.autocrlf=false", *args],
793
+ cwd=root,
794
+ env=env,
795
+ text=True,
796
+ encoding="utf-8",
797
+ errors="replace",
798
+ capture_output=True,
799
+ check=False,
800
+ )
801
+ except FileNotFoundError as error:
802
+ raise BuildError("git is required to read the product tag and commit.") from error
@@ -0,0 +1,6 @@
1
+ """Environment detection for light* apps (stub)."""
2
+
3
+
4
+ def runtime_name() -> str:
5
+ """Return a short name for the current runtime (dev, test, packaged, etc.)."""
6
+ raise NotImplementedError("xharness.env.runtime_name is not implemented yet")
@@ -0,0 +1,6 @@
1
+ """Logging helpers for light* apps (stub)."""
2
+
3
+
4
+ def configure() -> None:
5
+ """Apply default logging configuration."""
6
+ raise NotImplementedError("xharness.logging.configure is not implemented yet")