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
codecin/pic.py ADDED
@@ -0,0 +1,1917 @@
1
+ """``pic`` —— Code CIN 包管理器 (pip 风格)。
2
+
3
+ 核心约定 (v6.2.0+):
4
+
5
+ * **中央注册/分发**: 包记录 (标识名、Git 获取地址、版本列表、源码/清单摘要、
6
+ 发布者) 与 ``.cinpkg`` 制品存放在 ``package.codecin.org.cn``;
7
+ * **Cdifit 只负责登录**: 首次使用通过临时本地网页登录 ``www.cdifit.cn``,
8
+ 获取 AccessToken 后用于中央服务器鉴权;
9
+ * **Git 作为源码来源**: 包内容仍在用户自己的 Git 仓库; 安装时可优先使用
10
+ 中央制品, 否则按标签/提交拉取 Git 并校验摘要;
11
+ * **安装即可直接 import**: 包安装到 ``$PIC_HOME/packages/<name>/<version>``
12
+ 或项目 ``pic_modules/<name>``; CIN 的 ``import "name"`` 会自动解析;
13
+ v6.4.0 起支持分块导入 ``import "name:module"`` / ``import "name::<版本>:*"``,
14
+ 不写版本时**默认使用最高已安装版本**;
15
+ * **默认安装最新版本**: ``pic install <name>`` 按中央注册表的 ``latest``
16
+ 指针解析, 不写版本时即使本地已装旧版本也会升级;
17
+ * **依赖递归安装** / **可编辑安装** 与旧版一致;
18
+ * ``PIC_OFFLINE=1`` 时退化为纯本地注册表 (离线开发/测试)。
19
+
20
+ ``pic`` 本身不执行被安装包的代码, 也不编译; 编译/运行交给 ``mkn`` / ``cvm``。
21
+ """
22
+
23
+ import argparse
24
+ import contextlib
25
+ import json
26
+ import os
27
+ import re
28
+ import shutil
29
+ import sys
30
+ import urllib.parse
31
+ import uuid
32
+ import webbrowser
33
+ from dataclasses import dataclass
34
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
35
+
36
+ from . import __version__
37
+ from .packaging import archive, vcs
38
+ from .packaging.model import (
39
+ Dependency,
40
+ ManifestError,
41
+ PackageMeta,
42
+ load_package_manifest,
43
+ satisfies,
44
+ validate_name,
45
+ validate_version,
46
+ )
47
+ from .packaging.spec import SpecError, parse_package_spec
48
+ from .packaging.store import (
49
+ InstalledPackage,
50
+ PackageStore,
51
+ copy_package_tree,
52
+ default_store,
53
+ project_modules_dir,
54
+ resolve_link,
55
+ )
56
+ from .packaging.toml import dumps as toml_dumps
57
+ from .packaging.toml import load as toml_load
58
+ from .pic_api import (
59
+ DEFAULT_API_BASE,
60
+ ApiError,
61
+ AuthStore,
62
+ CdifitClient,
63
+ TwoFactorRequired,
64
+ client_from_store,
65
+ )
66
+ from .pic_login import AuthError, run_login_flow
67
+ from .pic_registry import (
68
+ DEFAULT_REGISTRY_URL,
69
+ RegistryClient,
70
+ RegistryError,
71
+ iter_package_files,
72
+ manifest_digest,
73
+ package_modules,
74
+ source_digest,
75
+ )
76
+
77
+ __all__ = ['main', 'install_spec', 'install_path', 'install_git',
78
+ 'install_named', 'build_package', 'write_project_lock']
79
+
80
+ _META_FILE = '.pic-meta.json'
81
+ _IGNORE = shutil.ignore_patterns(
82
+ '.git', '.hg', '.svn', '__pycache__', '*.pyc', '.pytest_cache',
83
+ '.ruff_cache', 'dist', 'build', 'target', 'pic_modules', '.pic', '.mkn',
84
+ 'node_modules', '.venv', 'venv', '*.cinpkg')
85
+
86
+ #: 进程内缓存的已登录客户端 (一次 CLI 调用只弹一次浏览器)
87
+ _CLIENT: Optional[CdifitClient] = None
88
+ _CLIENT_HOME: Optional[str] = None
89
+
90
+
91
+ class PicError(RuntimeError):
92
+ """pic 命令的可预期失败 (不打印 traceback)。"""
93
+
94
+
95
+ # ==================== 配置 / 登录 ====================
96
+
97
+
98
+ @dataclass
99
+ class PicConfig:
100
+ api_base: str = DEFAULT_API_BASE
101
+ registry_url: str = DEFAULT_REGISTRY_URL
102
+ offline: bool = False
103
+
104
+
105
+ def _pic_home() -> str:
106
+ return os.path.abspath(os.environ.get('PIC_HOME')
107
+ or os.path.join(os.path.expanduser('~'), '.pic'))
108
+
109
+
110
+ def _read_config() -> Dict[str, Any]:
111
+ path = os.path.join(_pic_home(), 'config.toml')
112
+ if not os.path.isfile(path):
113
+ return {}
114
+ try:
115
+ return toml_load(path)
116
+ except Exception: # noqa: BLE001 - 配置损坏不应让所有命令崩溃
117
+ return {}
118
+
119
+
120
+ def load_config() -> PicConfig:
121
+ data = _read_config()
122
+ registry = data.get('registry') or {}
123
+ login = data.get('login') or {}
124
+ env_offline = os.environ.get('PIC_OFFLINE', '').lower() in (
125
+ '1', 'true', 'yes', 'on')
126
+ api_base = os.environ.get('PIC_API_BASE') or registry.get('api_base')
127
+ if not api_base:
128
+ saved = AuthStore().load()
129
+ api_base = saved.api_base if saved is not None else DEFAULT_API_BASE
130
+ return PicConfig(
131
+ api_base=str(api_base).rstrip('/'),
132
+ registry_url=str(os.environ.get('PIC_REGISTRY_URL')
133
+ or registry.get('url') or DEFAULT_REGISTRY_URL).rstrip('/'),
134
+ offline=env_offline or bool(registry.get('offline') or
135
+ login.get('offline') or False),
136
+ )
137
+
138
+
139
+ def _reset_client() -> None:
140
+ global _CLIENT, _CLIENT_HOME
141
+ _CLIENT = None
142
+ _CLIENT_HOME = None
143
+
144
+
145
+ def _version_key(version: str) -> Tuple[int, int, int]:
146
+ try:
147
+ return tuple(int(part) for part in version.split('-')[0].split('.'))
148
+ except ValueError:
149
+ return (0, 0, 0)
150
+
151
+
152
+ def _step(index: int, total: int, title: str) -> None:
153
+ print(f'[{index}/{total}] {title}')
154
+
155
+
156
+ def _detail(key: str, value: Any, indent: int = 6) -> None:
157
+ print(' ' * indent + f'{key:<11}: {value}')
158
+
159
+
160
+ def _fmt_size(size: int) -> str:
161
+ value = float(size)
162
+ for unit in ('B', 'KiB', 'MiB', 'GiB'):
163
+ if value < 1024 or unit == 'GiB':
164
+ return f'{value:.1f} {unit}' if unit != 'B' else f'{int(value)} B'
165
+ value /= 1024
166
+ return f'{size} B'
167
+
168
+
169
+ def get_client(*, interactive: bool = True,
170
+ open_browser: bool = True,
171
+ force_login: bool = False) -> CdifitClient:
172
+ """返回已登录客户端; 未登录时按需启动浏览器登录。"""
173
+ global _CLIENT, _CLIENT_HOME
174
+ config = load_config()
175
+ if config.offline:
176
+ raise PicError('PIC_OFFLINE=1: 中央注册表已禁用')
177
+ store = AuthStore()
178
+ state = store.load()
179
+ home = _pic_home()
180
+ if _CLIENT is not None and not force_login and home == _CLIENT_HOME \
181
+ and state is not None and _CLIENT.auth is not None \
182
+ and _CLIENT.auth.access_token == state.access_token:
183
+ return _CLIENT
184
+ if state is not None and state.api_base.rstrip('/') == config.api_base:
185
+ client = CdifitClient(config.api_base, auth=state, store=store)
186
+ try:
187
+ client.ensure_token()
188
+ _CLIENT = client
189
+ _CLIENT_HOME = home
190
+ return client
191
+ except ApiError:
192
+ # access/refresh 都失效 -> 重新登录
193
+ store.clear()
194
+ if not interactive:
195
+ raise PicError('未登录 Cdifit; 请先运行 `pic login`')
196
+ state = run_login_flow(config.api_base, store=store,
197
+ open_browser=open_browser)
198
+ client = CdifitClient(config.api_base, auth=state, store=store)
199
+ _CLIENT = client
200
+ _CLIENT_HOME = home
201
+ return client
202
+
203
+
204
+ def get_registry(*, interactive: bool = True,
205
+ open_browser: bool = True,
206
+ auth: bool = True) -> Optional[RegistryClient]:
207
+ """返回注册表客户端; ``auth=False`` 用于搜索等公开只读接口。"""
208
+ config = load_config()
209
+ if config.offline:
210
+ return None
211
+ if auth:
212
+ client = get_client(interactive=interactive, open_browser=open_browser)
213
+ token = client.auth.access_token if client.auth else ''
214
+ else:
215
+ state = AuthStore().load()
216
+ token = ''
217
+ if state is not None and state.api_base.rstrip('/') == config.api_base:
218
+ token = state.access_token
219
+ return RegistryClient(config.registry_url, token=token)
220
+
221
+
222
+ # ==================== 包文件与归档 ====================
223
+
224
+
225
+ def _strip_suffix(text: str, suffix: str) -> str:
226
+ return text[:-len(suffix)] if text.endswith(suffix) else text
227
+
228
+
229
+ def _iter_package_files(root: str) -> Iterable[Tuple[str, str]]:
230
+ return iter_package_files(root)
231
+
232
+
233
+ def build_package(root: str, out: Optional[str] = None) -> Tuple[str, PackageMeta]:
234
+ """把包目录打成 ``.cinpkg`` (含 ``META-INF/SHA256SUMS``)。"""
235
+ meta = _load_any_manifest(root)
236
+ root = meta.root
237
+ if out is None:
238
+ out = os.path.join(root, 'dist',
239
+ f'{meta.name}-{meta.version}.cinpkg')
240
+ files: Dict[str, bytes] = {}
241
+ for rel, path in _iter_package_files(root):
242
+ with open(path, 'rb') as f:
243
+ files[rel] = f.read()
244
+ # 清单以规范化形式写入, 避免发布后的包与内存中的 name/version 漂移
245
+ files['pic.toml'] = toml_dumps(meta.to_dict()).encode('utf-8')
246
+ entries = archive.build_archive_entries(files)
247
+ archive.write_zip(out, entries)
248
+ return os.path.abspath(out), meta
249
+
250
+
251
+ # ==================== 安装 ====================
252
+
253
+
254
+ def _meta_path(path: str) -> str:
255
+ return os.path.join(path, _META_FILE)
256
+
257
+
258
+ def _read_meta(path: str) -> Dict[str, Any]:
259
+ try:
260
+ with open(_meta_path(path), encoding='utf-8') as f:
261
+ return json.load(f)
262
+ except (OSError, ValueError):
263
+ return {}
264
+
265
+
266
+ def _write_meta(path: str, repo: str = '', rev: str = '',
267
+ editable: bool = False, source: str = '') -> None:
268
+ data = {'repo': repo, 'rev': rev, 'editable': editable,
269
+ 'source': source, 'installed_by': f'pic {__version__}'}
270
+ with open(_meta_path(path), 'w', encoding='utf-8', newline='\n') as f:
271
+ json.dump(data, f, ensure_ascii=False, indent=2)
272
+ f.write('\n')
273
+
274
+
275
+ def _read_installed_manifest(path: str) -> Optional[PackageMeta]:
276
+ try:
277
+ return load_package_manifest(resolve_link(path), require_entry=False)
278
+ except (ManifestError, OSError):
279
+ return None
280
+
281
+
282
+ def _load_any_manifest(root: str) -> PackageMeta:
283
+ """读取 pic.toml; 也接受 mkn 项目 (自动生成等效包元数据)。"""
284
+ pic_path = os.path.join(root, 'pic.toml')
285
+ if os.path.isfile(pic_path):
286
+ return load_package_manifest(root)
287
+ mkn_path = os.path.join(root, 'mkn.toml')
288
+ if os.path.isfile(mkn_path):
289
+ from .packaging.model import load_mkn_manifest
290
+ project = load_mkn_manifest(mkn_path)
291
+ return PackageMeta(
292
+ root=project.root, manifest_path=project.manifest_path,
293
+ name=project.name, version=project.version,
294
+ description=project.description, license=project.license,
295
+ authors=list(project.authors), entry=project.entry,
296
+ repo=project.repo, tag=project.tag,
297
+ dependencies=list(project.dependencies), raw=project.raw)
298
+ raise ManifestError(
299
+ f'{root}: 既没有 pic.toml 也没有 mkn.toml, 无法作为包安装')
300
+
301
+
302
+ def _project_existing(target_root: str, name: str) -> Optional[PackageMeta]:
303
+ path = os.path.join(target_root, name)
304
+ if not os.path.isdir(path):
305
+ return None
306
+ return _read_installed_manifest(path)
307
+
308
+
309
+ def _check_expected(meta: PackageMeta, name: Optional[str],
310
+ version: Optional[str]) -> None:
311
+ if name and meta.name != name:
312
+ raise PicError(
313
+ f'包名不匹配: 请求 {name!r}, 仓库清单为 {meta.name!r}')
314
+ if version and meta.version != version:
315
+ raise PicError(
316
+ f'版本不匹配: 请求 {version!r}, 仓库清单为 {meta.version!r}')
317
+
318
+
319
+ def _install_into(meta: PackageMeta, store: PackageStore, *,
320
+ target_root: Optional[str], editable: bool, force: bool,
321
+ repo: str = '', rev: str = '', source: str = ''
322
+ ) -> InstalledPackage:
323
+ if target_root:
324
+ target_root = os.path.abspath(target_root)
325
+ os.makedirs(target_root, exist_ok=True)
326
+ dest = os.path.join(target_root, meta.name)
327
+ existing = _read_installed_manifest(dest)
328
+ if existing is not None and existing.version == meta.version \
329
+ and not force:
330
+ return InstalledPackage(
331
+ name=meta.name, version=meta.version, path=dest,
332
+ repo=repo, rev=rev, editable=editable)
333
+ copy_package_tree(meta.root, dest, editable=editable)
334
+ if not editable:
335
+ _write_meta(dest, repo=repo, rev=rev, source=source or meta.root)
336
+ if not os.path.isfile(os.path.join(dest, 'pic.toml')):
337
+ with open(os.path.join(dest, 'pic.toml'), 'w',
338
+ encoding='utf-8', newline='\n') as f:
339
+ f.write(toml_dumps(meta.to_dict()))
340
+ return InstalledPackage(name=meta.name, version=meta.version,
341
+ path=dest, repo=repo, rev=rev,
342
+ editable=editable)
343
+
344
+ pkg = store.add(meta.root, meta.name, meta.version, repo=repo, rev=rev,
345
+ editable=editable, force=force)
346
+ if not editable:
347
+ _write_meta(pkg.path, repo=repo, rev=rev,
348
+ source=source or meta.root)
349
+ if not os.path.isfile(os.path.join(pkg.path, 'pic.toml')):
350
+ with open(os.path.join(pkg.path, 'pic.toml'), 'w',
351
+ encoding='utf-8', newline='\n') as f:
352
+ f.write(toml_dumps(meta.to_dict()))
353
+ return pkg
354
+
355
+
356
+ def _dependency_specs(meta: PackageMeta) -> List[Dependency]:
357
+ return list(meta.dependencies)
358
+
359
+
360
+ def install_path(path: str, store: PackageStore, *,
361
+ target_root: Optional[str] = None, editable: bool = False,
362
+ force: bool = False, no_deps: bool = False,
363
+ expected_name: Optional[str] = None,
364
+ expected_version: Optional[str] = None,
365
+ repo: str = '', rev: str = '',
366
+ _seen: Optional[set] = None) -> InstalledPackage:
367
+ """安装本地目录 / ``pic.toml`` / ``.cinpkg``。"""
368
+ seen = _seen if _seen is not None else set()
369
+ path = os.path.abspath(path)
370
+ tmp_dir: Optional[str] = None
371
+ try:
372
+ if os.path.isfile(path) and path.lower().endswith(('.cinpkg', '.mkn')):
373
+ # 不用 tempfile.mkdtemp: 部分受限环境会给 mkdtemp 目录加不可写 ACL
374
+ tmp_dir = os.path.join(
375
+ store.cache_dir, f'extract-{os.getpid()}-{uuid.uuid4().hex[:8]}')
376
+ os.makedirs(tmp_dir, exist_ok=True)
377
+ archive.safe_extract(path, tmp_dir)
378
+ root = tmp_dir
379
+ elif os.path.isfile(path) and os.path.basename(path) == 'pic.toml':
380
+ root = os.path.dirname(path)
381
+ elif os.path.isdir(path):
382
+ root = path
383
+ else:
384
+ raise PicError(f'不是可安装的路径或 .cinpkg: {path}')
385
+
386
+ meta = _load_any_manifest(root)
387
+ _check_expected(meta, expected_name, expected_version)
388
+ key = f'{meta.name}=={meta.version}'
389
+ if key in seen:
390
+ existing = store.get(meta.name, meta.version)
391
+ if existing is not None:
392
+ return existing
393
+ seen.add(key)
394
+
395
+ installed = _install_into(
396
+ meta, store, target_root=target_root, editable=editable,
397
+ force=force, repo=repo, rev=rev, source=root)
398
+
399
+ if not no_deps:
400
+ for dep in _dependency_specs(meta):
401
+ _install_dependency(dep, store, target_root=target_root,
402
+ force=force, seen=seen)
403
+ return installed
404
+ finally:
405
+ if tmp_dir:
406
+ shutil.rmtree(tmp_dir, ignore_errors=True)
407
+
408
+
409
+ def _cache_key(url: str, ref: Optional[str]) -> str:
410
+ import hashlib
411
+ digest = hashlib.sha256(f'{url}\0{ref or ""}'.encode()).hexdigest()[:24]
412
+ return digest
413
+
414
+
415
+ def install_git(url: str, store: PackageStore, *,
416
+ ref: Optional[str] = None, target_root: Optional[str] = None,
417
+ editable: bool = False, force: bool = False,
418
+ no_deps: bool = False, expected_name: Optional[str] = None,
419
+ expected_version: Optional[str] = None,
420
+ _seen: Optional[set] = None) -> InstalledPackage:
421
+ """从 Git 仓库安装 (浅克隆到缓存后复制)。"""
422
+ if not vcs.git_available():
423
+ raise PicError('未找到 git 命令; 从 Git 安装需要先安装 Git')
424
+ seen = _seen if _seen is not None else set()
425
+ url, inline_ref = vcs.split_git_spec(url)
426
+ ref = ref or inline_ref
427
+ cache = os.path.join(store.cache_dir, 'git', _cache_key(url, ref))
428
+ if force or not os.path.isdir(cache):
429
+ shutil.rmtree(cache, ignore_errors=True)
430
+ os.makedirs(os.path.dirname(cache), exist_ok=True)
431
+ vcs.clone(url, cache, ref=ref)
432
+ meta = _load_any_manifest(cache)
433
+ _check_expected(meta, expected_name, expected_version)
434
+ rev = ''
435
+ with contextlib.suppress(vcs.VcsError):
436
+ rev = vcs.current_rev(cache)
437
+ key = f'{meta.name}=={meta.version}'
438
+ if key in seen:
439
+ existing = store.get(meta.name, meta.version)
440
+ if existing is not None:
441
+ return existing
442
+ seen.add(key)
443
+ installed = _install_into(
444
+ meta, store, target_root=target_root, editable=editable, force=force,
445
+ repo=url, rev=rev, source=cache)
446
+ if not no_deps:
447
+ for dep in _dependency_specs(meta):
448
+ _install_dependency(dep, store, target_root=target_root,
449
+ force=force, seen=seen)
450
+ return installed
451
+
452
+
453
+ def _tag_version(tag: str) -> Optional[str]:
454
+ text = tag.strip()
455
+ if text.lower().startswith('v'):
456
+ text = text[1:]
457
+ return text if re.fullmatch(r'\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?', text) else None
458
+
459
+
460
+ def _choose_tag(url: str, constraint: str) -> Optional[str]:
461
+ """从远端标签中选一个满足约束的最高版本标签。"""
462
+ try:
463
+ tags = vcs.list_tags(url=url)
464
+ except vcs.VcsError:
465
+ return None
466
+ candidates: List[Tuple[Tuple[int, int, int], str]] = []
467
+ for tag in tags:
468
+ version = _tag_version(tag)
469
+ if version and satisfies(version, constraint):
470
+ candidates.append((tuple(int(x) for x in version.split('-')[0].split('.')),
471
+ tag))
472
+ if not candidates:
473
+ return None
474
+ candidates.sort()
475
+ return candidates[-1][1]
476
+
477
+
478
+ def install_named(name: str, constraint: str, store: PackageStore, *,
479
+ target_root: Optional[str] = None, editable: bool = False,
480
+ force: bool = False, no_deps: bool = False,
481
+ _seen: Optional[set] = None) -> InstalledPackage:
482
+ """按名称安装 (注册表 -> Git 仓库)。
483
+
484
+ 不写版本 (``pic install rich``) 时默认安装**最新版本**: 在线时按中央
485
+ 注册表的 ``latest`` 指针/最高未撤回版本解析, 即使本地已安装旧版本也会
486
+ 升级; 指定 ``rich@^1.1`` / ``rich@1.1.1`` 时保持"满足约束即可"的旧语义。
487
+ """
488
+ validate_name(name)
489
+ constraint = str(constraint or '').strip()
490
+ if constraint.lower() in ('latest', 'any'):
491
+ constraint = ''
492
+ latest_only = not constraint
493
+
494
+ # 1) 明确版本约束: 已安装且满足约束时直接复用 (不强制联网)
495
+ if not latest_only:
496
+ if target_root:
497
+ existing = _project_existing(target_root, name)
498
+ if existing is not None and satisfies(existing.version, constraint) \
499
+ and not force:
500
+ return InstalledPackage(name=name, version=existing.version,
501
+ path=os.path.join(target_root, name))
502
+ else:
503
+ for version in sorted(store.versions(name), key=_version_key,
504
+ reverse=True):
505
+ if satisfies(version, constraint):
506
+ pkg = store.get(name, version)
507
+ if pkg is not None:
508
+ # 显式指定版本时同时切换 current, 让 `import "name"`
509
+ # 与 `pic install name@version` 的期望一致。
510
+ store.set_current(name, version)
511
+ return pkg
512
+
513
+ # 2) 中央注册表 (在线)
514
+ config = load_config()
515
+ registry = None if config.offline else get_registry(interactive=True)
516
+ if registry is not None:
517
+ installed = None
518
+ try:
519
+ repo, version, registered = registry.resolve(
520
+ name, '' if latest_only else constraint)
521
+ artifact_sha = str(registered.get('archive_sha256') or '')
522
+ use_artifact = bool(artifact_sha and registered.get('artifact_url'))
523
+ _detail('中央注册表', registry.base_url)
524
+ _detail('解析', f'{name}@{version}'
525
+ + (f' (约束 {constraint})' if constraint else ' (最新)'))
526
+ _detail('获取地址', repo)
527
+ _detail('分发方式', '中央制品' if use_artifact else 'Git 仓库')
528
+ if use_artifact:
529
+ _detail('制品 SHA-256', artifact_sha)
530
+
531
+ # 已安装同一个版本: 复用 (但仍把 current 指向它)
532
+ if not force:
533
+ if target_root:
534
+ existing = _project_existing(target_root, name)
535
+ if existing is not None and existing.version == version:
536
+ return InstalledPackage(
537
+ name=name, version=version,
538
+ path=os.path.join(target_root, name), repo=repo,
539
+ rev=str(registered.get('rev') or ''))
540
+ else:
541
+ existing = store.get(name, version)
542
+ if existing is not None:
543
+ store.set_current(name, version)
544
+ return existing
545
+
546
+ if use_artifact:
547
+ cache = store.cache_path('artifacts')
548
+ dest = os.path.join(cache, f'{name}-{version}.cinpkg')
549
+ registry.download_artifact(name, version, dest, artifact_sha)
550
+ installed = install_path(
551
+ dest, store, target_root=target_root, force=force,
552
+ no_deps=no_deps, expected_name=name,
553
+ expected_version=version, repo=repo,
554
+ rev=str(registered.get('rev') or ''), _seen=_seen)
555
+ meta = _read_installed_manifest(installed.real_path)
556
+ if meta is None:
557
+ raise RegistryError(
558
+ f'安装后无法读取包清单: {installed.path}')
559
+ RegistryClient.verify_install(meta, registered)
560
+ else:
561
+ ref = str(registered.get('tag')
562
+ or registered.get('rev') or '') or None
563
+ installed = install_git(
564
+ repo, store, ref=ref, target_root=target_root,
565
+ editable=editable, force=force, no_deps=no_deps,
566
+ expected_name=name, expected_version=version, _seen=_seen)
567
+ if installed.version != version:
568
+ raise RegistryError(
569
+ f'安装版本不匹配: 注册表为 {version}, 实际为 '
570
+ f'{installed.version}')
571
+ meta = _read_installed_manifest(installed.real_path)
572
+ if meta is None:
573
+ raise RegistryError(
574
+ f'安装后无法读取包清单: {installed.path}')
575
+ RegistryClient.verify_install(meta, registered,
576
+ rev=installed.rev)
577
+ if not target_root:
578
+ store.set_current(name, installed.version)
579
+ return installed
580
+ except RegistryError as e:
581
+ if installed is not None:
582
+ if target_root:
583
+ shutil.rmtree(os.path.join(target_root, name),
584
+ ignore_errors=True)
585
+ else:
586
+ store.remove(name, installed.version)
587
+ raise PicError(str(e)) from e
588
+
589
+ # 3) 离线/本地注册表: 按登记的版本选择, 无版本则取最高
590
+ entry = store.lookup(name)
591
+ if entry and entry.get('repo'):
592
+ repo = str(entry['repo'])
593
+ versions = entry.get('versions') or {}
594
+ candidates = sorted(
595
+ (v for v in versions if satisfies(v, constraint or '*')),
596
+ key=_version_key, reverse=True)
597
+ chosen = candidates[0] if candidates else ''
598
+ if chosen:
599
+ tag = str((versions.get(chosen) or {}).get('tag') or '') \
600
+ or f'v{chosen}'
601
+ installed = install_git(
602
+ repo, store, ref=tag, target_root=target_root,
603
+ editable=editable, force=force, no_deps=no_deps,
604
+ expected_name=name, expected_version=chosen, _seen=_seen)
605
+ if not target_root:
606
+ store.set_current(name, installed.version)
607
+ return installed
608
+ if versions:
609
+ available = ', '.join(sorted(versions))
610
+ raise PicError(
611
+ f'{name} 没有满足约束 {constraint or "*"} 的版本; '
612
+ f'本地登记: {available}')
613
+ ref = _choose_tag(repo, constraint) if constraint else None
614
+ installed = install_git(repo, store, ref=ref, target_root=target_root,
615
+ editable=editable, force=force,
616
+ no_deps=no_deps, expected_name=name,
617
+ _seen=_seen)
618
+ if constraint and not satisfies(installed.version, constraint):
619
+ if target_root:
620
+ shutil.rmtree(os.path.join(target_root, name), ignore_errors=True)
621
+ else:
622
+ store.remove(name, installed.version)
623
+ raise PicError(
624
+ f'{name} 的最新可选版本 {installed.version} 不满足约束 '
625
+ f'{constraint!r}; 请检查仓库标签或放宽版本范围')
626
+ return installed
627
+
628
+ # 4) 离线且未登记仓库: 已安装包按最高版本复用
629
+ installed_versions = sorted(store.versions(name), key=_version_key,
630
+ reverse=True)
631
+ if installed_versions:
632
+ pkg = store.get(name, installed_versions[0])
633
+ if pkg is not None:
634
+ store.set_current(name, pkg.version)
635
+ return pkg
636
+ if target_root:
637
+ existing = _project_existing(target_root, name)
638
+ if existing is not None:
639
+ return InstalledPackage(name=name, version=existing.version,
640
+ path=os.path.join(target_root, name))
641
+
642
+ raise PicError(
643
+ f'未找到包 {name!r} 的仓库。\n'
644
+ f' 在线: 请确认包已通过 `pic publish` 登记到中央注册服务器;\n'
645
+ f' 离线: 可用 `pic install git+<url>` 直接安装, 或在 pic.toml 中声明 '
646
+ f'`[dependencies.{name}] git = "..."`;\n'
647
+ f' 也可用 `pic registry add <url> --name {name}` 登记本地名称。')
648
+
649
+
650
+ def _install_dependency(dep: Dependency, store: PackageStore, *,
651
+ target_root: Optional[str], force: bool,
652
+ seen: set) -> InstalledPackage:
653
+ if dep.path:
654
+ return install_path(dep.path, store, target_root=target_root,
655
+ force=force, expected_name=dep.name, _seen=seen)
656
+ if dep.git:
657
+ return install_git(dep.git, store, ref=dep.tag or dep.rev or None,
658
+ target_root=target_root, force=force,
659
+ expected_name=dep.name, _seen=seen)
660
+ return install_named(dep.name, dep.constraint, store,
661
+ target_root=target_root, force=force, _seen=seen)
662
+
663
+
664
+ def _split_name_version(spec: str) -> Tuple[str, str]:
665
+ text = spec.strip()
666
+ if '==' in text:
667
+ name, version = text.split('==', 1)
668
+ return name.strip(), version.strip()
669
+ if '@' in text and not text.startswith('git@'):
670
+ name, version = text.rsplit('@', 1)
671
+ if re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,63}', name):
672
+ return name, version.strip()
673
+ return text, ''
674
+
675
+
676
+ def install_spec(spec: str, store: PackageStore, *,
677
+ target_root: Optional[str] = None, editable: bool = False,
678
+ force: bool = False, no_deps: bool = False,
679
+ name: Optional[str] = None, version: Optional[str] = None,
680
+ ref: Optional[str] = None,
681
+ _seen: Optional[set] = None) -> InstalledPackage:
682
+ """安装任意规格: 本地路径 / .cinpkg / git+URL / name[:module][::version]。
683
+
684
+ ``name:*`` / ``name::<版本>:*`` 里的模块选择器只影响 import 写法,
685
+ 安装时始终安装整个包; 未写版本时默认安装最新版本。
686
+ """
687
+ seen = _seen if _seen is not None else set()
688
+ text = str(spec or '').strip()
689
+ if not text:
690
+ raise PicError('空的安装规格')
691
+
692
+ if text.startswith('path:'):
693
+ return install_path(text[len('path:'):], store,
694
+ target_root=target_root, editable=editable,
695
+ force=force, no_deps=no_deps,
696
+ expected_name=name, _seen=seen)
697
+ if os.path.exists(text):
698
+ return install_path(text, store, target_root=target_root,
699
+ editable=editable, force=force, no_deps=no_deps,
700
+ expected_name=name, _seen=seen)
701
+ if vcs.is_git_spec(text):
702
+ return install_git(text, store, ref=ref, target_root=target_root,
703
+ editable=editable, force=force, no_deps=no_deps,
704
+ expected_name=name, expected_version=version,
705
+ _seen=seen)
706
+
707
+ try:
708
+ package = parse_package_spec(text)
709
+ except SpecError:
710
+ package = None
711
+ if package is not None:
712
+ pkg_name = name or package.name
713
+ pkg_version = version or (
714
+ '' if package.is_latest else package.version)
715
+ return install_named(pkg_name, pkg_version, store,
716
+ target_root=target_root, editable=editable,
717
+ force=force, no_deps=no_deps, _seen=seen)
718
+
719
+ pkg_name, pkg_version = _split_name_version(text)
720
+ if name:
721
+ pkg_name = name
722
+ if version:
723
+ pkg_version = version
724
+ return install_named(pkg_name, pkg_version, store,
725
+ target_root=target_root, editable=editable,
726
+ force=force, no_deps=no_deps, _seen=seen)
727
+
728
+
729
+ # ==================== 项目锁文件 ====================
730
+
731
+
732
+ def _scan_project_packages(target_root: str) -> List[Dict[str, Any]]:
733
+ out: List[Dict[str, Any]] = []
734
+ if not os.path.isdir(target_root):
735
+ return out
736
+ for name in sorted(os.listdir(target_root)):
737
+ path = os.path.join(target_root, name)
738
+ if not os.path.isdir(path):
739
+ continue
740
+ meta = _read_installed_manifest(path)
741
+ if meta is None:
742
+ continue
743
+ info = _read_meta(path)
744
+ out.append({
745
+ 'name': meta.name,
746
+ 'version': meta.version,
747
+ 'path': os.path.relpath(resolve_link(path), target_root).replace(
748
+ os.sep, '/'),
749
+ 'repo': info.get('repo', ''),
750
+ 'rev': info.get('rev', ''),
751
+ 'editable': bool(info.get('editable', False)),
752
+ })
753
+ return out
754
+
755
+
756
+ def write_project_lock(project_root: str,
757
+ target_root: Optional[str] = None) -> Optional[str]:
758
+ """把 ``pic_modules`` 的解析结果写入 ``pic.lock``。"""
759
+ project_root = os.path.abspath(project_root)
760
+ target_root = target_root or project_modules_dir(project_root)
761
+ packages = _scan_project_packages(target_root)
762
+ if not packages:
763
+ return None
764
+ data = {'lock-version': 1, 'package': packages}
765
+ path = os.path.join(project_root, 'pic.lock')
766
+ with open(path, 'w', encoding='utf-8', newline='\n') as f:
767
+ f.write(toml_dumps(data))
768
+ return path
769
+
770
+
771
+ # ==================== 命令实现 ====================
772
+
773
+
774
+ def _guard_name(name: str) -> str:
775
+ return re.sub(r'[^A-Za-z0-9_]', '_', name)
776
+
777
+
778
+ def cmd_init(args) -> int:
779
+ root = os.path.abspath(args.path or os.getcwd())
780
+ name = args.name or os.path.basename(root.rstrip('\\/')) or 'my-package'
781
+ name = re.sub(r'[^A-Za-z0-9_-]', '-', name)
782
+ if not re.match(r'^[A-Za-z]', name):
783
+ name = 'pkg-' + name
784
+ validate_name(name)
785
+ os.makedirs(root, exist_ok=True)
786
+ manifest = os.path.join(root, 'pic.toml')
787
+ if os.path.isfile(manifest) and not args.force:
788
+ raise PicError(f'{manifest} 已存在 (使用 --force 覆盖)')
789
+ entry_rel = args.entry or f'src/{name}.cin'
790
+ entry_path = os.path.join(root, entry_rel.replace('/', os.sep))
791
+ os.makedirs(os.path.dirname(entry_path), exist_ok=True)
792
+ package = {
793
+ 'package': {
794
+ 'name': name,
795
+ 'version': args.version,
796
+ 'description': args.description or f'{name} package for Code CIN',
797
+ 'license': args.license,
798
+ 'entry': entry_rel.replace(os.sep, '/'),
799
+ 'authors': [],
800
+ },
801
+ }
802
+ if args.repo:
803
+ package['package']['repo'] = args.repo
804
+ with open(manifest, 'w', encoding='utf-8', newline='\n') as f:
805
+ f.write(toml_dumps(package))
806
+ if not os.path.isfile(entry_path):
807
+ fn = _guard_name(name)
808
+ with open(entry_path, 'w', encoding='utf-8', newline='\n') as f:
809
+ f.write(
810
+ f'// {name} - Code CIN 包入口\n'
811
+ f'// 其他项目可 `import "{name}"` 直接使用本文件中的函数。\n\n'
812
+ f'function {fn}_hello() -> string {{\n'
813
+ f' return "hello from {name}"\n'
814
+ f'}}\n')
815
+ readme = os.path.join(root, 'README.md')
816
+ if not os.path.isfile(readme):
817
+ with open(readme, 'w', encoding='utf-8', newline='\n') as f:
818
+ f.write(f'# {name}\n\nCode CIN package `{name}`.\n\n'
819
+ f'```bash\npic install git+<repo-url>\n```\n')
820
+ gitignore = os.path.join(root, '.gitignore')
821
+ if not os.path.isfile(gitignore):
822
+ with open(gitignore, 'w', encoding='utf-8', newline='\n') as f:
823
+ f.write('dist/\n*.cinpkg\npic_modules/\n__pycache__/\n')
824
+ print(f'Created package {name} {args.version} at {root}')
825
+ print(f' manifest: {manifest}')
826
+ print(f' entry : {entry_path}')
827
+ return 0
828
+
829
+
830
+ def cmd_build(args) -> int:
831
+ root = _manifest_root(args.manifest)
832
+ out, meta = build_package(root, args.output)
833
+ print(f'pic build {meta.name}@{meta.version}')
834
+ _detail('manifest', meta.manifest_path)
835
+ _detail('archive', out)
836
+ _detail('size', _fmt_size(os.path.getsize(out)))
837
+ _detail('sha256', archive.sha256_file(out))
838
+ return 0
839
+
840
+
841
+ def _manifest_root(path: Optional[str]) -> str:
842
+ if path:
843
+ path = os.path.abspath(path)
844
+ return os.path.dirname(path) if os.path.isfile(path) else path
845
+ return os.getcwd()
846
+
847
+
848
+ def cmd_publish(args) -> int:
849
+ root = _manifest_root(args.manifest)
850
+ manifest_path = os.path.join(root, 'pic.toml')
851
+ meta = _load_any_manifest(root)
852
+ root = meta.root
853
+ if args.name and args.name != meta.name:
854
+ validate_name(args.name)
855
+ meta.name = args.name
856
+ if args.version:
857
+ validate_version(args.version)
858
+ meta.version = args.version
859
+ if args.repo:
860
+ meta.repo = args.repo
861
+ if not meta.repo:
862
+ raise PicError(
863
+ '发布需要 Git 仓库地址: 使用 `--repo <git-url>` 或在 pic.toml '
864
+ '的 [package].repo 中填写')
865
+ if not vcs.git_available():
866
+ raise PicError('未找到 git 命令; 发布需要 Git')
867
+
868
+ config = load_config()
869
+ registry = None if config.offline else get_registry(interactive=True)
870
+ if registry is not None and not vcs.is_repo(root):
871
+ raise PicError(
872
+ '发布到中央注册表需要 Git 仓库: 请在包目录执行 git init/commit, '
873
+ '或使用 PIC_OFFLINE=1 仅登记本地注册表')
874
+
875
+ print(f'pic publish {meta.name}@{meta.version}')
876
+ _step(1, 8, '认证 / 配置')
877
+ auth = AuthStore().load()
878
+ if auth is not None:
879
+ _detail('Cdifit 用户', f'{auth.display_name} <{auth.email}>')
880
+ else:
881
+ _detail('登录', '离线模式 (未登录)')
882
+ _detail('注册服务器', config.registry_url)
883
+ _detail('Git 仓库', meta.repo)
884
+ _step(2, 8, '清单')
885
+ _detail('包名', meta.name)
886
+ _detail('版本', meta.version)
887
+ _detail('入口', meta.entry_rel)
888
+ _detail('清单文件', manifest_path)
889
+
890
+ if vcs.is_repo(root):
891
+ _step(3, 8, 'Git 工作区检查')
892
+ _detail('仓库', root)
893
+ if not args.allow_dirty and not vcs.is_clean(root):
894
+ raise PicError(
895
+ 'Git 工作区不干净; 先提交改动, 或使用 --allow-dirty 强制发布')
896
+ _detail('工作区', 'clean')
897
+ elif args.push:
898
+ raise PicError('--push 需要在 Git 仓库内运行 (未找到 .git)')
899
+
900
+ # 回写规范化清单 (name/version/repo/tag)。注意: 这一步会修改工作区,
901
+ # 因此 --push 要求用户先把清单改动提交, 保证标签指向的提交包含发布元数据。
902
+ rewrite = bool(args.repo or args.name or args.version or args.tag)
903
+ if rewrite:
904
+ if args.tag:
905
+ meta.tag = args.tag
906
+ with open(manifest_path, 'w', encoding='utf-8', newline='\n') as f:
907
+ f.write(toml_dumps(meta.to_dict()))
908
+ if args.push and vcs.is_repo(root) and not args.allow_dirty \
909
+ and not vcs.is_clean(root):
910
+ raise PicError(
911
+ '发布元数据已写入 pic.toml, 但工作区随之变脏; '
912
+ '请先提交该文件, 再重新运行 --push')
913
+
914
+ out, meta = build_package(root, args.output)
915
+ archive_sha = archive.sha256_file(out)
916
+ _step(4, 8, '构建 .cinpkg')
917
+ _detail('归档', out)
918
+ _detail('大小', _fmt_size(os.path.getsize(out)))
919
+ _detail('SHA-256', archive_sha)
920
+ _detail('源码摘要', source_digest(meta.root))
921
+ _detail('清单摘要', manifest_digest(meta))
922
+ tag = args.tag or f'v{meta.version}'
923
+ pushed = False
924
+ _step(5, 8, 'Git 标签')
925
+ if vcs.is_repo(root) and not args.no_tag:
926
+ created = vcs.create_tag(root, tag,
927
+ message=f'{meta.name} {meta.version}')
928
+ _detail('标签', tag + (' (新建)' if created else ' (已存在)'))
929
+ if args.push:
930
+ remote = args.remote or 'origin'
931
+ try:
932
+ vcs.push_tag(root, tag, remote=remote)
933
+ pushed = True
934
+ _detail('推送', f'{remote}/{tag}')
935
+ except vcs.VcsError as e:
936
+ raise PicError(f'推送标签失败: {e}') from e
937
+ else:
938
+ _detail('标签', '(跳过, 使用 Git 提交)')
939
+
940
+ store = default_store()
941
+ store.register(meta.name, meta.repo, meta.version, tag)
942
+ _step(6, 8, '本地缓存')
943
+ _detail('registry.json', '已登记 (离线回退)')
944
+
945
+ if registry is not None:
946
+ _step(7, 8, '中央注册 / 分发')
947
+ rev = ''
948
+ if vcs.is_repo(root):
949
+ with contextlib.suppress(vcs.VcsError):
950
+ rev = vcs.current_rev(root)
951
+ result = registry.publish(
952
+ meta, repo=meta.repo, tag=('' if args.no_tag else tag), rev=rev,
953
+ archive_path=out)
954
+ artifact = result.get('artifact') or {}
955
+ _detail('服务器', config.registry_url)
956
+ _detail('元数据', f'PUT /api/v1/packages/{meta.name}/{meta.version}')
957
+ _detail('制品', artifact.get('url') or '未上传')
958
+ _detail('制品大小', _fmt_size(int(artifact.get('size') or
959
+ os.path.getsize(out))))
960
+ _detail('发布者', (result.get('publisher') or {}).get('email')
961
+ or (auth.email if auth else 'unknown'))
962
+ else:
963
+ _step(7, 8, '中央注册 / 分发')
964
+ _detail('状态', '离线模式, 仅本地登记')
965
+
966
+ _step(8, 8, '完成')
967
+ _detail('包', f'{meta.name}@{meta.version}')
968
+ _detail('获取地址', meta.repo)
969
+ _detail('标签', tag + (' (pushed)' if pushed else ''))
970
+ _detail('校验和', archive_sha)
971
+ _detail('安装', f'pic install {meta.name}@{meta.version}')
972
+ _detail('导入', f'import "{meta.name}:*" (或 import "{meta.name}")')
973
+
974
+ if args.index:
975
+ index_dir = os.path.abspath(args.index)
976
+ os.makedirs(index_dir, exist_ok=True)
977
+ entry = {
978
+ 'package': {
979
+ 'name': meta.name,
980
+ 'repo': meta.repo,
981
+ 'latest': meta.version,
982
+ },
983
+ 'versions': {
984
+ meta.version: {
985
+ 'tag': tag,
986
+ 'file': os.path.basename(out),
987
+ 'sha256': archive_sha,
988
+ },
989
+ },
990
+ }
991
+ indexPath = os.path.join(index_dir, f'{meta.name}.toml')
992
+ with open(indexPath, 'w', encoding='utf-8', newline='\n') as f:
993
+ f.write(toml_dumps(entry))
994
+ _detail('索引', indexPath)
995
+ return 0
996
+
997
+
998
+ def _project_root() -> str:
999
+ from .packaging.model import find_project_root
1000
+ return find_project_root(os.getcwd()) or os.getcwd()
1001
+
1002
+
1003
+ def _target_root(args, store: PackageStore) -> Optional[str]:
1004
+ if getattr(args, 'project', False):
1005
+ return project_modules_dir(_project_root())
1006
+ return None
1007
+
1008
+
1009
+ def cmd_install(args) -> int:
1010
+ store = default_store()
1011
+ target_root = _target_root(args, store)
1012
+ installed: List[InstalledPackage] = []
1013
+ imports: List[str] = []
1014
+ print('pic install ' + (' '.join(args.specs) if args.specs else '(pic.toml)'))
1015
+ _step(1, 3, '解析安装规格')
1016
+ _detail('目标', target_root or store.root)
1017
+ _detail('模式', '可编辑' if args.editable else '复制安装')
1018
+ _detail('版本策略', '未指定版本时安装最新版本')
1019
+
1020
+ specs = list(args.specs)
1021
+ if not specs:
1022
+ manifest_path = os.path.join(os.getcwd(), 'pic.toml')
1023
+ if not os.path.isfile(manifest_path):
1024
+ raise PicError('未指定包, 且当前目录没有 pic.toml')
1025
+ meta = load_package_manifest(os.getcwd())
1026
+ seen: set = set()
1027
+ for dep in meta.dependencies:
1028
+ installed.append(_install_dependency(
1029
+ dep, store, target_root=target_root, force=args.force,
1030
+ seen=seen))
1031
+ imports.append(f'import "{dep.name}"')
1032
+ else:
1033
+ for spec in specs:
1034
+ pkg = install_spec(
1035
+ spec, store, target_root=target_root, editable=args.editable,
1036
+ force=args.force, no_deps=args.no_deps, name=args.name,
1037
+ version=args.version, ref=args.ref)
1038
+ installed.append(pkg)
1039
+ imports.append(_import_hint_for_spec(spec, pkg.name))
1040
+
1041
+ _step(2, 3, '写入锁定信息')
1042
+ if target_root:
1043
+ lock = write_project_lock(_project_root(), target_root)
1044
+ if lock:
1045
+ _detail('pic.lock', lock)
1046
+ else:
1047
+ _detail('pic.lock', '(全局安装)')
1048
+
1049
+ _step(3, 3, '安装完成')
1050
+ for index, pkg in enumerate(installed):
1051
+ meta = _read_installed_manifest(pkg.real_path)
1052
+ _detail('包', f'{pkg.name}@{pkg.version}')
1053
+ _detail('路径', pkg.real_path)
1054
+ _detail('来源', pkg.repo or '(local)')
1055
+ _detail('提交', pkg.rev or '-')
1056
+ if meta is not None:
1057
+ _detail('入口', meta.entry_rel)
1058
+ hint = imports[index] if index < len(imports) else f'import "{pkg.name}"'
1059
+ _detail('导入', hint)
1060
+ return 0
1061
+
1062
+
1063
+ def _import_hint_for_spec(spec: str, name: str) -> str:
1064
+ """把安装规格转成推荐的 import 写法。"""
1065
+ try:
1066
+ parsed = parse_package_spec(spec)
1067
+ except SpecError:
1068
+ return f'import "{name}"'
1069
+ if parsed.has_selector:
1070
+ text = name
1071
+ if parsed.version and not parsed.is_latest:
1072
+ text += '::' + parsed.version
1073
+ text += ':' + parsed.selector
1074
+ return f'import "{text}"'
1075
+ return f'import "{name}"'
1076
+
1077
+
1078
+
1079
+ def cmd_uninstall(args) -> int:
1080
+ store = default_store()
1081
+ if args.project:
1082
+ target = os.path.join(project_modules_dir(_project_root()), args.name)
1083
+ if not os.path.isdir(target):
1084
+ raise PicError(f'项目未安装: {args.name}')
1085
+ shutil.rmtree(target)
1086
+ write_project_lock(_project_root())
1087
+ print(f'Removed {args.name} from pic_modules')
1088
+ return 0
1089
+ if not store.remove(args.name, args.version):
1090
+ raise PicError(f'未安装: {args.name}'
1091
+ + (f'=={args.version}' if args.version else ''))
1092
+ print(f'Removed {args.name}'
1093
+ + (f' {args.version}' if args.version else ''))
1094
+ return 0
1095
+
1096
+
1097
+ def cmd_list(args) -> int:
1098
+ store = default_store()
1099
+ if args.project:
1100
+ target = project_modules_dir(_project_root())
1101
+ packages = _scan_project_packages(target)
1102
+ if args.json:
1103
+ print(json.dumps(packages, ensure_ascii=False, indent=2))
1104
+ return 0
1105
+ if not packages:
1106
+ print('No packages installed in this project.')
1107
+ return 0
1108
+ print('NAME VERSION SOURCE')
1109
+ for pkg in packages:
1110
+ print(f'{pkg["name"]:<20} {pkg["version"]:<11} '
1111
+ f'{pkg.get("repo") or pkg.get("path", "")}')
1112
+ return 0
1113
+ packages = store.all()
1114
+ if args.json:
1115
+ data = []
1116
+ for p in packages:
1117
+ item = p.to_dict()
1118
+ item['name'] = p.name
1119
+ item['version'] = p.version
1120
+ data.append(item)
1121
+ print(json.dumps(data, ensure_ascii=False, indent=2))
1122
+ return 0
1123
+ if not packages:
1124
+ print('No packages installed.')
1125
+ return 0
1126
+ print('NAME VERSION SOURCE')
1127
+ for pkg in packages:
1128
+ source = pkg.repo or ('editable:' + pkg.real_path if pkg.editable
1129
+ else pkg.path)
1130
+ print(f'{pkg.name:<20} {pkg.version:<11} {source}')
1131
+ return 0
1132
+
1133
+
1134
+ def cmd_show(args) -> int:
1135
+ store = default_store()
1136
+ pkg = store.get(args.name, args.version)
1137
+ if pkg is None and args.project:
1138
+ path = os.path.join(project_modules_dir(_project_root()), args.name)
1139
+ meta = _read_installed_manifest(path)
1140
+ if meta:
1141
+ pkg = InstalledPackage(meta.name, meta.version, path)
1142
+ if pkg is None:
1143
+ raise PicError(f'未安装: {args.name}')
1144
+ meta = _read_installed_manifest(pkg.real_path)
1145
+ data = {
1146
+ 'name': pkg.name,
1147
+ 'version': pkg.version,
1148
+ 'path': pkg.real_path,
1149
+ 'repo': pkg.repo or _read_meta(pkg.real_path).get('repo', ''),
1150
+ 'rev': pkg.rev or _read_meta(pkg.real_path).get('rev', ''),
1151
+ 'editable': pkg.editable,
1152
+ 'entry': (meta.entry_rel if meta else ''),
1153
+ 'dependencies': ([d.spec for d in meta.dependencies] if meta else []),
1154
+ }
1155
+ if args.json:
1156
+ print(json.dumps(data, ensure_ascii=False, indent=2))
1157
+ else:
1158
+ for key, value in data.items():
1159
+ if isinstance(value, list):
1160
+ value = ', '.join(value) if value else '-'
1161
+ print(f'{key:<12}: {value}')
1162
+ return 0
1163
+
1164
+
1165
+ def cmd_freeze(args) -> int:
1166
+ store = default_store()
1167
+ if args.project:
1168
+ lock = write_project_lock(_project_root())
1169
+ if lock is None:
1170
+ print('No packages installed in this project.')
1171
+ return 0
1172
+ print(lock)
1173
+ return 0
1174
+ lines = ['# pic freeze (global)', '']
1175
+ for pkg in store.all():
1176
+ lines.append(f'{pkg.name}=={pkg.version}'
1177
+ + (f' # {pkg.repo}' if pkg.repo else ''))
1178
+ text = '\n'.join(lines) + '\n'
1179
+ if args.output:
1180
+ with open(args.output, 'w', encoding='utf-8', newline='\n') as f:
1181
+ f.write(text)
1182
+ print(args.output)
1183
+ else:
1184
+ sys.stdout.write(text)
1185
+ return 0
1186
+
1187
+
1188
+ def cmd_search(args) -> int:
1189
+ config = load_config()
1190
+ query = str(args.query or '').strip()
1191
+ params: Dict[str, Any] = {
1192
+ 'limit': getattr(args, 'limit', 0) or 0,
1193
+ 'offset': getattr(args, 'offset', 0) or 0,
1194
+ 'sort': getattr(args, 'sort', '') or '',
1195
+ 'order': getattr(args, 'order', '') or '',
1196
+ 'keyword': getattr(args, 'keyword', '') or '',
1197
+ }
1198
+ if config.offline:
1199
+ records, total = _offline_search(query, params)
1200
+ if args.json:
1201
+ print(json.dumps({'packages': records, 'total': total,
1202
+ 'count': len(records), 'offline': True},
1203
+ ensure_ascii=False, indent=2))
1204
+ return 0
1205
+ _print_search_header(query, config, len(records), total, offline=True)
1206
+ _print_package_table(records)
1207
+ return 0
1208
+
1209
+ registry = get_registry(interactive=True, auth=False)
1210
+ result = registry.search(query, **params)
1211
+ records = result.get('packages') or []
1212
+ total = int(result.get('total') or len(records))
1213
+ if args.json:
1214
+ print(json.dumps(result, ensure_ascii=False, indent=2))
1215
+ return 0
1216
+ _print_search_header(query, config, len(records), total, offline=False)
1217
+ _print_package_table(records)
1218
+ return 0
1219
+
1220
+
1221
+ def _print_search_header(query: str, config: PicConfig, count: int,
1222
+ total: int, *, offline: bool) -> None:
1223
+ print(f'pic search {query or "*"}')
1224
+ print(f' registry: {config.registry_url if not offline else "local"}')
1225
+ if total != count:
1226
+ print(f' results : {count} / {total}')
1227
+ else:
1228
+ print(f' results : {count}')
1229
+
1230
+
1231
+ def _print_package_table(records: Sequence[Dict[str, Any]]) -> None:
1232
+ if not records:
1233
+ print('No matching packages in registry.')
1234
+ return
1235
+ print(f'{"NAME":<20} {"LATEST":<11} {"VERSIONS":>8} {"DOWNLOADS":>9} '
1236
+ f'DESCRIPTION')
1237
+ for record in records:
1238
+ name = str(record.get('name') or '')
1239
+ latest = str(record.get('latest') or '-')
1240
+ versions = int(record.get('versions') or 0)
1241
+ downloads = int(record.get('downloads') or 0)
1242
+ description = str(record.get('description')
1243
+ or record.get('repo') or '').replace('\n', ' ')
1244
+ if len(description) > 52:
1245
+ description = description[:51] + '…'
1246
+ print(f'{name:<20} {latest:<11} {versions:>8} {downloads:>9} '
1247
+ f'{description}')
1248
+
1249
+
1250
+ def _offline_search(query: str,
1251
+ params: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], int]:
1252
+ store = default_store()
1253
+ text = query.lower()
1254
+ rows: Dict[str, Dict[str, Any]] = {}
1255
+ data = store.load_registry().get('packages', {})
1256
+ for name, entry in data.items():
1257
+ repo = str(entry.get('repo') or '')
1258
+ versions = sorted((entry.get('versions') or {}).keys(),
1259
+ key=_version_key, reverse=True)
1260
+ if text and text not in name.lower() and text not in repo.lower():
1261
+ continue
1262
+ rows[name] = {
1263
+ 'name': name, 'repo': repo,
1264
+ 'latest': versions[0] if versions else '-',
1265
+ 'versions': len(versions), 'downloads': 0,
1266
+ 'description': '',
1267
+ }
1268
+ for pkg in store.all():
1269
+ if text and text not in pkg.name.lower():
1270
+ continue
1271
+ row = rows.setdefault(pkg.name, {
1272
+ 'name': pkg.name, 'repo': pkg.repo, 'latest': pkg.version,
1273
+ 'versions': len(store.versions(pkg.name)), 'downloads': 0,
1274
+ 'description': '(installed)',
1275
+ })
1276
+ row['latest'] = store.versions(pkg.name)[-1] if store.versions(
1277
+ pkg.name) else row['latest']
1278
+ keyword = str(params.get('keyword') or '').lower()
1279
+ items = [row for row in rows.values()
1280
+ if not keyword or keyword in str(row.get('description', '')).lower()]
1281
+ sort = params.get('sort') or 'name'
1282
+ reverse = (params.get('order') or '').lower() != 'asc'
1283
+ if sort == 'name':
1284
+ items.sort(key=lambda item: item['name'].lower(),
1285
+ reverse=(params.get('order') or '').lower() == 'desc')
1286
+ elif sort == 'downloads':
1287
+ items.sort(key=lambda item: item['downloads'], reverse=reverse)
1288
+ elif sort == 'versions':
1289
+ items.sort(key=lambda item: item['versions'], reverse=reverse)
1290
+ elif sort == 'latest':
1291
+ items.sort(key=lambda item: _version_key(item['latest']), reverse=reverse)
1292
+ offset = int(params.get('offset') or 0)
1293
+ limit = int(params.get('limit') or 0)
1294
+ total = len(items)
1295
+ page = items[offset:offset + limit] if limit > 0 else items[offset:]
1296
+ return page, total
1297
+
1298
+
1299
+ def cmd_versions(args) -> int:
1300
+ name = args.name.strip()
1301
+ validate_name(name)
1302
+ config = load_config()
1303
+ installed = default_store().versions(name)
1304
+ if config.offline:
1305
+ rows = _local_version_rows(name, installed)
1306
+ source = 'local'
1307
+ else:
1308
+ registry = get_registry(interactive=True, auth=False)
1309
+ rows = registry.version_list(name)
1310
+ source = config.registry_url
1311
+ if args.json:
1312
+ print(json.dumps({'name': name, 'registry': source,
1313
+ 'installed': installed, 'versions': rows},
1314
+ ensure_ascii=False, indent=2))
1315
+ return 0
1316
+ print(f'pic versions {name}')
1317
+ print(f' registry : {source}')
1318
+ print(f' installed: {", ".join(installed) if installed else "-"}')
1319
+ if not rows:
1320
+ print(' (no versions)')
1321
+ return 0
1322
+ print(f'{"VERSION":<14} {"TAG":<16} {"STATUS":<10} {"SIZE":>10} '
1323
+ f'PUBLISHED')
1324
+ for row in rows:
1325
+ version = str(row.get('version') or '')
1326
+ tag = str(row.get('tag') or '-')
1327
+ flags = []
1328
+ if row.get('latest'):
1329
+ flags.append('latest')
1330
+ if row.get('yanked'):
1331
+ flags.append('yanked')
1332
+ if version in installed:
1333
+ flags.append('installed')
1334
+ size = _fmt_size(int(row.get('archive_size') or 0))
1335
+ published = str(row.get('published_at') or '')[:19].replace('T', ' ')
1336
+ print(f'{version:<14} {tag:<16} {" ".join(flags) or "-":<10} '
1337
+ f'{size:>10} {published}')
1338
+ return 0
1339
+
1340
+
1341
+ def _local_version_rows(name: str,
1342
+ installed: Sequence[str]) -> List[Dict[str, Any]]:
1343
+ store = default_store()
1344
+ entry = store.lookup(name) or {}
1345
+ rows = []
1346
+ for version, info in sorted((entry.get('versions') or {}).items(),
1347
+ key=lambda item: _version_key(item[0]),
1348
+ reverse=True):
1349
+ rows.append({
1350
+ 'version': version,
1351
+ 'tag': (info or {}).get('tag') or '-',
1352
+ 'yanked': False,
1353
+ 'latest': version == (installed[-1] if installed else ''),
1354
+ 'archive_size': 0,
1355
+ 'published_at': '',
1356
+ })
1357
+ for version in sorted(installed, key=_version_key, reverse=True):
1358
+ if all(row['version'] != version for row in rows):
1359
+ rows.append({'version': version, 'tag': '-',
1360
+ 'yanked': False, 'latest': version == installed[-1],
1361
+ 'archive_size': 0, 'published_at': ''})
1362
+ return rows
1363
+
1364
+
1365
+ def cmd_info(args) -> int:
1366
+ name = args.name.strip()
1367
+ validate_name(name)
1368
+ config = load_config()
1369
+ data: Dict[str, Any] = {'name': name}
1370
+ if config.offline:
1371
+ data['offline'] = True
1372
+ entry = default_store().lookup(name) or {}
1373
+ data.update({'repo': entry.get('repo', ''),
1374
+ 'versions': [{'version': version} for version in sorted(
1375
+ entry.get('versions') or {})]})
1376
+ else:
1377
+ registry = get_registry(interactive=True, auth=False)
1378
+ record = registry.get_package(name)
1379
+ if record is None:
1380
+ raise PicError(f'中央注册服务器未找到包: {name}')
1381
+ data.update({
1382
+ 'repo': record.get('repo', ''),
1383
+ 'latest': record.get('latest', ''),
1384
+ 'description': record.get('description', ''),
1385
+ 'keywords': record.get('keywords', []),
1386
+ 'license': record.get('license', ''),
1387
+ 'homepage': record.get('homepage', ''),
1388
+ 'entry': record.get('entry', ''),
1389
+ 'modules': record.get('modules', []),
1390
+ 'downloads': record.get('downloads', 0),
1391
+ 'versions': registry.version_list(name),
1392
+ })
1393
+ data['installed'] = default_store().versions(name)
1394
+ if args.json:
1395
+ print(json.dumps(data, ensure_ascii=False, indent=2))
1396
+ return 0
1397
+ print(f'pic info {name}')
1398
+ _detail('仓库', data.get('repo') or '-')
1399
+ _detail('最新', data.get('latest') or '-')
1400
+ _detail('描述', data.get('description') or '-')
1401
+ _detail('关键词', ', '.join(data.get('keywords') or []) or '-')
1402
+ _detail('许可证', data.get('license') or '-')
1403
+ _detail('主页', data.get('homepage') or '-')
1404
+ _detail('入口', data.get('entry') or '-')
1405
+ _detail('模块', ', '.join(data.get('modules') or []) or '-')
1406
+ _detail('下载', data.get('downloads') or 0)
1407
+ _detail('已安装', ', '.join(data.get('installed') or []) or '-')
1408
+ versions = data.get('versions') or []
1409
+ if isinstance(versions, list):
1410
+ _detail('版本', ', '.join(str(row.get('version'))
1411
+ for row in versions) or '-')
1412
+ return 0
1413
+
1414
+
1415
+ def cmd_yank(args) -> int:
1416
+ name, version = _name_version_pair(args.name, args.version)
1417
+ config = load_config()
1418
+ if config.offline:
1419
+ raise PicError('yank 需要连接中央注册服务器 (PIC_OFFLINE=1 已禁用)')
1420
+ registry = get_registry(interactive=True)
1421
+ registry.yank(name, version, yanked=not args.undo)
1422
+ action = '恢复' if args.undo else '撤回'
1423
+ print(f'{action} {name}@{version}')
1424
+ return 0
1425
+
1426
+
1427
+ def cmd_latest(args) -> int:
1428
+ name, version = _name_version_pair(args.name, args.version)
1429
+ config = load_config()
1430
+ if config.offline:
1431
+ raise PicError('latest 需要连接中央注册服务器 (PIC_OFFLINE=1 已禁用)')
1432
+ registry = get_registry(interactive=True)
1433
+ result = registry.set_latest(name, version)
1434
+ print(f'latest -> {name}@{version}')
1435
+ if result.get('latest'):
1436
+ _detail('最新', result['latest'])
1437
+ return 0
1438
+
1439
+
1440
+ def cmd_use(args) -> int:
1441
+ """切换本地 ``current`` 版本 (不影响 CIN import 的“默认最新”规则)。"""
1442
+ store = default_store()
1443
+ text = str(args.name or '').strip()
1444
+ name, inline = _split_name_version(text)
1445
+ validate_name(name)
1446
+ version = (args.version or inline or '').strip().lstrip('vV')
1447
+ if not version:
1448
+ installed = sorted(store.versions(name), key=_version_key,
1449
+ reverse=True)
1450
+ if not installed:
1451
+ raise PicError(f'未安装: {name}')
1452
+ version = installed[0]
1453
+ validate_version(version)
1454
+ store.set_current(name, version)
1455
+ print(f'{name} -> {version}')
1456
+ return 0
1457
+
1458
+
1459
+ def _name_version_pair(name_spec: str,
1460
+ version: Optional[str]) -> Tuple[str, str]:
1461
+ text = str(name_spec or '').strip()
1462
+ name, inline = _split_name_version(text)
1463
+ resolved = (version or inline or '').strip().lstrip('vV')
1464
+ if not resolved:
1465
+ raise PicError('需要指定版本: pic <命令> <包名> <版本> 或 <包名>@<版本>')
1466
+ validate_name(name)
1467
+ validate_version(resolved)
1468
+ return name, resolved
1469
+
1470
+
1471
+ def cmd_modules(args) -> int:
1472
+ name = args.name.strip()
1473
+ validate_name(name)
1474
+ store = default_store()
1475
+ version = args.version
1476
+ path: Optional[str] = None
1477
+ if args.project:
1478
+ candidate = os.path.join(project_modules_dir(_project_root()), name)
1479
+ if os.path.isdir(candidate):
1480
+ path = candidate
1481
+ if path is None and store.versions(name):
1482
+ pkg = store.get(name, version)
1483
+ if pkg is not None:
1484
+ path = pkg.real_path
1485
+ modules: List[str] = []
1486
+ source = ''
1487
+ if path is not None:
1488
+ modules = package_modules(path)
1489
+ source = path
1490
+ elif not load_config().offline:
1491
+ registry = get_registry(interactive=True, auth=False)
1492
+ record = registry.get_package(name)
1493
+ if record is None:
1494
+ raise PicError(f'未安装且中央注册服务器未找到包: {name}')
1495
+ modules = [str(item) for item in record.get('modules') or []]
1496
+ source = 'central registry'
1497
+ if path is None and load_config().offline:
1498
+ raise PicError(f'未安装: {name} (PIC_OFFLINE=1 时无法查询远程模块列表)')
1499
+ if args.json:
1500
+ print(json.dumps({'name': name, 'source': source,
1501
+ 'modules': modules}, ensure_ascii=False, indent=2))
1502
+ return 0
1503
+ print(f'pic modules {name}')
1504
+ print(f' source: {source or "(unknown)"}')
1505
+ if not modules:
1506
+ print(' (no importable modules)')
1507
+ return 0
1508
+ public = [module for module in modules
1509
+ if not _is_private_module(module)]
1510
+ private = [module for module in modules if _is_private_module(module)]
1511
+ for module in public:
1512
+ print(f' {module}')
1513
+ if private:
1514
+ print(' -- 私有模块 (需显式选择, 可能连带入口) --')
1515
+ for module in private:
1516
+ print(f' {module}')
1517
+ print()
1518
+ print(f' 导入全部公开模块: import "{name}:*"')
1519
+ suggestions = [module for module in (public or modules) if module != name]
1520
+ if not suggestions:
1521
+ print(f' 导入入口: import "{name}"')
1522
+ return 0
1523
+ for module in suggestions[:5]:
1524
+ print(f' 导入单个模块: import "{name}:{module}"')
1525
+ if len(suggestions) > 5:
1526
+ print(f' 其余模块同理: import "{name}:<模块名>"')
1527
+ return 0
1528
+
1529
+
1530
+ def _is_private_module(module: str) -> bool:
1531
+ first = module.replace('\\', '/').split('/')[0]
1532
+ return first in ('internal', 'private', 'test', 'tests', 'demo',
1533
+ 'demos', 'example', 'examples')
1534
+
1535
+
1536
+ def cmd_admin(args) -> int:
1537
+ config = load_config()
1538
+ if config.offline:
1539
+ raise PicError('后台管理需要连接中央注册服务器 (PIC_OFFLINE=1 已禁用)')
1540
+ client = get_client(interactive=True)
1541
+ token = client.auth.access_token if client.auth else ''
1542
+ if args.print_token:
1543
+ print(token)
1544
+ return 0
1545
+ url = config.registry_url.rstrip('/') + '/admin'
1546
+ if token:
1547
+ url += '#token=' + urllib.parse.quote(token, safe='')
1548
+ print('pic admin')
1549
+ _detail('后台', config.registry_url.rstrip('/') + '/admin')
1550
+ _detail('说明', '令牌放在 URL fragment, 不会发送给服务器; 可随时清除')
1551
+ if not args.no_browser:
1552
+ opened = webbrowser.open(url)
1553
+ _detail('浏览器', '已打开' if opened else '未能自动打开')
1554
+ if args.print_url:
1555
+ print(url)
1556
+ return 0
1557
+
1558
+
1559
+
1560
+ def cmd_registry(args) -> int:
1561
+ store = default_store()
1562
+ if args.action == 'add':
1563
+ raw_name = args.name
1564
+ url = args.url
1565
+ if url is None:
1566
+ url = raw_name
1567
+ raw_name = args.option_name
1568
+ if not url:
1569
+ raise PicError('registry add 需要 Git 仓库地址: '
1570
+ 'pic registry add <name> <git-url>')
1571
+ name = raw_name or args.option_name
1572
+ if not name:
1573
+ name = os.path.basename(_strip_suffix(url.rstrip('/'), '.git'))
1574
+ store.register(name, url)
1575
+ print(f'Registered {name} -> {url} (local fallback)')
1576
+ return 0
1577
+ if args.action == 'remove':
1578
+ data = store.load_registry()
1579
+ if data.get('packages', {}).pop(args.name, None) is None:
1580
+ raise PicError(f'本地注册表没有 {args.name}')
1581
+ store.save_registry(data)
1582
+ print(f'Unregistered {args.name}')
1583
+ return 0
1584
+
1585
+ config = load_config()
1586
+ if not config.offline:
1587
+ registry = get_registry(interactive=True, auth=False)
1588
+ records = registry.list_packages()
1589
+ if not records:
1590
+ print('Central registry is empty.')
1591
+ return 0
1592
+ print('NAME LATEST REPO')
1593
+ for record in sorted(records, key=lambda item: item.get('name', '')):
1594
+ latest = str(record.get('latest') or '-')
1595
+ print(f'{record.get("name", ""):<20} {latest:<11} '
1596
+ f'{record.get("repo", "")}')
1597
+ return 0
1598
+
1599
+ data = store.load_registry().get('packages', {})
1600
+ if not data:
1601
+ print('Local registry is empty.')
1602
+ return 0
1603
+ print('NAME REPO')
1604
+ for name, entry in sorted(data.items()):
1605
+ print(f'{name:<20} {entry.get("repo", "")}')
1606
+ return 0
1607
+
1608
+
1609
+ def _write_config_api_base(api_base: str) -> None:
1610
+ path = os.path.join(_pic_home(), 'config.toml')
1611
+ data = _read_config()
1612
+ registry = data.setdefault('registry', {})
1613
+ if not isinstance(registry, dict):
1614
+ registry = {}
1615
+ data['registry'] = registry
1616
+ registry['api_base'] = api_base
1617
+ os.makedirs(os.path.dirname(path), exist_ok=True)
1618
+ with open(path, 'w', encoding='utf-8', newline='\n') as f:
1619
+ f.write(toml_dumps(data))
1620
+
1621
+
1622
+ def cmd_login(args) -> int:
1623
+ config = load_config()
1624
+ if args.api_base:
1625
+ config.api_base = args.api_base.rstrip('/')
1626
+ _write_config_api_base(config.api_base)
1627
+ print('pic login')
1628
+ _step(1, 3, '连接 Cdifit')
1629
+ _detail('认证地址', config.api_base)
1630
+ _detail('注册服务器', config.registry_url)
1631
+ store = AuthStore()
1632
+ existing = store.load()
1633
+ if existing is not None and not args.force \
1634
+ and existing.api_base.rstrip('/') == config.api_base:
1635
+ client = CdifitClient(config.api_base, auth=existing, store=store)
1636
+ try:
1637
+ client.userinfo()
1638
+ _step(2, 3, '已有有效会话')
1639
+ _detail('用户', f'{existing.display_name} <{existing.email}>')
1640
+ _step(3, 3, '完成')
1641
+ return 0
1642
+ except ApiError:
1643
+ store.clear()
1644
+
1645
+ _step(2, 3, '浏览器/凭据登录' if not args.email else '密码登录')
1646
+ if args.email:
1647
+ email = args.email
1648
+ password = args.password
1649
+ if not password:
1650
+ import getpass
1651
+ password = getpass.getpass('Cdifit 密码: ')
1652
+ client = CdifitClient(config.api_base, store=store)
1653
+ try:
1654
+ state = client.login(email, password)
1655
+ except TwoFactorRequired as e:
1656
+ if not args.code:
1657
+ raise PicError(
1658
+ '该账号启用了两步验证; 请追加 `--code <验证码>` 重新运行, '
1659
+ '或使用默认浏览器登录流程') from e
1660
+ state = client.finish_2fa(e.session, args.code)
1661
+ else:
1662
+ state = run_login_flow(config.api_base, store=store,
1663
+ timeout=args.timeout,
1664
+ open_browser=not args.no_browser)
1665
+ _reset_client()
1666
+ _step(3, 3, '保存令牌')
1667
+ _detail('用户', f'{state.display_name} <{state.email}>')
1668
+ _detail('API', state.api_base)
1669
+ _detail('令牌文件', store.path)
1670
+ _detail('Access 过期', state.access_expires or '(未知)')
1671
+ return 0
1672
+
1673
+
1674
+ def cmd_logout(args) -> int:
1675
+ print('pic logout')
1676
+ _step(1, 2, '撤销 Cdifit 令牌')
1677
+ store = AuthStore()
1678
+ client = client_from_store()
1679
+ if client is not None:
1680
+ client.logout()
1681
+ _detail('远程', '已请求撤销 refresh token')
1682
+ else:
1683
+ store.clear()
1684
+ _detail('本地', '没有登录记录')
1685
+ _step(2, 2, '清理本地令牌')
1686
+ _detail('auth.json', '已删除' if not os.path.isfile(store.path)
1687
+ else store.path)
1688
+ _reset_client()
1689
+ return 0
1690
+
1691
+
1692
+ def cmd_whoami(args) -> int:
1693
+ client = get_client(interactive=True)
1694
+ user = client.userinfo()
1695
+ if args.json:
1696
+ print(json.dumps(user, ensure_ascii=False, indent=2))
1697
+ return 0
1698
+ auth = client.auth
1699
+ print(f'name : {auth.display_name if auth else ""}')
1700
+ print(f'email: {auth.email if auth else ""}')
1701
+ print(f'id : {user.get("sub") or (auth.user.get("id") if auth else "")}')
1702
+ print(f'api : {client.api_base}')
1703
+ return 0
1704
+
1705
+
1706
+ def cmd_doctor(args) -> int:
1707
+ store = default_store()
1708
+ config = load_config()
1709
+ auth = AuthStore().load()
1710
+ print(f'pic {__version__}')
1711
+ print(f'home : {store.root}')
1712
+ print(f'git : {shutil.which("git") or "NOT FOUND"}')
1713
+ print(f'packages : {len(store.all())}')
1714
+ print(f'api base : {config.api_base}')
1715
+ print(f'registry : {config.registry_url}')
1716
+ print(f'offline : {config.offline}')
1717
+ print('login : ' + (
1718
+ f'{auth.display_name} <{auth.email}>' if auth else 'not logged in'))
1719
+ print(f'local reg : {len(store.load_registry().get("packages", {}))}')
1720
+ return 0
1721
+
1722
+
1723
+ # ==================== argparse ====================
1724
+
1725
+
1726
+ def build_parser() -> argparse.ArgumentParser:
1727
+ parser = argparse.ArgumentParser(
1728
+ prog='pic',
1729
+ description='Code CIN 包管理器 (中央注册表 + Cdifit 登录 + Git 内容源, '
1730
+ '安装后可直接 import; 支持分块导入/搜索/版本管理)')
1731
+ parser.add_argument('--version', action='version',
1732
+ version=f'pic {__version__}')
1733
+ parser.add_argument('--offline', action='store_true',
1734
+ help='禁用中央注册表, 仅使用本地 registry.json')
1735
+ sub = parser.add_subparsers(dest='command', required=True)
1736
+
1737
+ p = sub.add_parser('login', help='登录 Cdifit (默认打开浏览器)')
1738
+ p.add_argument('--email', help='直接使用邮箱登录 (不打开浏览器)')
1739
+ p.add_argument('--password', help='密码 (建议省略, 改用交互式输入)')
1740
+ p.add_argument('--code', help='两步验证码 (与 --email/--password 同用)')
1741
+ p.add_argument('--api-base', help='覆盖 Cdifit API 地址')
1742
+ p.add_argument('--no-browser', action='store_true',
1743
+ help='不自动打开浏览器, 只打印临时登录地址')
1744
+ p.add_argument('--timeout', type=float, default=300.0,
1745
+ help='浏览器登录超时秒数 (默认 300)')
1746
+ p.add_argument('--force', action='store_true', help='强制重新登录')
1747
+ p.set_defaults(func=cmd_login)
1748
+
1749
+ p = sub.add_parser('logout', help='退出 Cdifit 登录')
1750
+ p.set_defaults(func=cmd_logout)
1751
+
1752
+ p = sub.add_parser('whoami', help='显示当前登录用户')
1753
+ p.add_argument('--json', action='store_true')
1754
+ p.set_defaults(func=cmd_whoami)
1755
+
1756
+ p = sub.add_parser('init', help='创建 pic.toml 与包入口')
1757
+ p.add_argument('name', nargs='?', help='包名 (默认目录名)')
1758
+ p.add_argument('--path', help='包目录 (默认当前目录)')
1759
+ p.add_argument('--version', default='0.1.0', help='初始版本 (默认 0.1.0)')
1760
+ p.add_argument('--entry', help='入口文件 (默认 src/<name>.cin)')
1761
+ p.add_argument('--description', default='')
1762
+ p.add_argument('--license', default='MIT')
1763
+ p.add_argument('--repo', help='Git 仓库地址')
1764
+ p.add_argument('--force', action='store_true')
1765
+ p.set_defaults(func=cmd_init)
1766
+
1767
+ p = sub.add_parser('build', help='生成 .cinpkg 包归档')
1768
+ p.add_argument('--manifest', help='pic.toml 或包目录')
1769
+ p.add_argument('-o', '--output', help='输出 .cinpkg 路径')
1770
+ p.set_defaults(func=cmd_build)
1771
+
1772
+ p = sub.add_parser('publish', help='发布到中央注册表 (Cdifit)')
1773
+ p.add_argument('--manifest', help='pic.toml 或包目录')
1774
+ p.add_argument('--repo', help='Git 仓库地址')
1775
+ p.add_argument('--name', help='包标识名')
1776
+ p.add_argument('--version', help='发布版本')
1777
+ p.add_argument('--tag', help='Git 标签 (默认 v<version>)')
1778
+ p.add_argument('--no-tag', action='store_true', help='不创建 Git 标签')
1779
+ p.add_argument('--push', action='store_true', help='推送标签到远端')
1780
+ p.add_argument('--remote', default='origin')
1781
+ p.add_argument('--allow-dirty', action='store_true')
1782
+ p.add_argument('--index', help='额外写入本地分散索引目录')
1783
+ p.add_argument('-o', '--output', help='包归档输出路径')
1784
+ p.set_defaults(func=cmd_publish)
1785
+
1786
+ p = sub.add_parser('install', help='安装包 (未指定版本时安装最新版本)')
1787
+ p.add_argument('specs', nargs='*',
1788
+ help='包规格: name / name@version / name:* / '
1789
+ 'name::<版本>:* / path / git+URL / .cinpkg')
1790
+ p.add_argument('-e', '--editable', action='store_true',
1791
+ help='可编辑安装 (仅本地路径)')
1792
+ p.add_argument('--project', action='store_true',
1793
+ help='安装到当前项目 pic_modules/ (可直接 import)')
1794
+ p.add_argument('--name', help='覆盖期望包名')
1795
+ p.add_argument('--version', help='覆盖期望版本 (不写则安装最新版本)')
1796
+ p.add_argument('--ref', help='Git 引用 (标签/分支/提交)')
1797
+ p.add_argument('--force', action='store_true')
1798
+ p.add_argument('--no-deps', action='store_true', help='不安装依赖')
1799
+ p.set_defaults(func=cmd_install)
1800
+
1801
+ p = sub.add_parser('uninstall', help='卸载包')
1802
+ p.add_argument('name')
1803
+ p.add_argument('--version')
1804
+ p.add_argument('--project', action='store_true')
1805
+ p.set_defaults(func=cmd_uninstall)
1806
+
1807
+ p = sub.add_parser('list', help='列出已安装包')
1808
+ p.add_argument('--project', action='store_true')
1809
+ p.add_argument('--json', action='store_true')
1810
+ p.set_defaults(func=cmd_list)
1811
+
1812
+ p = sub.add_parser('show', help='查看包详情')
1813
+ p.add_argument('name')
1814
+ p.add_argument('--version')
1815
+ p.add_argument('--project', action='store_true')
1816
+ p.add_argument('--json', action='store_true')
1817
+ p.set_defaults(func=cmd_show)
1818
+
1819
+ p = sub.add_parser('freeze', help='输出锁定信息')
1820
+ p.add_argument('--project', action='store_true')
1821
+ p.add_argument('-o', '--output')
1822
+ p.set_defaults(func=cmd_freeze)
1823
+
1824
+ p = sub.add_parser('search', help='搜索中央注册表 (离线时搜索本地)')
1825
+ p.add_argument('query', nargs='?')
1826
+ p.add_argument('--json', action='store_true', help='输出 JSON')
1827
+ p.add_argument('--limit', type=int, default=0, help='最多返回条数 (0=全部)')
1828
+ p.add_argument('--offset', type=int, default=0, help='跳过条数')
1829
+ p.add_argument('--sort', choices=['name', 'latest', 'updated',
1830
+ 'downloads', 'versions'],
1831
+ default='', help='排序字段')
1832
+ p.add_argument('--order', choices=['asc', 'desc'], default='',
1833
+ help='排序方向')
1834
+ p.add_argument('--keyword', default='', help='按关键词过滤')
1835
+ p.set_defaults(func=cmd_search)
1836
+
1837
+ p = sub.add_parser('versions', help='列出一个包的全部版本')
1838
+ p.add_argument('name')
1839
+ p.add_argument('--json', action='store_true')
1840
+ p.set_defaults(func=cmd_versions)
1841
+
1842
+ p = sub.add_parser('info', help='查看包的远程详情 (版本/模块/下载量)')
1843
+ p.add_argument('name')
1844
+ p.add_argument('--json', action='store_true')
1845
+ p.set_defaults(func=cmd_info)
1846
+
1847
+ p = sub.add_parser('yank', help='撤回一个版本 (发布者/管理员)')
1848
+ p.add_argument('name', help='包名或 name@version')
1849
+ p.add_argument('version', nargs='?')
1850
+ p.set_defaults(func=cmd_yank, undo=False)
1851
+
1852
+ p = sub.add_parser('unyank', help='恢复一个被撤回的版本')
1853
+ p.add_argument('name', help='包名或 name@version')
1854
+ p.add_argument('version', nargs='?')
1855
+ p.set_defaults(func=cmd_yank, undo=True)
1856
+
1857
+ p = sub.add_parser('latest', help='把 latest 指针指向指定版本')
1858
+ p.add_argument('name', help='包名或 name@version')
1859
+ p.add_argument('version', nargs='?')
1860
+ p.set_defaults(func=cmd_latest)
1861
+
1862
+ p = sub.add_parser('use', help='切换本地 current 版本 (import 默认最新)')
1863
+ p.add_argument('name', help='包名或 name@version')
1864
+ p.add_argument('version', nargs='?')
1865
+ p.set_defaults(func=cmd_use)
1866
+
1867
+ p = sub.add_parser('modules', help='列出包内可 import 的模块 (分块导入)')
1868
+ p.add_argument('name')
1869
+ p.add_argument('--version')
1870
+ p.add_argument('--project', action='store_true')
1871
+ p.add_argument('--json', action='store_true')
1872
+ p.set_defaults(func=cmd_modules)
1873
+
1874
+ p = sub.add_parser('admin', help='打开 pic registry 后台管理页')
1875
+ p.add_argument('--no-browser', action='store_true')
1876
+ p.add_argument('--print-token', action='store_true',
1877
+ help='只打印 AccessToken (用于后台登录框)')
1878
+ p.add_argument('--print-url', action='store_true',
1879
+ help='同时打印带令牌的 URL (注意终端历史记录)')
1880
+ p.set_defaults(func=cmd_admin)
1881
+
1882
+ p = sub.add_parser('registry', help='本地回退注册表 / 中央列表')
1883
+ p.add_argument('action', choices=['add', 'remove', 'list'])
1884
+ p.add_argument('name', nargs='?', help='add: 包名 (或只给 URL); remove: 包名')
1885
+ p.add_argument('url', nargs='?', help='add: Git 仓库地址')
1886
+ p.add_argument('--name', dest='option_name', help='add: 包标识名')
1887
+ p.set_defaults(func=cmd_registry)
1888
+
1889
+ p = sub.add_parser('doctor', help='检查环境')
1890
+ p.set_defaults(func=cmd_doctor)
1891
+ return parser
1892
+
1893
+
1894
+ def main(argv: Optional[Sequence[str]] = None) -> int:
1895
+ from .toolkit import configure_stdio
1896
+ configure_stdio()
1897
+ parser = build_parser()
1898
+ args = parser.parse_args(list(sys.argv[1:] if argv is None else argv))
1899
+ if getattr(args, 'offline', False):
1900
+ os.environ['PIC_OFFLINE'] = '1'
1901
+ try:
1902
+ # 首次使用门禁: 除登录/退出/诊断外, 没有本地 auth.json 时先走浏览器
1903
+ # 登录。PIC_OFFLINE=1 或 config.toml 的 offline=true 可绕过 (离线开发)。
1904
+ config = load_config()
1905
+ if not config.offline and args.command not in (
1906
+ 'login', 'logout', 'doctor', 'search', 'versions', 'info',
1907
+ 'modules', 'registry') and AuthStore().load() is None:
1908
+ get_client(interactive=True)
1909
+ return int(args.func(args) or 0)
1910
+ except (PicError, SpecError, ManifestError, archive.ArchiveError,
1911
+ vcs.VcsError, ApiError, AuthError, RegistryError, OSError) as e:
1912
+ sys.stderr.write(f'pic: error: {e}\n')
1913
+ return 1
1914
+
1915
+
1916
+ if __name__ == '__main__':
1917
+ sys.exit(main())