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.
Files changed (202) hide show
  1. codecin/__init__.py +27 -0
  2. codecin/aot.py +1057 -0
  3. codecin/assembler.py +619 -0
  4. codecin/cbackend.py +3024 -0
  5. codecin/cin.py +4265 -0
  6. codecin/cli.py +670 -0
  7. codecin/codecin_native.dll +0 -0
  8. codecin/config.py +50 -0
  9. codecin/console.py +183 -0
  10. codecin/cpu.py +312 -0
  11. codecin/crom.py +449 -0
  12. codecin/cvm.py +708 -0
  13. codecin/disasm.py +149 -0
  14. codecin/environment.py +176 -0
  15. codecin/errors.py +54 -0
  16. codecin/isa.py +560 -0
  17. codecin/lib/array/pic.toml +10 -0
  18. codecin/lib/array/src/array.cin +103 -0
  19. codecin/lib/bigint/pic.toml +10 -0
  20. codecin/lib/bigint/src/bigint.cin +589 -0
  21. codecin/lib/bits/pic.toml +10 -0
  22. codecin/lib/bits/src/bits.cin +143 -0
  23. codecin/lib/bitset/pic.toml +10 -0
  24. codecin/lib/bitset/src/bitset.cin +374 -0
  25. codecin/lib/codec/pic.toml +10 -0
  26. codecin/lib/codec/src/codec.cin +563 -0
  27. codecin/lib/combin/pic.toml +10 -0
  28. codecin/lib/combin/src/combin.cin +414 -0
  29. codecin/lib/conv/pic.toml +10 -0
  30. codecin/lib/conv/src/conv.cin +151 -0
  31. codecin/lib/cppstd/pic.toml +10 -0
  32. codecin/lib/cppstd/src/cppstd.cin +418 -0
  33. codecin/lib/cstd/pic.toml +10 -0
  34. codecin/lib/cstd/src/cstd.cin +424 -0
  35. codecin/lib/csv/pic.toml +10 -0
  36. codecin/lib/csv/src/csv.cin +405 -0
  37. codecin/lib/dp/pic.toml +10 -0
  38. codecin/lib/dp/src/dp.cin +325 -0
  39. codecin/lib/ffi/pic.toml +10 -0
  40. codecin/lib/ffi/src/ffi.cin +163 -0
  41. codecin/lib/fmt/pic.toml +10 -0
  42. codecin/lib/fmt/src/fmt.cin +325 -0
  43. codecin/lib/frac/pic.toml +10 -0
  44. codecin/lib/frac/src/frac.cin +252 -0
  45. codecin/lib/gostd/pic.toml +10 -0
  46. codecin/lib/gostd/src/gostd.cin +415 -0
  47. codecin/lib/graph/pic.toml +10 -0
  48. codecin/lib/graph/src/graph.cin +367 -0
  49. codecin/lib/gui/pic.toml +10 -0
  50. codecin/lib/gui/src/gui.cin +218 -0
  51. codecin/lib/hash/pic.toml +10 -0
  52. codecin/lib/hash/src/hash.cin +67 -0
  53. codecin/lib/heap/pic.toml +10 -0
  54. codecin/lib/heap/src/heap.cin +199 -0
  55. codecin/lib/io/pic.toml +10 -0
  56. codecin/lib/io/src/io.cin +141 -0
  57. codecin/lib/json/pic.toml +10 -0
  58. codecin/lib/json/src/json.cin +84 -0
  59. codecin/lib/key/pic.toml +10 -0
  60. codecin/lib/key/src/key.cin +78 -0
  61. codecin/lib/math/pic.toml +10 -0
  62. codecin/lib/math/src/math.cin +50 -0
  63. codecin/lib/matrix/pic.toml +10 -0
  64. codecin/lib/matrix/src/matrix.cin +155 -0
  65. codecin/lib/net/pic.toml +10 -0
  66. codecin/lib/net/src/net.cin +171 -0
  67. codecin/lib/path/pic.toml +10 -0
  68. codecin/lib/path/src/path.cin +372 -0
  69. codecin/lib/queue/pic.toml +10 -0
  70. codecin/lib/queue/src/queue.cin +112 -0
  71. codecin/lib/rand/pic.toml +10 -0
  72. codecin/lib/rand/src/rand.cin +46 -0
  73. codecin/lib/set/pic.toml +10 -0
  74. codecin/lib/set/src/set.cin +269 -0
  75. codecin/lib/sort/pic.toml +10 -0
  76. codecin/lib/sort/src/sort.cin +93 -0
  77. codecin/lib/stat/pic.toml +10 -0
  78. codecin/lib/stat/src/stat.cin +138 -0
  79. codecin/lib/str/pic.toml +10 -0
  80. codecin/lib/str/src/str.cin +54 -0
  81. codecin/lib/termux/pic.toml +10 -0
  82. codecin/lib/termux/src/termux.cin +118 -0
  83. codecin/lib/test/pic.toml +10 -0
  84. codecin/lib/test/src/test.cin +74 -0
  85. codecin/lib/text/pic.toml +10 -0
  86. codecin/lib/text/src/text.cin +323 -0
  87. codecin/lib/time/pic.toml +10 -0
  88. codecin/lib/time/src/time.cin +54 -0
  89. codecin/lib/token/pic.toml +10 -0
  90. codecin/lib/token/src/token.cin +183 -0
  91. codecin/lib/tree/pic.toml +10 -0
  92. codecin/lib/tree/src/tree.cin +256 -0
  93. codecin/lib/unionfind/pic.toml +10 -0
  94. codecin/lib/unionfind/src/unionfind.cin +115 -0
  95. codecin/lib/validate/pic.toml +10 -0
  96. codecin/lib/validate/src/validate.cin +148 -0
  97. codecin/lib/vec/pic.toml +10 -0
  98. codecin/lib/vec/src/vec.cin +88 -0
  99. codecin/logger.py +145 -0
  100. codecin/memory.py +306 -0
  101. codecin/mkn.py +916 -0
  102. codecin/native/aot/aot.go +114 -0
  103. codecin/native/aot/stub_main.go.txt +23 -0
  104. codecin/native/build.ps1 +33 -0
  105. codecin/native/build.sh +48 -0
  106. codecin/native/cmd/cincc/main.go +66 -0
  107. codecin/native/compiler/codegen.go +2238 -0
  108. codecin/native/compiler/compile_test.go +1069 -0
  109. codecin/native/compiler/parser.go +1331 -0
  110. codecin/native/compiler/syscalls.go +166 -0
  111. codecin/native/compiler/tokenizer.go +394 -0
  112. codecin/native/compiler/types.go +217 -0
  113. codecin/native/engine/args.go +37 -0
  114. codecin/native/engine/audio.go +402 -0
  115. codecin/native/engine/audio_other.go +105 -0
  116. codecin/native/engine/audio_test.go +279 -0
  117. codecin/native/engine/audio_windows.go +190 -0
  118. codecin/native/engine/canvas.go +271 -0
  119. codecin/native/engine/console_other.go +9 -0
  120. codecin/native/engine/console_windows.go +43 -0
  121. codecin/native/engine/crom.go +86 -0
  122. codecin/native/engine/encode.go +93 -0
  123. codecin/native/engine/engine_test.go +198 -0
  124. codecin/native/engine/ffi_nocgo.go +20 -0
  125. codecin/native/engine/ffi_registry.go +69 -0
  126. codecin/native/engine/ffi_unix.go +109 -0
  127. codecin/native/engine/ffi_windows.go +117 -0
  128. codecin/native/engine/gui.go +209 -0
  129. codecin/native/engine/gui_stub.go +13 -0
  130. codecin/native/engine/gui_test.go +148 -0
  131. codecin/native/engine/gui_windows.go +604 -0
  132. codecin/native/engine/gui_x11.go +723 -0
  133. codecin/native/engine/host_test.go +139 -0
  134. codecin/native/engine/hostcrypto.go +30 -0
  135. codecin/native/engine/hostdesktop.go +173 -0
  136. codecin/native/engine/hostnet.go +127 -0
  137. codecin/native/engine/isa_gen.go +689 -0
  138. codecin/native/engine/keyboard.go +432 -0
  139. codecin/native/engine/keyboard_other.go +94 -0
  140. codecin/native/engine/keyboard_stub.go +17 -0
  141. codecin/native/engine/keyboard_termios_darwin.go +9 -0
  142. codecin/native/engine/keyboard_termios_linux.go +9 -0
  143. codecin/native/engine/keyboard_test.go +246 -0
  144. codecin/native/engine/keyboard_windows.go +208 -0
  145. codecin/native/engine/keyboard_windows_test.go +123 -0
  146. codecin/native/engine/lineedit.go +262 -0
  147. codecin/native/engine/lineedit_test.go +105 -0
  148. codecin/native/engine/lineint_unix.go +17 -0
  149. codecin/native/engine/lineint_windows.go +19 -0
  150. codecin/native/engine/mem_other.go +37 -0
  151. codecin/native/engine/mem_windows.go +33 -0
  152. codecin/native/engine/native.go +640 -0
  153. codecin/native/engine/netsock.go +321 -0
  154. codecin/native/engine/ops_ext.go +515 -0
  155. codecin/native/engine/stdin.go +72 -0
  156. codecin/native/engine/stdin_other.go +9 -0
  157. codecin/native/engine/stdin_windows.go +60 -0
  158. codecin/native/engine/system.go +313 -0
  159. codecin/native/engine/termux.go +180 -0
  160. codecin/native/engine/version_gen.go +7 -0
  161. codecin/native/engine/vkb_darwin.go +62 -0
  162. codecin/native/engine/vkb_linux.go +95 -0
  163. codecin/native/engine/vkb_stub.go +11 -0
  164. codecin/native/engine/vm.go +1677 -0
  165. codecin/native/go.mod +3 -0
  166. codecin/native/ir/ir.go +48 -0
  167. codecin/native/main.go +448 -0
  168. codecin/native/mc/aarch64.go +165 -0
  169. codecin/native/mc/aarch64_test.go +30 -0
  170. codecin/native/mc/elf.go +88 -0
  171. codecin/native/mc/print_test.go +52 -0
  172. codecin/native/mc/x86_64.go +1262 -0
  173. codecin/native/mc/x86_64_test.go +102 -0
  174. codecin/native.py +432 -0
  175. codecin/native_codegen.py +987 -0
  176. codecin/nativegen.py +786 -0
  177. codecin/object.py +539 -0
  178. codecin/optimizer.py +236 -0
  179. codecin/packaging/__init__.py +46 -0
  180. codecin/packaging/archive.py +177 -0
  181. codecin/packaging/model.py +519 -0
  182. codecin/packaging/spec.py +193 -0
  183. codecin/packaging/store.py +372 -0
  184. codecin/packaging/toml.py +541 -0
  185. codecin/packaging/vcs.py +215 -0
  186. codecin/pic.py +1917 -0
  187. codecin/pic_api.py +374 -0
  188. codecin/pic_login.py +519 -0
  189. codecin/pic_registry.py +515 -0
  190. codecin/registers.py +130 -0
  191. codecin/sdgcc.py +493 -0
  192. codecin/stats.py +230 -0
  193. codecin/stdlib.py +138 -0
  194. codecin/toolchain.py +396 -0
  195. codecin/toolkit.py +26 -0
  196. codecin/version.py +260 -0
  197. codecin-7.22.10.dist-info/METADATA +1077 -0
  198. codecin-7.22.10.dist-info/RECORD +202 -0
  199. codecin-7.22.10.dist-info/WHEEL +5 -0
  200. codecin-7.22.10.dist-info/entry_points.txt +5 -0
  201. codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
  202. codecin-7.22.10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,193 @@
1
+ """pic 包/导入规格的解析。
2
+
3
+ 同一个规格同时用于 ``pic install`` 与 CIN ``import``:
4
+
5
+ ============================ ==================================================
6
+ 写法 含义
7
+ ============================ ==================================================
8
+ ``rich`` 包入口 (兼容旧写法)
9
+ ``rich:*`` 包内全部公开模块 (分块导入)
10
+ ``rich:table`` 只导入 ``table`` 模块
11
+ ``rich:table,markdown`` 导入多个模块 (也可用 ``+`` 分隔)
12
+ ``rich::1.1.1`` 指定版本的包入口
13
+ ``rich::1.1.1:*`` 指定版本的全部公开模块
14
+ ``rich::1.1.1:table`` 指定版本的 ``table`` 模块
15
+ ``rich@1.1.1`` 旧式版本写法, 等价 ``rich::1.1.1``
16
+ ``rich@1.1.1:table`` 旧式版本 + 模块选择
17
+ ============================ ==================================================
18
+
19
+ 冒号是 CIN 的包选择分隔符: 包名里不允许出现 ``:``, 因此不会与现有
20
+ ``import "hello/util.cin"`` 之类的路径写法冲突。版本号只接受精确版本
21
+ (``x.y.z``); 安装时仍可用 ``^1.2`` / ``~1.2`` 等约束。
22
+ """
23
+
24
+ import os
25
+ import re
26
+ from dataclasses import dataclass
27
+ from typing import Iterable, Optional, Tuple
28
+
29
+ __all__ = [
30
+ 'PackageSpec', 'SpecError', 'is_package_spec', 'parse_package_spec',
31
+ 'split_selectors',
32
+ ]
33
+
34
+ _NAME_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_-]{0,63}$')
35
+ _VERSION_RE = re.compile(
36
+ r'^[vV]?(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)$')
37
+
38
+ #: 明显的非包名规格: 路径 / Git / URL / 归档
39
+ _NON_PACKAGE_PREFIXES = (
40
+ '.', '/', '\\', '~', 'path:', 'git+', 'git:', 'file:', 'http:', 'https:',
41
+ )
42
+
43
+
44
+ class SpecError(ValueError):
45
+ """包/导入规格非法。"""
46
+
47
+
48
+ def split_selectors(selector: str) -> Tuple[str, ...]:
49
+ """把 ``table,markdown`` / ``a+b`` 拆成模块选择器元组。"""
50
+ text = str(selector or '').strip()
51
+ if not text:
52
+ return ()
53
+ parts = [part.strip() for part in re.split(r'[,+]', text)]
54
+ return tuple(part for part in parts if part)
55
+
56
+
57
+ def _validate_selector(selector: str) -> str:
58
+ text = str(selector or '').strip().replace('\\', '/')
59
+ if not text:
60
+ return ''
61
+ if text.startswith('/') or '..' in text.split('/'):
62
+ raise SpecError(f'模块选择器不能是绝对路径或包含 "..": {selector!r}')
63
+ for part in split_selectors(text):
64
+ if not re.fullmatch(r'[A-Za-z0-9_.*?/\[\]-]+', part):
65
+ raise SpecError(f'模块选择器非法: {part!r}')
66
+ return text
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class PackageSpec:
71
+ """解析后的包规格 (安装 / import 共用)。"""
72
+
73
+ name: str
74
+ version: str = ''
75
+ selector: str = ''
76
+
77
+ @property
78
+ def modules(self) -> Tuple[str, ...]:
79
+ return split_selectors(self.selector)
80
+
81
+ @property
82
+ def is_all(self) -> bool:
83
+ """``rich:*`` / ``rich::1.1.1:*``: 导入全部公开模块。"""
84
+ return any(module == '*' for module in self.modules)
85
+
86
+ @property
87
+ def has_selector(self) -> bool:
88
+ return bool(self.selector)
89
+
90
+ @property
91
+ def is_latest(self) -> bool:
92
+ return not self.version or self.version.lower() in ('latest', '*', 'any')
93
+
94
+ @property
95
+ def display(self) -> str:
96
+ text = self.name
97
+ if self.version and not self.is_latest:
98
+ text += '::' + self.version
99
+ if self.selector:
100
+ text += ':' + self.selector
101
+ return text
102
+
103
+ def __str__(self) -> str: # pragma: no cover - 便于调试
104
+ return self.display
105
+
106
+
107
+ def is_package_spec(text: str) -> bool:
108
+ """判断字符串是否像 ``name[:selector][::version]`` 包规格。"""
109
+ try:
110
+ parse_package_spec(text)
111
+ except SpecError:
112
+ return False
113
+ return True
114
+
115
+
116
+ def _looks_like_path(text: str) -> bool:
117
+ lowered = text.lower()
118
+ if lowered.endswith(('.cinpkg', '.mkn', '.cvm', '.toml')):
119
+ return True
120
+ if os.path.exists(text):
121
+ return True
122
+ return lowered.startswith(_NON_PACKAGE_PREFIXES)
123
+
124
+
125
+ def parse_package_spec(text: str) -> PackageSpec:
126
+ """解析 ``name`` / ``name:module`` / ``name::version:module``。"""
127
+ raw = str(text or '').strip()
128
+ if not raw:
129
+ raise SpecError('空的包规格')
130
+ if _looks_like_path(raw):
131
+ raise SpecError(f'不是包名规格: {raw!r}')
132
+
133
+ version = ''
134
+ selector = ''
135
+ name_part = raw
136
+
137
+ # 1) 版本段: name[...]::<version>[:<selector>]
138
+ if '::' in name_part:
139
+ left, right = name_part.split('::', 1)
140
+ version_part, sep, selector_part = right.partition(':')
141
+ version = version_part.strip()
142
+ if sep:
143
+ selector = selector_part.strip()
144
+ name_part = left
145
+
146
+ # 2) 模块段: name[...]:<selector>
147
+ if ':' in name_part:
148
+ head, selector_part = name_part.split(':', 1)
149
+ if selector and selector_part.strip():
150
+ raise SpecError(
151
+ f'包规格只能有一个模块选择器: {raw!r}')
152
+ selector = selector_part.strip()
153
+ name_part = head
154
+
155
+ # 3) 旧式版本: name@<version> / name==<version>
156
+ if '==' in name_part:
157
+ name_part, version_part = name_part.split('==', 1)
158
+ if version and version_part.strip():
159
+ raise SpecError(f'包规格出现多个版本: {raw!r}')
160
+ version = version_part.strip()
161
+ elif '@' in name_part:
162
+ name_part, version_part = name_part.rsplit('@', 1)
163
+ if version and version_part.strip():
164
+ raise SpecError(f'包规格出现多个版本: {raw!r}')
165
+ version = version_part.strip()
166
+
167
+ name = name_part.strip()
168
+ if not _NAME_RE.match(name):
169
+ raise SpecError(f'包名非法: {name!r}')
170
+
171
+ version = version.lstrip('vV') if version else ''
172
+ if version and version.lower() not in ('latest', '*', 'any'):
173
+ match = _VERSION_RE.match(version)
174
+ if match is None:
175
+ raise SpecError(
176
+ f'版本号非法: {version!r} (import 需要精确版本 x.y.z)')
177
+ version = match.group(1)
178
+
179
+ return PackageSpec(name=name, version=version,
180
+ selector=_validate_selector(selector))
181
+
182
+
183
+ def spec_from_parts(name: str, version: Optional[str] = None,
184
+ selector: Optional[str] = None) -> PackageSpec:
185
+ """由已经在手的字段构造规格 (selector 为空表示入口)。"""
186
+ return parse_package_spec(
187
+ str(name)
188
+ + (f'::{version}' if version else '')
189
+ + (f':{selector}' if selector else ''))
190
+
191
+
192
+ def format_specs(specs: Iterable[PackageSpec]) -> str: # pragma: no cover
193
+ return ', '.join(spec.display for spec in specs)
@@ -0,0 +1,372 @@
1
+ """包安装存储与项目依赖目录。
2
+
3
+ 全局存储 (默认 ``~/.pic``, 可用 ``PIC_HOME`` 覆盖)::
4
+
5
+ index.json # 已安装记录 (JSON, 原子写)
6
+ packages/<name>/<version>/ # 包内容 (pic.toml + src/...)
7
+ packages/<name>/<version>/.pic-link # 可编辑安装: 指向源目录
8
+ cache/ # Git 缓存 / 归档缓存
9
+ registry.json # 分散式注册表 (名称 -> Git 仓库)
10
+
11
+ 项目依赖目录 (``mkn`` / ``pic --project`` 使用)::
12
+
13
+ <project>/pic_modules/<name>/ # 直接可被 CIN import 解析
14
+
15
+ 存储只负责文件与索引, 不执行网络/编译。
16
+ """
17
+
18
+ import contextlib
19
+ import hashlib
20
+ import json
21
+ import os
22
+ import shutil
23
+ import tempfile
24
+ from dataclasses import dataclass
25
+ from datetime import datetime, timezone
26
+ from typing import Any, Dict, Iterable, List, Optional
27
+
28
+ from .model import ManifestError, load_package_manifest, validate_name, validate_version
29
+
30
+ __all__ = ['InstalledPackage', 'PackageStore', 'default_store',
31
+ 'project_modules_dir', 'copy_package_tree', 'resolve_link']
32
+
33
+ _COPY_IGNORE = shutil.ignore_patterns(
34
+ '.git', '.hg', '.svn', '__pycache__', '*.pyc', '.pytest_cache',
35
+ '.mypy_cache', '.ruff_cache', 'build', 'dist', 'target', 'pic_modules',
36
+ '.pic', '.mkn', 'node_modules', '.venv', 'venv',
37
+ )
38
+
39
+
40
+ class StoreError(ManifestError):
41
+ """包存储操作失败。"""
42
+
43
+
44
+ @dataclass
45
+ class InstalledPackage:
46
+ name: str
47
+ version: str
48
+ path: str
49
+ repo: str = ''
50
+ rev: str = ''
51
+ editable: bool = False
52
+ installed_at: str = ''
53
+
54
+ @property
55
+ def real_path(self) -> str:
56
+ return resolve_link(self.path)
57
+
58
+ def to_dict(self) -> Dict[str, Any]:
59
+ data: Dict[str, Any] = {'path': self.path}
60
+ if self.repo:
61
+ data['repo'] = self.repo
62
+ if self.rev:
63
+ data['rev'] = self.rev
64
+ if self.editable:
65
+ data['editable'] = True
66
+ if self.installed_at:
67
+ data['installed_at'] = self.installed_at
68
+ return data
69
+
70
+
71
+ def resolve_link(path: str) -> str:
72
+ """可编辑安装的 ``.pic-link`` 解引用; 普通目录原样返回。"""
73
+ link = os.path.join(path, '.pic-link')
74
+ if os.path.isfile(link):
75
+ try:
76
+ with open(link, encoding='utf-8') as f:
77
+ target = f.read().strip()
78
+ except OSError:
79
+ return path
80
+ if target:
81
+ return os.path.abspath(target)
82
+ return path
83
+
84
+
85
+ def project_modules_dir(project_root: str) -> str:
86
+ return os.path.join(os.path.abspath(project_root), 'pic_modules')
87
+
88
+
89
+ def copy_package_tree(src: str, dest: str, editable: bool = False) -> str:
90
+ """把包目录复制/链接到 ``dest``; 返回 ``dest``。"""
91
+ src = os.path.abspath(src)
92
+ dest = os.path.abspath(dest)
93
+ if not os.path.isdir(src):
94
+ raise StoreError(f'包源目录不存在: {src}')
95
+ if os.path.exists(dest):
96
+ shutil.rmtree(dest)
97
+ parent = os.path.dirname(dest)
98
+ os.makedirs(parent, exist_ok=True)
99
+ if editable:
100
+ os.makedirs(dest, exist_ok=True)
101
+ with open(os.path.join(dest, '.pic-link'), 'w', encoding='utf-8') as f:
102
+ f.write(src + '\n')
103
+ return dest
104
+ shutil.copytree(src, dest, ignore=_COPY_IGNORE, dirs_exist_ok=False)
105
+ return dest
106
+
107
+
108
+ def _now() -> str:
109
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
110
+
111
+
112
+ class PackageStore:
113
+ """全局包存储 (带 JSON 索引与损坏自愈)。"""
114
+
115
+ def __init__(self, root: Optional[str] = None):
116
+ if root is None:
117
+ root = os.environ.get('PIC_HOME') or os.path.join(
118
+ os.path.expanduser('~'), '.pic')
119
+ self.root = os.path.abspath(root)
120
+ self.packages_dir = os.path.join(self.root, 'packages')
121
+ self.index_path = os.path.join(self.root, 'index.json')
122
+ self.registry_path = os.path.join(self.root, 'registry.json')
123
+ self.cache_dir = os.path.join(self.root, 'cache')
124
+ self.index: Dict[str, Any] = {}
125
+ self._load()
126
+
127
+ # ---------------- 索引 ----------------
128
+
129
+ def _empty_index(self) -> Dict[str, Any]:
130
+ return {'format': 1, 'packages': {}}
131
+
132
+ def _load(self) -> None:
133
+ self.index = self._empty_index()
134
+ if os.path.isfile(self.index_path):
135
+ try:
136
+ with open(self.index_path, encoding='utf-8') as f:
137
+ data = json.load(f)
138
+ if isinstance(data, dict) and isinstance(data.get('packages'), dict):
139
+ self.index = data
140
+ return
141
+ except (OSError, ValueError):
142
+ pass
143
+ self.scan()
144
+ self.save()
145
+
146
+ def save(self) -> None:
147
+ os.makedirs(self.root, exist_ok=True)
148
+ payload = json.dumps(self.index, ensure_ascii=False, indent=2,
149
+ sort_keys=True) + '\n'
150
+ fd, tmp = tempfile.mkstemp(prefix='.index-', suffix='.json',
151
+ dir=self.root)
152
+ try:
153
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as f:
154
+ f.write(payload)
155
+ os.replace(tmp, self.index_path)
156
+ finally:
157
+ if os.path.exists(tmp):
158
+ with contextlib.suppress(OSError):
159
+ os.remove(tmp)
160
+
161
+ def scan(self) -> None:
162
+ """从磁盘重建索引 (只读目录结构, 不需要 pic.toml)。"""
163
+ packages: Dict[str, Any] = {}
164
+ if os.path.isdir(self.packages_dir):
165
+ for name in sorted(os.listdir(self.packages_dir)):
166
+ name_dir = os.path.join(self.packages_dir, name)
167
+ if not os.path.isdir(name_dir):
168
+ continue
169
+ versions: Dict[str, Any] = {}
170
+ for version in sorted(os.listdir(name_dir)):
171
+ path = os.path.join(name_dir, version)
172
+ if not os.path.isdir(path):
173
+ continue
174
+ try:
175
+ validate_name(name)
176
+ validate_version(version)
177
+ except ManifestError:
178
+ continue
179
+ versions[version] = InstalledPackage(
180
+ name=name, version=version, path=path).to_dict()
181
+ if versions:
182
+ packages[name] = {
183
+ 'current': self._highest(list(versions)),
184
+ 'versions': versions,
185
+ }
186
+ self.index = {'format': 1, 'packages': packages}
187
+
188
+ @staticmethod
189
+ def _highest(versions: Iterable[str]) -> str:
190
+ def key(v: str):
191
+ try:
192
+ return tuple(int(p) for p in v.split('-')[0].split('.'))
193
+ except ValueError:
194
+ return (0, 0, 0)
195
+ return max(versions, key=key)
196
+
197
+ # ---------------- 查询 ----------------
198
+
199
+ def _records(self, name: Optional[str] = None) -> Dict[str, Any]:
200
+ packages = self.index.get('packages', {})
201
+ if name is None:
202
+ return packages
203
+ entry = packages.get(name)
204
+ return entry if isinstance(entry, dict) else {}
205
+
206
+ def versions(self, name: str) -> List[str]:
207
+ entry = self._records(name)
208
+ versions = entry.get('versions')
209
+ return sorted(versions) if isinstance(versions, dict) else []
210
+
211
+ def get(self, name: str, version: Optional[str] = None
212
+ ) -> Optional[InstalledPackage]:
213
+ entry = self._records(name)
214
+ versions = entry.get('versions')
215
+ if not isinstance(versions, dict) or not versions:
216
+ return None
217
+ if version is None:
218
+ version = entry.get('current') or self._highest(list(versions))
219
+ record = versions.get(version)
220
+ if record is None:
221
+ return None
222
+ path = record.get('path') or os.path.join(
223
+ self.packages_dir, name, version)
224
+ if not os.path.isabs(path):
225
+ path = os.path.join(self.root, path)
226
+ return InstalledPackage(
227
+ name=name, version=version, path=os.path.abspath(path),
228
+ repo=str(record.get('repo') or ''),
229
+ rev=str(record.get('rev') or ''),
230
+ editable=bool(record.get('editable')),
231
+ installed_at=str(record.get('installed_at') or ''),
232
+ )
233
+
234
+ def all(self) -> List[InstalledPackage]:
235
+ out: List[InstalledPackage] = []
236
+ for name in sorted(self._records()):
237
+ for version in self.versions(name):
238
+ pkg = self.get(name, version)
239
+ if pkg is not None:
240
+ out.append(pkg)
241
+ return out
242
+
243
+ def package_entry(self, name: str,
244
+ version: Optional[str] = None) -> Optional[str]:
245
+ pkg = self.get(name, version)
246
+ if pkg is None or not os.path.isdir(pkg.real_path):
247
+ return None
248
+ try:
249
+ return load_package_manifest(pkg.real_path,
250
+ require_entry=False).entry_path
251
+ except ManifestError:
252
+ for candidate in (f'src/{name}.cin', f'{name}.cin',
253
+ 'src/main.cin', 'main.cin'):
254
+ path = os.path.join(pkg.real_path, candidate)
255
+ if os.path.isfile(path):
256
+ return path
257
+ return None
258
+
259
+ # ---------------- 写入 ----------------
260
+
261
+ def install_dir(self, name: str, version: str) -> str:
262
+ validate_name(name)
263
+ validate_version(version)
264
+ return os.path.join(self.packages_dir, name, version)
265
+
266
+ def add(self, src_root: str, name: str, version: str, *,
267
+ repo: str = '', rev: str = '', editable: bool = False,
268
+ force: bool = False, make_current: bool = True
269
+ ) -> InstalledPackage:
270
+ validate_name(name)
271
+ validate_version(version)
272
+ dest = self.install_dir(name, version)
273
+ if os.path.exists(dest) and not force:
274
+ pkg = self.get(name, version)
275
+ if pkg is not None:
276
+ return pkg
277
+ raise StoreError(
278
+ f'{name}=={version} 已存在 ({dest}); 使用 --force 覆盖')
279
+ copy_package_tree(src_root, dest, editable=editable)
280
+ record = InstalledPackage(
281
+ name=name, version=version, path=dest, repo=repo, rev=rev,
282
+ editable=editable, installed_at=_now())
283
+ package = self.index.setdefault('packages', {}).setdefault(
284
+ name, {'versions': {}})
285
+ versions = package.setdefault('versions', {})
286
+ versions[version] = record.to_dict()
287
+ if make_current or not package.get('current'):
288
+ package['current'] = version
289
+ self.save()
290
+ return record
291
+
292
+ def set_current(self, name: str, version: str) -> None:
293
+ package = self.index.get('packages', {}).get(name)
294
+ if not package or version not in package.get('versions', {}):
295
+ raise StoreError(f'未安装: {name}=={version}')
296
+ package['current'] = version
297
+ self.save()
298
+
299
+ def remove(self, name: str, version: Optional[str] = None) -> bool:
300
+ package = self.index.get('packages', {}).get(name)
301
+ if not package:
302
+ return False
303
+ versions = package.get('versions', {})
304
+ targets = [version] if version else list(versions)
305
+ removed = False
306
+ for ver in list(targets):
307
+ if ver not in versions:
308
+ continue
309
+ path = self.install_dir(name, ver)
310
+ shutil.rmtree(path, ignore_errors=True)
311
+ versions.pop(ver, None)
312
+ removed = True
313
+ if not versions:
314
+ self.index['packages'].pop(name, None)
315
+ elif package.get('current') not in versions:
316
+ package['current'] = self._highest(versions)
317
+ if removed:
318
+ self.save()
319
+ return removed
320
+
321
+ # ---------------- 注册表 (名称 -> Git 仓库) ----------------
322
+
323
+ def load_registry(self) -> Dict[str, Any]:
324
+ if not os.path.isfile(self.registry_path):
325
+ return {'format': 1, 'packages': {}}
326
+ try:
327
+ with open(self.registry_path, encoding='utf-8') as f:
328
+ data = json.load(f)
329
+ if isinstance(data, dict) and isinstance(data.get('packages'), dict):
330
+ return data
331
+ except (OSError, ValueError):
332
+ pass
333
+ return {'format': 1, 'packages': {}}
334
+
335
+ def save_registry(self, data: Dict[str, Any]) -> None:
336
+ os.makedirs(self.root, exist_ok=True)
337
+ with open(self.registry_path, 'w', encoding='utf-8', newline='\n') as f:
338
+ json.dump(data, f, ensure_ascii=False, indent=2, sort_keys=True)
339
+ f.write('\n')
340
+
341
+ def register(self, name: str, repo: str, version: Optional[str] = None,
342
+ tag: Optional[str] = None) -> Dict[str, Any]:
343
+ validate_name(name, '注册名')
344
+ data = self.load_registry()
345
+ entry = data.setdefault('packages', {}).setdefault(
346
+ name, {'repo': repo, 'versions': {}})
347
+ entry['repo'] = repo
348
+ if version:
349
+ entry.setdefault('versions', {})[version] = {
350
+ 'tag': tag or f'v{version}',
351
+ }
352
+ self.save_registry(data)
353
+ return entry
354
+
355
+ def lookup(self, name: str) -> Optional[Dict[str, Any]]:
356
+ entry = self.load_registry().get('packages', {}).get(name)
357
+ return entry if isinstance(entry, dict) else None
358
+
359
+ # ---------------- 杂项 ----------------
360
+
361
+ def cache_path(self, *parts: str) -> str:
362
+ path = os.path.join(self.cache_dir, *parts)
363
+ os.makedirs(path, exist_ok=True)
364
+ return path
365
+
366
+
367
+ def default_store() -> PackageStore:
368
+ return PackageStore()
369
+
370
+
371
+ def file_digest(data: bytes) -> str:
372
+ return hashlib.sha256(data).hexdigest()