codecin 7.22.10__py3-none-win_amd64.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.
- codecin/__init__.py +27 -0
- codecin/aot.py +1057 -0
- codecin/assembler.py +619 -0
- codecin/cbackend.py +3024 -0
- codecin/cin.py +4265 -0
- codecin/cli.py +670 -0
- codecin/codecin_native.dll +0 -0
- codecin/config.py +50 -0
- codecin/console.py +183 -0
- codecin/cpu.py +312 -0
- codecin/crom.py +449 -0
- codecin/cvm.py +708 -0
- codecin/disasm.py +149 -0
- codecin/environment.py +176 -0
- codecin/errors.py +54 -0
- codecin/isa.py +560 -0
- codecin/lib/array/pic.toml +10 -0
- codecin/lib/array/src/array.cin +103 -0
- codecin/lib/bigint/pic.toml +10 -0
- codecin/lib/bigint/src/bigint.cin +589 -0
- codecin/lib/bits/pic.toml +10 -0
- codecin/lib/bits/src/bits.cin +143 -0
- codecin/lib/bitset/pic.toml +10 -0
- codecin/lib/bitset/src/bitset.cin +374 -0
- codecin/lib/codec/pic.toml +10 -0
- codecin/lib/codec/src/codec.cin +563 -0
- codecin/lib/combin/pic.toml +10 -0
- codecin/lib/combin/src/combin.cin +414 -0
- codecin/lib/conv/pic.toml +10 -0
- codecin/lib/conv/src/conv.cin +151 -0
- codecin/lib/cppstd/pic.toml +10 -0
- codecin/lib/cppstd/src/cppstd.cin +418 -0
- codecin/lib/cstd/pic.toml +10 -0
- codecin/lib/cstd/src/cstd.cin +424 -0
- codecin/lib/csv/pic.toml +10 -0
- codecin/lib/csv/src/csv.cin +405 -0
- codecin/lib/dp/pic.toml +10 -0
- codecin/lib/dp/src/dp.cin +325 -0
- codecin/lib/ffi/pic.toml +10 -0
- codecin/lib/ffi/src/ffi.cin +163 -0
- codecin/lib/fmt/pic.toml +10 -0
- codecin/lib/fmt/src/fmt.cin +325 -0
- codecin/lib/frac/pic.toml +10 -0
- codecin/lib/frac/src/frac.cin +252 -0
- codecin/lib/gostd/pic.toml +10 -0
- codecin/lib/gostd/src/gostd.cin +415 -0
- codecin/lib/graph/pic.toml +10 -0
- codecin/lib/graph/src/graph.cin +367 -0
- codecin/lib/gui/pic.toml +10 -0
- codecin/lib/gui/src/gui.cin +218 -0
- codecin/lib/hash/pic.toml +10 -0
- codecin/lib/hash/src/hash.cin +67 -0
- codecin/lib/heap/pic.toml +10 -0
- codecin/lib/heap/src/heap.cin +199 -0
- codecin/lib/io/pic.toml +10 -0
- codecin/lib/io/src/io.cin +141 -0
- codecin/lib/json/pic.toml +10 -0
- codecin/lib/json/src/json.cin +84 -0
- codecin/lib/key/pic.toml +10 -0
- codecin/lib/key/src/key.cin +78 -0
- codecin/lib/math/pic.toml +10 -0
- codecin/lib/math/src/math.cin +50 -0
- codecin/lib/matrix/pic.toml +10 -0
- codecin/lib/matrix/src/matrix.cin +155 -0
- codecin/lib/net/pic.toml +10 -0
- codecin/lib/net/src/net.cin +171 -0
- codecin/lib/path/pic.toml +10 -0
- codecin/lib/path/src/path.cin +372 -0
- codecin/lib/queue/pic.toml +10 -0
- codecin/lib/queue/src/queue.cin +112 -0
- codecin/lib/rand/pic.toml +10 -0
- codecin/lib/rand/src/rand.cin +46 -0
- codecin/lib/set/pic.toml +10 -0
- codecin/lib/set/src/set.cin +269 -0
- codecin/lib/sort/pic.toml +10 -0
- codecin/lib/sort/src/sort.cin +93 -0
- codecin/lib/stat/pic.toml +10 -0
- codecin/lib/stat/src/stat.cin +138 -0
- codecin/lib/str/pic.toml +10 -0
- codecin/lib/str/src/str.cin +54 -0
- codecin/lib/termux/pic.toml +10 -0
- codecin/lib/termux/src/termux.cin +118 -0
- codecin/lib/test/pic.toml +10 -0
- codecin/lib/test/src/test.cin +74 -0
- codecin/lib/text/pic.toml +10 -0
- codecin/lib/text/src/text.cin +323 -0
- codecin/lib/time/pic.toml +10 -0
- codecin/lib/time/src/time.cin +54 -0
- codecin/lib/token/pic.toml +10 -0
- codecin/lib/token/src/token.cin +183 -0
- codecin/lib/tree/pic.toml +10 -0
- codecin/lib/tree/src/tree.cin +256 -0
- codecin/lib/unionfind/pic.toml +10 -0
- codecin/lib/unionfind/src/unionfind.cin +115 -0
- codecin/lib/validate/pic.toml +10 -0
- codecin/lib/validate/src/validate.cin +148 -0
- codecin/lib/vec/pic.toml +10 -0
- codecin/lib/vec/src/vec.cin +88 -0
- codecin/logger.py +145 -0
- codecin/memory.py +306 -0
- codecin/mkn.py +916 -0
- codecin/native/aot/aot.go +114 -0
- codecin/native/aot/stub_main.go.txt +23 -0
- codecin/native/build.ps1 +33 -0
- codecin/native/build.sh +48 -0
- codecin/native/cmd/cincc/main.go +66 -0
- codecin/native/compiler/codegen.go +2238 -0
- codecin/native/compiler/compile_test.go +1069 -0
- codecin/native/compiler/parser.go +1331 -0
- codecin/native/compiler/syscalls.go +166 -0
- codecin/native/compiler/tokenizer.go +394 -0
- codecin/native/compiler/types.go +217 -0
- codecin/native/engine/args.go +37 -0
- codecin/native/engine/audio.go +402 -0
- codecin/native/engine/audio_other.go +105 -0
- codecin/native/engine/audio_test.go +279 -0
- codecin/native/engine/audio_windows.go +190 -0
- codecin/native/engine/canvas.go +271 -0
- codecin/native/engine/console_other.go +9 -0
- codecin/native/engine/console_windows.go +43 -0
- codecin/native/engine/crom.go +86 -0
- codecin/native/engine/encode.go +93 -0
- codecin/native/engine/engine_test.go +198 -0
- codecin/native/engine/ffi_nocgo.go +20 -0
- codecin/native/engine/ffi_registry.go +69 -0
- codecin/native/engine/ffi_unix.go +109 -0
- codecin/native/engine/ffi_windows.go +117 -0
- codecin/native/engine/gui.go +209 -0
- codecin/native/engine/gui_stub.go +13 -0
- codecin/native/engine/gui_test.go +148 -0
- codecin/native/engine/gui_windows.go +604 -0
- codecin/native/engine/gui_x11.go +723 -0
- codecin/native/engine/host_test.go +139 -0
- codecin/native/engine/hostcrypto.go +30 -0
- codecin/native/engine/hostdesktop.go +173 -0
- codecin/native/engine/hostnet.go +127 -0
- codecin/native/engine/isa_gen.go +689 -0
- codecin/native/engine/keyboard.go +432 -0
- codecin/native/engine/keyboard_other.go +94 -0
- codecin/native/engine/keyboard_stub.go +17 -0
- codecin/native/engine/keyboard_termios_darwin.go +9 -0
- codecin/native/engine/keyboard_termios_linux.go +9 -0
- codecin/native/engine/keyboard_test.go +246 -0
- codecin/native/engine/keyboard_windows.go +208 -0
- codecin/native/engine/keyboard_windows_test.go +123 -0
- codecin/native/engine/lineedit.go +262 -0
- codecin/native/engine/lineedit_test.go +105 -0
- codecin/native/engine/lineint_unix.go +17 -0
- codecin/native/engine/lineint_windows.go +19 -0
- codecin/native/engine/mem_other.go +37 -0
- codecin/native/engine/mem_windows.go +33 -0
- codecin/native/engine/native.go +640 -0
- codecin/native/engine/netsock.go +321 -0
- codecin/native/engine/ops_ext.go +515 -0
- codecin/native/engine/stdin.go +72 -0
- codecin/native/engine/stdin_other.go +9 -0
- codecin/native/engine/stdin_windows.go +60 -0
- codecin/native/engine/system.go +313 -0
- codecin/native/engine/termux.go +180 -0
- codecin/native/engine/version_gen.go +7 -0
- codecin/native/engine/vkb_darwin.go +62 -0
- codecin/native/engine/vkb_linux.go +95 -0
- codecin/native/engine/vkb_stub.go +11 -0
- codecin/native/engine/vm.go +1677 -0
- codecin/native/go.mod +3 -0
- codecin/native/ir/ir.go +48 -0
- codecin/native/main.go +448 -0
- codecin/native/mc/aarch64.go +165 -0
- codecin/native/mc/aarch64_test.go +30 -0
- codecin/native/mc/elf.go +88 -0
- codecin/native/mc/print_test.go +52 -0
- codecin/native/mc/x86_64.go +1262 -0
- codecin/native/mc/x86_64_test.go +102 -0
- codecin/native.py +432 -0
- codecin/native_codegen.py +987 -0
- codecin/nativegen.py +786 -0
- codecin/object.py +539 -0
- codecin/optimizer.py +236 -0
- codecin/packaging/__init__.py +46 -0
- codecin/packaging/archive.py +177 -0
- codecin/packaging/model.py +519 -0
- codecin/packaging/spec.py +193 -0
- codecin/packaging/store.py +372 -0
- codecin/packaging/toml.py +541 -0
- codecin/packaging/vcs.py +215 -0
- codecin/pic.py +1917 -0
- codecin/pic_api.py +374 -0
- codecin/pic_login.py +519 -0
- codecin/pic_registry.py +515 -0
- codecin/registers.py +130 -0
- codecin/sdgcc.py +493 -0
- codecin/stats.py +230 -0
- codecin/stdlib.py +138 -0
- codecin/toolchain.py +396 -0
- codecin/toolkit.py +26 -0
- codecin/version.py +260 -0
- codecin-7.22.10.dist-info/METADATA +1077 -0
- codecin-7.22.10.dist-info/RECORD +202 -0
- codecin-7.22.10.dist-info/WHEEL +5 -0
- codecin-7.22.10.dist-info/entry_points.txt +5 -0
- codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
- codecin-7.22.10.dist-info/top_level.txt +1 -0
codecin/toolchain.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
"""AOT 工具链发现与获取 (GCC 家族, 支持交叉编译)。
|
|
2
|
+
|
|
3
|
+
AOT 后端不再调用 Go: 生成的 C 源码交给 GCC/Clang 编译成本机或交叉目标的
|
|
4
|
+
可执行文件。本模块只回答三个问题——**用哪个编译器、它是哪个目标、缺了怎么装**,
|
|
5
|
+
不负责生成代码 (见 :mod:`codecin.cbackend`)。
|
|
6
|
+
|
|
7
|
+
每个目标独立按下列顺序查找:
|
|
8
|
+
|
|
9
|
+
1. ``CODECIN_CC_<TARGET>`` (例如 ``CODECIN_CC_AARCH64_LINUX``);
|
|
10
|
+
2. ``CODECIN_CC``;
|
|
11
|
+
3. 自带工具链 ``$CODECIN_GCC_HOME`` / ``~/.codecin/gcc/<target>/bin/<prefix>gcc``;
|
|
12
|
+
4. PATH 中的目标专用驱动 (``aarch64-linux-gnu-gcc`` / ``x86_64-w64-mingw32-gcc``);
|
|
13
|
+
5. PATH 中的本机 ``gcc`` / ``clang``, 仅当 ``-dumpmachine`` 与目标匹配。
|
|
14
|
+
|
|
15
|
+
``python -m codecin.toolchain install <target> --url <压缩包>`` 可把交叉工具链
|
|
16
|
+
解包到 ``~/.codecin/gcc/<target>``; 未指定 ``--url`` 时使用 :data:`MIRROR` 的
|
|
17
|
+
约定路径。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import hashlib
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import shutil
|
|
24
|
+
import subprocess
|
|
25
|
+
import sys
|
|
26
|
+
import tarfile
|
|
27
|
+
import tempfile
|
|
28
|
+
import urllib.parse
|
|
29
|
+
import urllib.request
|
|
30
|
+
import zipfile
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from typing import Dict, List, Optional, Sequence, Tuple
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
'MIRROR',
|
|
36
|
+
'TARGETS',
|
|
37
|
+
'CompilerInfo',
|
|
38
|
+
'Target',
|
|
39
|
+
'ToolchainError',
|
|
40
|
+
'download',
|
|
41
|
+
'find_compiler',
|
|
42
|
+
'find_zig',
|
|
43
|
+
'get_target',
|
|
44
|
+
'hint',
|
|
45
|
+
'install_archive',
|
|
46
|
+
'mirror_url',
|
|
47
|
+
'probe',
|
|
48
|
+
'require',
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
#: 预编译 GCC 工具链镜像 (用户可自带; 也可用 ``--url`` 指定任意地址)。
|
|
52
|
+
MIRROR = 'https://mirror.marwan.ma/gcc/'
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ToolchainError(RuntimeError):
|
|
56
|
+
"""找不到可用的 C 编译器 / 工具链安装失败。"""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class Target:
|
|
61
|
+
"""一个 AOT 目标: 名字、GNU triple、可执行文件后缀、驱动前缀。"""
|
|
62
|
+
|
|
63
|
+
name: str
|
|
64
|
+
triple: str
|
|
65
|
+
exe: str
|
|
66
|
+
prefix: str
|
|
67
|
+
fmt: str
|
|
68
|
+
aliases: Tuple[str, ...] = ()
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def is_host(self) -> bool:
|
|
72
|
+
return self.triple == _host_triple()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
TARGETS: Dict[str, Target] = {
|
|
76
|
+
t.name: t for t in (
|
|
77
|
+
Target('x86_64-windows', 'x86_64-w64-mingw32', '.exe',
|
|
78
|
+
'x86_64-w64-mingw32-', 'pe',
|
|
79
|
+
('windows-x86_64', 'win64', 'windows')),
|
|
80
|
+
Target('x86_64-linux', 'x86_64-linux-gnu', '', 'x86_64-linux-gnu-',
|
|
81
|
+
'elf', ('linux-x86_64', 'linux', 'linux64')),
|
|
82
|
+
Target('aarch64-linux', 'aarch64-linux-gnu', '', 'aarch64-linux-gnu-',
|
|
83
|
+
'elf', ('linux-aarch64', 'arm64-linux', 'aarch64')),
|
|
84
|
+
Target('arm-linux', 'arm-linux-gnueabihf', '', 'arm-linux-gnueabihf-',
|
|
85
|
+
'elf', ('linux-arm', 'armv7-linux', 'arm32-linux', 'arm')),
|
|
86
|
+
Target('riscv64-linux', 'riscv64-linux-gnu', '', 'riscv64-linux-gnu-',
|
|
87
|
+
'elf', ('linux-riscv64', 'riscv64', 'riscv')),
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
_ALIASES = {alias: t.name for t in TARGETS.values() for alias in t.aliases}
|
|
92
|
+
_ALIASES.update({name: name for name in TARGETS})
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _host_triple() -> str:
|
|
96
|
+
"""本机 triple 的近似值 (只用于 ``Target.is_host`` 判断)。"""
|
|
97
|
+
system = sys.platform
|
|
98
|
+
machine = (os.environ.get('PROCESSOR_ARCHITECTURE') or '').lower()
|
|
99
|
+
try:
|
|
100
|
+
import platform
|
|
101
|
+
machine = platform.machine().lower()
|
|
102
|
+
except Exception: # noqa: BLE001 - 探测失败不影响交叉编译
|
|
103
|
+
pass
|
|
104
|
+
arch = 'aarch64' if machine in ('arm64', 'aarch64') else 'x86_64'
|
|
105
|
+
if system == 'win32':
|
|
106
|
+
return 'x86_64-w64-mingw32'
|
|
107
|
+
if system == 'darwin':
|
|
108
|
+
return f'{arch}-apple-darwin'
|
|
109
|
+
return f'{arch}-linux-gnu'
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def get_target(name: str) -> Target:
|
|
113
|
+
"""按名字或别名解析目标 (``linux-x86_64`` -> ``x86_64-linux``)。"""
|
|
114
|
+
key = (name or '').strip().lower()
|
|
115
|
+
resolved = _ALIASES.get(key)
|
|
116
|
+
if resolved is None:
|
|
117
|
+
raise ToolchainError(
|
|
118
|
+
f'未知 AOT 目标: {name!r} (可选: {", ".join(sorted(TARGETS))})')
|
|
119
|
+
return TARGETS[resolved]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def mirror_url(target: Target) -> str:
|
|
123
|
+
"""镜像上的约定路径 (压缩包内含 ``<target>/bin/...``)。"""
|
|
124
|
+
return urllib.parse.urljoin(MIRROR, f'{target.name}.tar.gz')
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _toolchain_root() -> str:
|
|
128
|
+
explicit = os.environ.get('CODECIN_GCC_HOME')
|
|
129
|
+
if explicit:
|
|
130
|
+
return os.path.abspath(explicit)
|
|
131
|
+
return os.path.join(os.path.expanduser('~'), '.codecin', 'gcc')
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def compiler_candidates(target: Target) -> List[str]:
|
|
135
|
+
"""按优先级返回候选编译器路径 (不保证存在)。"""
|
|
136
|
+
env_key = 'CODECIN_CC_' + re.sub(r'[^A-Z0-9]+', '_', target.name.upper())
|
|
137
|
+
paths: List[str] = []
|
|
138
|
+
for key in (env_key, 'CODECIN_CC'):
|
|
139
|
+
value = os.environ.get(key)
|
|
140
|
+
if value:
|
|
141
|
+
paths.append(value)
|
|
142
|
+
root = _toolchain_root()
|
|
143
|
+
for prefix in (os.path.join(root, target.name), root):
|
|
144
|
+
for name in (f'{target.prefix}gcc', f'{target.prefix}clang',
|
|
145
|
+
'gcc', 'cc', 'clang'):
|
|
146
|
+
paths.append(os.path.join(prefix, 'bin', name + '.exe'
|
|
147
|
+
if sys.platform == 'win32'
|
|
148
|
+
and not name.endswith('.exe') else name))
|
|
149
|
+
for name in (f'{target.prefix}gcc', f'{target.prefix}clang',
|
|
150
|
+
'gcc', 'cc', 'clang'):
|
|
151
|
+
found = shutil.which(name)
|
|
152
|
+
if found:
|
|
153
|
+
paths.append(found)
|
|
154
|
+
seen = set()
|
|
155
|
+
unique = []
|
|
156
|
+
for path in paths:
|
|
157
|
+
path = os.path.abspath(path) if os.path.isabs(path) else path
|
|
158
|
+
if path not in seen:
|
|
159
|
+
seen.add(path)
|
|
160
|
+
unique.append(path)
|
|
161
|
+
return unique
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@dataclass
|
|
165
|
+
class CompilerInfo:
|
|
166
|
+
path: str
|
|
167
|
+
target: Target
|
|
168
|
+
machine: str = ''
|
|
169
|
+
version: str = ''
|
|
170
|
+
ok: bool = False
|
|
171
|
+
|
|
172
|
+
def __bool__(self) -> bool:
|
|
173
|
+
return self.ok
|
|
174
|
+
|
|
175
|
+
def describe(self) -> str:
|
|
176
|
+
if not self.ok:
|
|
177
|
+
return f'{self.path} (不可用)'
|
|
178
|
+
return f'{self.path} [{self.machine}] {self.version}'.strip()
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def probe(path: str, target: Target, *, timeout: float = 10.0) -> CompilerInfo:
|
|
182
|
+
"""运行 ``-dumpmachine`` / ``--version`` 探测编译器; 失败不抛异常。"""
|
|
183
|
+
info = CompilerInfo(path=path, target=target)
|
|
184
|
+
if not path or not (os.path.isfile(path) or shutil.which(path)):
|
|
185
|
+
return info
|
|
186
|
+
try:
|
|
187
|
+
machine = subprocess.run(
|
|
188
|
+
[path, '-dumpmachine'], capture_output=True, text=True,
|
|
189
|
+
timeout=timeout, check=False)
|
|
190
|
+
version = subprocess.run(
|
|
191
|
+
[path, '--version'], capture_output=True, text=True,
|
|
192
|
+
timeout=timeout, check=False)
|
|
193
|
+
except (OSError, subprocess.SubprocessError):
|
|
194
|
+
return info
|
|
195
|
+
info.machine = (machine.stdout or '').strip()
|
|
196
|
+
first = (version.stdout or '').strip().splitlines()
|
|
197
|
+
info.version = first[0] if first else ''
|
|
198
|
+
info.ok = bool(info.machine) and machine.returncode == 0
|
|
199
|
+
return info
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def matches(target: Target, machine: str) -> bool:
|
|
203
|
+
"""``-dumpmachine`` 结果是否可用于该目标 (容忍发行版后缀差异)。"""
|
|
204
|
+
if not machine:
|
|
205
|
+
return False
|
|
206
|
+
machine = machine.lower()
|
|
207
|
+
if target.name.endswith('windows'):
|
|
208
|
+
return any(token in machine for token in ('mingw', 'windows', 'win32'))
|
|
209
|
+
if target.name.startswith('aarch64'):
|
|
210
|
+
if not any(token in machine for token in ('aarch64', 'arm64')):
|
|
211
|
+
return False
|
|
212
|
+
elif not any(token in machine for token in ('x86_64', 'amd64')):
|
|
213
|
+
return False
|
|
214
|
+
if target.name.endswith('linux'):
|
|
215
|
+
return 'linux' in machine
|
|
216
|
+
return True
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def find_compiler(target: Target) -> Optional[CompilerInfo]:
|
|
220
|
+
"""找到第一个**目标匹配**的编译器; 找不到返回 None。"""
|
|
221
|
+
for path in compiler_candidates(target):
|
|
222
|
+
info = probe(path, target)
|
|
223
|
+
if info.ok and matches(target, info.machine):
|
|
224
|
+
return info
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def find_zig() -> Optional[str]:
|
|
229
|
+
"""查找 Zig (``zig cc`` 自带跨平台 libc, 可当交叉编译器用)。
|
|
230
|
+
|
|
231
|
+
顺序: ``CODECIN_ZIG`` -> ``~/.codecin/zig/**/zig[.exe]`` -> PATH。
|
|
232
|
+
"""
|
|
233
|
+
explicit = os.environ.get('CODECIN_ZIG')
|
|
234
|
+
if explicit and os.path.isfile(explicit):
|
|
235
|
+
return os.path.abspath(explicit)
|
|
236
|
+
base = os.path.join(os.path.expanduser('~'), '.codecin', 'zig')
|
|
237
|
+
if os.path.isdir(base):
|
|
238
|
+
for name in sorted(os.listdir(base)):
|
|
239
|
+
for exe in ('zig.exe', 'zig'):
|
|
240
|
+
candidate = os.path.join(base, name, exe)
|
|
241
|
+
if os.path.isfile(candidate):
|
|
242
|
+
return candidate
|
|
243
|
+
return shutil.which('zig')
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def hint(target: Target) -> str:
|
|
247
|
+
"""缺失工具链时的安装指引 (可复制执行)。"""
|
|
248
|
+
env_key = 'CODECIN_CC_' + re.sub(r'[^A-Z0-9]+', '_', target.name.upper())
|
|
249
|
+
lines = [f'缺少可用于 {target.name} ({target.triple}) 的 C 编译器。',
|
|
250
|
+
'任选其一:',
|
|
251
|
+
f' 1. 安装系统交叉工具链并把驱动加入 PATH'
|
|
252
|
+
f' (例如 {target.prefix}gcc);',
|
|
253
|
+
f' 2. 指定现成编译器: 设置 {env_key}=<路径>,'
|
|
254
|
+
f' 或 CODECIN_CC=<路径>;',
|
|
255
|
+
f' 3. 使用自带工具链: python -m codecin.toolchain install'
|
|
256
|
+
f' {target.name} --url <压缩包>',
|
|
257
|
+
f' 默认镜像: {mirror_url(target)}',
|
|
258
|
+
f' 解包目录: {os.path.join(_toolchain_root(), target.name)}']
|
|
259
|
+
return '\n'.join(lines)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def require(target: Target) -> CompilerInfo:
|
|
263
|
+
info = find_compiler(target)
|
|
264
|
+
if info is None:
|
|
265
|
+
raise ToolchainError(hint(target))
|
|
266
|
+
return info
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# ==================== 下载 / 安装 ====================
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _sha256_file(path: str) -> str:
|
|
273
|
+
digest = hashlib.sha256()
|
|
274
|
+
with open(path, 'rb') as f:
|
|
275
|
+
for chunk in iter(lambda: f.read(1 << 20), b''):
|
|
276
|
+
digest.update(chunk)
|
|
277
|
+
return digest.hexdigest()
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def download(url: str, dest: str, *, sha256: Optional[str] = None,
|
|
281
|
+
timeout: float = 60.0) -> str:
|
|
282
|
+
"""下载 ``url`` 到 ``dest`` (支持 ``file://``), 可选校验 sha256。"""
|
|
283
|
+
os.makedirs(os.path.dirname(os.path.abspath(dest)) or '.', exist_ok=True)
|
|
284
|
+
scheme = urllib.parse.urlparse(url).scheme
|
|
285
|
+
if scheme in ('', 'file'):
|
|
286
|
+
src = urllib.request.url2pathname(urllib.parse.urlparse(url).path) \
|
|
287
|
+
if scheme == 'file' else url
|
|
288
|
+
if not os.path.isfile(src):
|
|
289
|
+
raise ToolchainError(f'文件不存在: {src}')
|
|
290
|
+
shutil.copyfile(src, dest)
|
|
291
|
+
else:
|
|
292
|
+
try:
|
|
293
|
+
with urllib.request.urlopen(url, timeout=timeout) as response, \
|
|
294
|
+
open(dest, 'wb') as out:
|
|
295
|
+
shutil.copyfileobj(response, out)
|
|
296
|
+
except Exception as e: # noqa: BLE001 - 统一转换为 ToolchainError
|
|
297
|
+
raise ToolchainError(f'下载失败: {url}: {e}') from e
|
|
298
|
+
if sha256:
|
|
299
|
+
actual = _sha256_file(dest)
|
|
300
|
+
if actual.lower() != sha256.lower():
|
|
301
|
+
raise ToolchainError(
|
|
302
|
+
f'sha256 不匹配: 期望 {sha256}, 实际 {actual}')
|
|
303
|
+
return os.path.abspath(dest)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _safe_members(names: Sequence[str]) -> None:
|
|
307
|
+
for name in names:
|
|
308
|
+
normalized = name.replace('\\', '/')
|
|
309
|
+
if normalized.startswith('/') or '..' in normalized.split('/'):
|
|
310
|
+
raise ToolchainError(f'压缩包包含越界路径: {name!r}')
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def install_archive(archive: str, target: Target, *,
|
|
314
|
+
root: Optional[str] = None) -> str:
|
|
315
|
+
"""把工具链压缩包解到 ``root/<target>``, 返回该目录。"""
|
|
316
|
+
dest = os.path.join(root or _toolchain_root(), target.name)
|
|
317
|
+
os.makedirs(dest, exist_ok=True)
|
|
318
|
+
lower = archive.lower()
|
|
319
|
+
if lower.endswith(('.tar.gz', '.tgz', '.tar.xz', '.tar.bz2')):
|
|
320
|
+
with tarfile.open(archive, 'r:*') as tar:
|
|
321
|
+
members = tar.getmembers()
|
|
322
|
+
_safe_members([m.name for m in members])
|
|
323
|
+
tar.extractall(dest)
|
|
324
|
+
elif lower.endswith('.zip'):
|
|
325
|
+
with zipfile.ZipFile(archive) as zf:
|
|
326
|
+
_safe_members(zf.namelist())
|
|
327
|
+
zf.extractall(dest)
|
|
328
|
+
else:
|
|
329
|
+
raise ToolchainError(f'不支持的压缩格式: {archive}')
|
|
330
|
+
for dirpath, _dirnames, filenames in os.walk(dest):
|
|
331
|
+
for name in filenames:
|
|
332
|
+
if name.endswith(('gcc', 'g++', 'cc', 'ld', '.exe')) or \
|
|
333
|
+
name in ('clang',):
|
|
334
|
+
path = os.path.join(dirpath, name)
|
|
335
|
+
if sys.platform != 'win32':
|
|
336
|
+
os.chmod(path, 0o755)
|
|
337
|
+
return dest
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def install(target_name: str, url: Optional[str] = None,
|
|
341
|
+
sha256: Optional[str] = None, *,
|
|
342
|
+
root: Optional[str] = None) -> str:
|
|
343
|
+
"""下载并安装自带工具链 (返回解包目录)。"""
|
|
344
|
+
target = get_target(target_name)
|
|
345
|
+
source = url or mirror_url(target)
|
|
346
|
+
with tempfile.TemporaryDirectory(prefix='.gccdl-') as tmp:
|
|
347
|
+
archive = download(source, os.path.join(tmp, 'toolchain.archive'),
|
|
348
|
+
sha256=sha256)
|
|
349
|
+
return install_archive(archive, target, root=root)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
# ==================== CLI ====================
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
356
|
+
import argparse
|
|
357
|
+
parser = argparse.ArgumentParser(
|
|
358
|
+
prog='python -m codecin.toolchain',
|
|
359
|
+
description='AOT 工具链 (GCC/Clang) 发现与安装')
|
|
360
|
+
sub = parser.add_subparsers(dest='command', required=True)
|
|
361
|
+
|
|
362
|
+
sub.add_parser('list', help='列出支持的 AOT 目标')
|
|
363
|
+
|
|
364
|
+
p = sub.add_parser('which', help='显示某目标实际会使用的编译器')
|
|
365
|
+
p.add_argument('target')
|
|
366
|
+
|
|
367
|
+
p = sub.add_parser('install', help='下载并解包自带工具链')
|
|
368
|
+
p.add_argument('target')
|
|
369
|
+
p.add_argument('--url')
|
|
370
|
+
p.add_argument('--sha256')
|
|
371
|
+
p.add_argument('--root')
|
|
372
|
+
|
|
373
|
+
args = parser.parse_args(list(sys.argv[1:] if argv is None else argv))
|
|
374
|
+
try:
|
|
375
|
+
if args.command == 'list':
|
|
376
|
+
for name in sorted(TARGETS):
|
|
377
|
+
target = TARGETS[name]
|
|
378
|
+
found = find_compiler(target)
|
|
379
|
+
state = found.describe() if found else '未找到'
|
|
380
|
+
print(f'{name:<16} {target.triple:<24} {state}')
|
|
381
|
+
return 0
|
|
382
|
+
if args.command == 'which':
|
|
383
|
+
target = get_target(args.target)
|
|
384
|
+
found = find_compiler(target)
|
|
385
|
+
print(found.path if found else hint(target))
|
|
386
|
+
return 0 if found else 1
|
|
387
|
+
dest = install(args.target, args.url, args.sha256, root=args.root)
|
|
388
|
+
print(f'工具链已安装到: {dest}')
|
|
389
|
+
return 0
|
|
390
|
+
except ToolchainError as e:
|
|
391
|
+
sys.stderr.write(f'toolchain: error: {e}\n')
|
|
392
|
+
return 1
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
if __name__ == '__main__':
|
|
396
|
+
sys.exit(main())
|
codecin/toolkit.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""工具链 CLI 的共享小工具 (仅标准库)。"""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import sys
|
|
5
|
+
from typing import Optional, Sequence
|
|
6
|
+
|
|
7
|
+
__all__ = ['configure_stdio']
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def configure_stdio() -> None:
|
|
11
|
+
"""把 stdout/stderr 切到 UTF-8 (Windows 中文控制台默认 GBK)。
|
|
12
|
+
|
|
13
|
+
与 ``codecin.cli.main`` 的处理保持一致: 无法编码的字符替换而不崩溃。
|
|
14
|
+
"""
|
|
15
|
+
for stream in (sys.stdout, sys.stderr):
|
|
16
|
+
if hasattr(stream, 'reconfigure'):
|
|
17
|
+
with contextlib.suppress(ValueError, OSError):
|
|
18
|
+
stream.reconfigure(encoding='utf-8', errors='replace')
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def strip_separator(args: Optional[Sequence[str]]) -> list:
|
|
22
|
+
"""去掉 argparse REMAINDER 可能保留的开头 ``--``。"""
|
|
23
|
+
values = list(args or [])
|
|
24
|
+
if values and values[0] == '--':
|
|
25
|
+
values = values[1:]
|
|
26
|
+
return values
|
codecin/version.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""版本设施: 单一真源的解析/比较 + 构建环境自检 (workstream C)。
|
|
2
|
+
|
|
3
|
+
版本号以前只是 `codecin/__init__.py` 里的一个字符串, 只能被打印。本模块把它变成
|
|
4
|
+
**可编程、可自检**的设施, 同时不复制版本号本身:
|
|
5
|
+
|
|
6
|
+
* 真源仍然是 `codecin.__version__` (见 `tests/test_version.py`,
|
|
7
|
+
`pyproject.toml` 的 dynamic version, 以及 `script/gen_native_isa.py`
|
|
8
|
+
生成的 Go 侧 `engine.BuildVersion`);
|
|
9
|
+
* 纯函数 (`version_tuple` / `compare` / `is_version_string`) 与副作用分离,
|
|
10
|
+
便于单测; 非法输入显式抛 `VersionError` 而不是静默算错;
|
|
11
|
+
* `build_info()` 采集运行环境快照 (解释器/平台/原生库/包路径), 并且
|
|
12
|
+
**保证绝不抛异常**: 原生库缺失、加载失败 (OSError)、ABI 不符或自报版本
|
|
13
|
+
异常时, 一律优雅降级为 `native: False` / `native_version: None`。
|
|
14
|
+
|
|
15
|
+
对外接口::
|
|
16
|
+
|
|
17
|
+
version_info() -> (major, minor, patch) # 非 x.y.z 抛 VersionError
|
|
18
|
+
version_tuple(text) -> (major, minor, patch) # 纯函数
|
|
19
|
+
compare(a, b) -> -1 / 0 / 1 # 纯函数
|
|
20
|
+
build_info() -> dict # 绝不抛异常
|
|
21
|
+
format_build_info() -> str # 可读多行文本
|
|
22
|
+
build_info_json() -> str # 机器可读 JSON
|
|
23
|
+
|
|
24
|
+
CLI 侧: `codecin --build-info [--json]` (见 codecin/cli.py)。
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import platform
|
|
30
|
+
import re
|
|
31
|
+
import sys
|
|
32
|
+
from typing import Any, Callable, Dict, Optional, Tuple
|
|
33
|
+
|
|
34
|
+
from . import __version__ as _SOURCE_VERSION
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
'VersionError',
|
|
38
|
+
'current_version',
|
|
39
|
+
'is_version_string',
|
|
40
|
+
'version_tuple',
|
|
41
|
+
'try_version_tuple',
|
|
42
|
+
'version_info',
|
|
43
|
+
'compare',
|
|
44
|
+
'build_info',
|
|
45
|
+
'format_build_info',
|
|
46
|
+
'build_info_json',
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
# x.y.z, 允许可选 'v' 前缀与语义化版本的 -预发布 / +构建 后缀。
|
|
50
|
+
# 后缀只用于识别, 比较时按 x.y.z 三段数值进行 (见 compare)。
|
|
51
|
+
_VERSION_RE = re.compile(r'^[vV]?(\d+)\.(\d+)\.(\d+)(?:[-+][0-9A-Za-z.\-+]*)?$')
|
|
52
|
+
|
|
53
|
+
#: bump_version.py 使用的严格形式 (不接受 v 前缀 / 后缀)。
|
|
54
|
+
STRICT_VERSION_RE = re.compile(r'^\d+\.\d+\.\d+$')
|
|
55
|
+
|
|
56
|
+
#: 原生库自报版本里的"没有版本"占位值 (见 codecin/native.py NativeEngine.version)。
|
|
57
|
+
_UNKNOWN_VERSIONS = frozenset({'', 'unknown', 'none', 'null', 'n/a'})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class VersionError(ValueError):
|
|
61
|
+
"""版本号无法按 x.y.z 解析。"""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def current_version() -> str:
|
|
65
|
+
"""读取唯一真源 `codecin.__version__` (每次动态读取, 便于测试替换)。"""
|
|
66
|
+
try:
|
|
67
|
+
import codecin
|
|
68
|
+
value = getattr(codecin, '__version__', _SOURCE_VERSION)
|
|
69
|
+
except Exception: # pragma: no cover - 导入异常兜底
|
|
70
|
+
value = _SOURCE_VERSION
|
|
71
|
+
return str(value)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def is_version_string(text: Any) -> bool:
|
|
75
|
+
"""`text` 是否为可解析的版本号 (x.y.z, 允许 v 前缀与 -/+ 后缀)。"""
|
|
76
|
+
try:
|
|
77
|
+
return _VERSION_RE.match(str(text).strip()) is not None
|
|
78
|
+
except Exception: # pragma: no cover - __str__ 抛异常
|
|
79
|
+
return False
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def version_tuple(text: Any) -> Tuple[int, int, int]:
|
|
83
|
+
"""把版本号解析为 `(major, minor, patch)` 整数元组 (纯函数)。
|
|
84
|
+
|
|
85
|
+
接受 `5.6.0` / `v5.6.0` / `5.6.0-rc.1+build.7` 与首尾空白;
|
|
86
|
+
其余形式 (空串 / `5.6` / `1.2.3.4` / `abc`) 抛 `VersionError` (ValueError 子类),
|
|
87
|
+
绝不返回 "猜测值"。
|
|
88
|
+
"""
|
|
89
|
+
raw = str(text).strip()
|
|
90
|
+
m = _VERSION_RE.match(raw)
|
|
91
|
+
if m is None:
|
|
92
|
+
raise VersionError(
|
|
93
|
+
f"版本号必须形如 x.y.z (可带 -预发布/+构建 后缀): {raw!r}")
|
|
94
|
+
return int(m.group(1)), int(m.group(2)), int(m.group(3))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def try_version_tuple(text: Any) -> Optional[Tuple[int, int, int]]:
|
|
98
|
+
"""`version_tuple` 的不抛异常版本: 非法输入返回 `None`。"""
|
|
99
|
+
try:
|
|
100
|
+
return version_tuple(text)
|
|
101
|
+
except (VersionError, TypeError, ValueError):
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def version_info() -> Tuple[int, int, int]:
|
|
106
|
+
"""当前版本 (`codecin.__version__`) 的 `(major, minor, patch)`。
|
|
107
|
+
|
|
108
|
+
非 x.y.z 形式会抛 `VersionError`: 版本号漂移属于发布链路故障, 必须显式失败。
|
|
109
|
+
需要"不抛异常"的调用方请用 `try_version_tuple(current_version())`。
|
|
110
|
+
"""
|
|
111
|
+
return version_tuple(current_version())
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def compare(a: Any, b: Any) -> int:
|
|
115
|
+
"""语义化数值比较 (纯函数): `a < b` 返回 -1, 相等 0, `a > b` 返回 1。
|
|
116
|
+
|
|
117
|
+
只比较 x.y.z 三段的整数值 (如 `5.6.0-rc1` 与 `5.6.0` 视为相等),
|
|
118
|
+
与 `script/bump_version.py` 的"新版本必须大于当前版本"判定一致。
|
|
119
|
+
任一入参非法即抛 `VersionError`。
|
|
120
|
+
"""
|
|
121
|
+
ta = version_tuple(a)
|
|
122
|
+
tb = version_tuple(b)
|
|
123
|
+
return (ta > tb) - (ta < tb)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _safe(fn: Callable[[], Any], default: Any = None) -> Any:
|
|
127
|
+
"""执行 `fn` 并把**任何**异常折叠为 `default` (build_info 的不抛异常基石)。"""
|
|
128
|
+
try:
|
|
129
|
+
return fn()
|
|
130
|
+
except Exception:
|
|
131
|
+
return default
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _native_details() -> Tuple[bool, Optional[str], Optional[str]]:
|
|
135
|
+
"""探测原生库: `(是否可用, 自报版本, 库文件路径)`。
|
|
136
|
+
|
|
137
|
+
加载失败 (库缺失 / OSError / 缺导出符号) 全部视为不可用, 不向上抛异常。
|
|
138
|
+
"""
|
|
139
|
+
try:
|
|
140
|
+
from . import native as native_mod
|
|
141
|
+
engine = native_mod.get_engine()
|
|
142
|
+
except Exception:
|
|
143
|
+
return False, None, None
|
|
144
|
+
if engine is None:
|
|
145
|
+
return False, None, None
|
|
146
|
+
|
|
147
|
+
raw = _safe(engine.version)
|
|
148
|
+
if isinstance(raw, bytes): # pragma: no cover - c_char_p 已解码
|
|
149
|
+
raw = raw.decode('utf-8', 'replace')
|
|
150
|
+
version = str(raw).strip() if raw is not None else ''
|
|
151
|
+
if version.lower() in _UNKNOWN_VERSIONS:
|
|
152
|
+
version = ''
|
|
153
|
+
|
|
154
|
+
lib = getattr(engine, 'lib', None)
|
|
155
|
+
path = _safe(lambda: getattr(lib, '_name', None))
|
|
156
|
+
return True, (version or None), (str(path) if path else None)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def build_info() -> Dict[str, Any]:
|
|
160
|
+
"""运行环境快照 (版本、解释器、平台、原生库、包路径)。
|
|
161
|
+
|
|
162
|
+
**本函数绝不抛异常** —— 它是发布/排障自检入口, 收集不到的字段填 `''`/`None`,
|
|
163
|
+
原生库不可用时 `native` 为 `False` (v5.9.0 起为 native-only, 需重建原生库)。
|
|
164
|
+
返回值可直接 `json.dumps`。
|
|
165
|
+
"""
|
|
166
|
+
version = _safe(current_version, '')
|
|
167
|
+
if not isinstance(version, str):
|
|
168
|
+
version = str(version)
|
|
169
|
+
parsed = try_version_tuple(version)
|
|
170
|
+
|
|
171
|
+
python_version = _safe(platform.python_version)
|
|
172
|
+
if not python_version:
|
|
173
|
+
python_version = _safe(lambda: sys.version.split()[0], '') or ''
|
|
174
|
+
implementation = _safe(platform.python_implementation) or ''
|
|
175
|
+
|
|
176
|
+
sys_platform = _safe(lambda: sys.platform, '') or ''
|
|
177
|
+
system = _safe(platform.system) or ''
|
|
178
|
+
machine = _safe(platform.machine) or ''
|
|
179
|
+
|
|
180
|
+
native_ok, native_version, native_path = _safe(
|
|
181
|
+
_native_details, (False, None, None))
|
|
182
|
+
native_ok = bool(native_ok)
|
|
183
|
+
if not isinstance(native_version, str):
|
|
184
|
+
native_version = None
|
|
185
|
+
if not isinstance(native_path, str):
|
|
186
|
+
native_path = None
|
|
187
|
+
|
|
188
|
+
# 自检: 原生库自报版本里是否含包版本 (Go 侧 BuildVersion 由生成器注入,
|
|
189
|
+
# 正常情况下必然一致; 不一致说明旁边放了一个旧库)。
|
|
190
|
+
native_matches: Optional[bool] = None
|
|
191
|
+
if native_ok and native_version and parsed is not None:
|
|
192
|
+
native_matches = version in native_version
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
'version': version,
|
|
196
|
+
'version_info': list(parsed) if parsed is not None else None,
|
|
197
|
+
'python': str(python_version),
|
|
198
|
+
'python_implementation': str(implementation),
|
|
199
|
+
'platform': f'{sys_platform}/{machine}' if machine else str(sys_platform),
|
|
200
|
+
'system': str(system),
|
|
201
|
+
'machine': str(machine),
|
|
202
|
+
'native': native_ok,
|
|
203
|
+
'native_version': native_version,
|
|
204
|
+
'native_path': native_path,
|
|
205
|
+
'native_version_matches': native_matches,
|
|
206
|
+
'package_path': os.path.dirname(os.path.abspath(__file__)),
|
|
207
|
+
'executable': _safe(lambda: sys.executable, '') or '',
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _human(value: Any, empty: str = '(未知)') -> str:
|
|
212
|
+
if value is None or value == '':
|
|
213
|
+
return empty
|
|
214
|
+
return str(value)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def format_build_info(info: Optional[Dict[str, Any]] = None) -> str:
|
|
218
|
+
"""把 `build_info()` 渲染成可读的多行纯文本 (无 ANSI, 便于重定向/贴报告)。"""
|
|
219
|
+
data: Dict[str, Any] = dict(build_info() if info is None else info)
|
|
220
|
+
|
|
221
|
+
parsed = data.get('version_info')
|
|
222
|
+
if isinstance(parsed, (list, tuple)) and len(parsed) == 3:
|
|
223
|
+
parsed_text = '(' + ', '.join(str(p) for p in parsed) + ')'
|
|
224
|
+
else:
|
|
225
|
+
parsed_text = '(无法解析为 x.y.z)'
|
|
226
|
+
|
|
227
|
+
if data.get('native'):
|
|
228
|
+
native_text = '可用'
|
|
229
|
+
if data.get('native_version'):
|
|
230
|
+
native_text += f": {data['native_version']}"
|
|
231
|
+
else:
|
|
232
|
+
native_text = '不可用 (请运行 codecin/native/build.ps1 或 build.sh 重建)'
|
|
233
|
+
|
|
234
|
+
matches = data.get('native_version_matches')
|
|
235
|
+
matches_text = ('(未知)' if matches is None
|
|
236
|
+
else '一致' if matches else '不一致 (原生库可能过期)')
|
|
237
|
+
|
|
238
|
+
lines = [
|
|
239
|
+
f"Code CIN 构建信息 (build info) - {_human(data.get('version'), '?')}",
|
|
240
|
+
f" version : {_human(data.get('version'), '?')}",
|
|
241
|
+
f" version_info : {parsed_text}",
|
|
242
|
+
f" python : {_human(data.get('python'))}"
|
|
243
|
+
f" ({_human(data.get('python_implementation'), '?')})",
|
|
244
|
+
f" platform : {_human(data.get('platform'))}",
|
|
245
|
+
f" system : {_human(data.get('system'))}",
|
|
246
|
+
f" machine : {_human(data.get('machine'))}",
|
|
247
|
+
f" native : {native_text}",
|
|
248
|
+
f" native version : {_human(data.get('native_version'))}",
|
|
249
|
+
f" native library : {_human(data.get('native_path'))}",
|
|
250
|
+
f" native matches : {matches_text}",
|
|
251
|
+
f" package path : {_human(data.get('package_path'))}",
|
|
252
|
+
f" executable : {_human(data.get('executable'))}",
|
|
253
|
+
]
|
|
254
|
+
return '\n'.join(lines)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def build_info_json(info: Optional[Dict[str, Any]] = None, indent: int = 2) -> str:
|
|
258
|
+
"""`build_info()` 的 JSON 文本 (UTF-8 友好: `ensure_ascii=False`)。"""
|
|
259
|
+
data = build_info() if info is None else info
|
|
260
|
+
return json.dumps(data, indent=indent, ensure_ascii=False)
|