funpub 0.1.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
funpub/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """funpub:多渠道制品发布工具"""
2
+
3
+ from funpub.channels import (
4
+ get_publisher,
5
+ list_available_channels,
6
+ list_missing_channels,
7
+ )
8
+ from funpub.core import BasePublisher, PublishResult
9
+
10
+ __version__ = "0.1.0"
11
+
12
+ __all__ = [
13
+ "get_publisher",
14
+ "list_available_channels",
15
+ "list_missing_channels",
16
+ "BasePublisher",
17
+ "PublishResult",
18
+ "__version__",
19
+ ]
@@ -0,0 +1,141 @@
1
+ """
2
+ funpub 发布渠道注册表
3
+
4
+ 渠道懒加载:``import funpub`` 不会导入任何渠道的第三方依赖,只有真正用到
5
+ 某个渠道时才会导入它。
6
+
7
+ 接入一个新渠道只需要两步:
8
+ 1. 在 ``funpub/channels/<name>/`` 下实现一个 :class:`funpub.core.BasePublisher`
9
+ 子类。
10
+ 2. 在 :data:`CHANNEL_SPECS` 里注册一行 :class:`ChannelSpec`。
11
+ """
12
+
13
+ import importlib
14
+ from typing import Any, Dict, NamedTuple, Optional, Type
15
+
16
+ from funpub.core.exceptions import ChannelNotFoundError
17
+
18
+
19
+ class ChannelSpec(NamedTuple):
20
+ """一个渠道的加载说明。"""
21
+
22
+ module: str
23
+ """相对模块路径,如 ``.aliyun``。"""
24
+
25
+ cls: str
26
+ """模块中导出的 Publisher 类名。"""
27
+
28
+ extra: Optional[str] = None
29
+ """安装该渠道所需的 pip extra;``None`` 表示只依赖核心依赖。"""
30
+
31
+ pip_target: Optional[str] = None
32
+ """``pip install`` 的目标覆写;默认是 ``funpub[<extra>]``。"""
33
+
34
+ @property
35
+ def install_hint(self) -> str:
36
+ if self.pip_target:
37
+ return self.pip_target
38
+ if self.extra:
39
+ return f"funpub[{self.extra}]"
40
+ return "funpub"
41
+
42
+
43
+ # 渠道注册表 —— 唯一的事实来源(渠道 key -> 模块/类名/pip extra)。
44
+ CHANNEL_SPECS: Dict[str, ChannelSpec] = {
45
+ "aliyun": ChannelSpec(".aliyun", "AliyunPublisher"),
46
+ }
47
+
48
+ _resolved: Dict[str, Type[Any]] = {}
49
+
50
+
51
+ def _load(spec: ChannelSpec) -> Type[Any]:
52
+ """导入并返回渠道的 Publisher 类。
53
+
54
+ Raises:
55
+ ImportError: 依赖缺失(带 pip 提示),或注册表类名有误(视为 bug)。
56
+ """
57
+ cache_key = f"{spec.module}:{spec.cls}"
58
+ if cache_key in _resolved:
59
+ return _resolved[cache_key]
60
+
61
+ try:
62
+ module = importlib.import_module(spec.module, __name__)
63
+ except ImportError as exc:
64
+ missing = getattr(exc, "name", None) or "?"
65
+ raise ImportError(
66
+ f"渠道 {spec.cls} 的依赖 {missing!r} 未安装,"
67
+ f"请运行: pip install {spec.install_hint}"
68
+ ) from exc
69
+
70
+ try:
71
+ publisher_cls = getattr(module, spec.cls)
72
+ except AttributeError as exc:
73
+ exported = ", ".join(sorted(n for n in vars(module) if n.endswith("Publisher")))
74
+ raise ImportError(
75
+ f"funpub 内部错误:模块 {spec.module} 没有导出 {spec.cls!r}。"
76
+ f"该模块实际导出的渠道类为: {exported or '(无)'}。"
77
+ f"请修正 funpub/channels/__init__.py 中的 CHANNEL_SPECS。"
78
+ ) from exc
79
+
80
+ _resolved[cache_key] = publisher_cls
81
+ return publisher_cls
82
+
83
+
84
+ def get_publisher(channel: str, *args: Any, **kwargs: Any) -> Any:
85
+ """
86
+ 根据渠道名称获取一个 Publisher 实例。
87
+
88
+ Args:
89
+ channel: 渠道名称,如 ``"aliyun"``
90
+ *args, **kwargs: 传递给渠道构造函数的参数
91
+
92
+ Returns:
93
+ BasePublisher: 渠道实例
94
+
95
+ Raises:
96
+ ChannelNotFoundError: 不支持的渠道
97
+ ImportError: 渠道依赖未安装
98
+
99
+ Examples:
100
+ >>> publisher = get_publisher("aliyun", repo_url="...", username="...", password="...")
101
+ """
102
+ key = channel.lower()
103
+ spec = CHANNEL_SPECS.get(key)
104
+ if spec is None:
105
+ available = ", ".join(sorted(CHANNEL_SPECS))
106
+ raise ChannelNotFoundError(
107
+ f"不支持的发布渠道: {channel}. 可用渠道: {available}"
108
+ )
109
+
110
+ return _load(spec)(*args, **kwargs)
111
+
112
+
113
+ def list_available_channels() -> Dict[str, Type[Any]]:
114
+ """列出当前环境中依赖已装好、可以直接实例化的渠道"""
115
+ result: Dict[str, Type[Any]] = {}
116
+ for key, spec in CHANNEL_SPECS.items():
117
+ try:
118
+ result[key] = _load(spec)
119
+ except ImportError:
120
+ continue
121
+ return result
122
+
123
+
124
+ def list_missing_channels() -> Dict[str, str]:
125
+ """列出依赖缺失的渠道及其安装命令"""
126
+ missing: Dict[str, str] = {}
127
+ for key, spec in CHANNEL_SPECS.items():
128
+ try:
129
+ _load(spec)
130
+ except ImportError:
131
+ missing[key] = spec.install_hint
132
+ return missing
133
+
134
+
135
+ __all__ = [
136
+ "get_publisher",
137
+ "list_available_channels",
138
+ "list_missing_channels",
139
+ "CHANNEL_SPECS",
140
+ "ChannelSpec",
141
+ ]
@@ -0,0 +1,3 @@
1
+ from .publisher import AliyunPublisher
2
+
3
+ __all__ = ["AliyunPublisher"]
@@ -0,0 +1,345 @@
1
+ """阿里云 Packages 制品仓库(generic 类型)REST 客户端
2
+
3
+ 覆盖官方文档描述的两套能力:
4
+
5
+ * 单次 API 上传/下载/免密下载地址(见 ``docs/aliyun/common/API上传.md``)。
6
+ * 大文件分块上传(见 ``docs/aliyun/common/大文件上传.md``)。协议细节文档
7
+ 中没有给出,是从官方 ``chunk_upload.py`` 脚本逆向出来的:创建上传会话
8
+ -> PATCH 分块 -> 触发异步合并 -> 轮询合并状态 -> 将 blob 关联到仓库路径。
9
+ """
10
+
11
+ import hashlib
12
+ import os
13
+ import re
14
+ import time
15
+ from base64 import b64encode
16
+ from typing import Any, Dict, Optional, Tuple
17
+ from urllib.parse import quote
18
+
19
+ from farlog import getLogger
20
+
21
+ from funpub.core.exceptions import (
22
+ AuthenticationError,
23
+ ChecksumMismatchError,
24
+ MergeTimeoutError,
25
+ PublishError,
26
+ RemoteNotFoundError,
27
+ )
28
+ from funpub.core.http import new_session
29
+
30
+ logger = getLogger("funpub.aliyun")
31
+
32
+ DEFAULT_CHUNK_SIZE = 100 * 1024 * 1024 # 100MB,与官方脚本默认值保持一致
33
+ DEFAULT_MERGE_POLL_INTERVAL = 3.0 # 秒
34
+ DEFAULT_MERGE_TIMEOUT = 20 * 60.0 # 秒
35
+
36
+ # repo_url 形如 https://packages.aliyun.com/api/protocol/{org_id}/generic/{repo}
37
+ _REPO_URL_RE = re.compile(r"^https?://([^/]+)/api/protocol/([^/]+)/[^/]+/([^/?]+)")
38
+
39
+
40
+ def _basic_auth_header(username: str, password: str) -> str:
41
+ token = b64encode(f"{username}:{password}".encode()).decode()
42
+ return f"Basic {token}"
43
+
44
+
45
+ def _file_md5(filepath: str, chunk_size: int = 8 * 1024 * 1024) -> str:
46
+ digest = hashlib.md5()
47
+ with open(filepath, "rb") as f:
48
+ while True:
49
+ chunk = f.read(chunk_size)
50
+ if not chunk:
51
+ break
52
+ digest.update(chunk)
53
+ return digest.hexdigest()
54
+
55
+
56
+ class AliyunClient:
57
+ """阿里云 Packages generic 仓库客户端"""
58
+
59
+ def __init__(
60
+ self,
61
+ repo_url: str,
62
+ username: str,
63
+ password: str,
64
+ timeout: float = 60.0,
65
+ ) -> None:
66
+ if not repo_url:
67
+ raise PublishError("repo_url 不能为空")
68
+ if not username or not password:
69
+ raise AuthenticationError("username/password 不能为空")
70
+
71
+ self.repo_url = repo_url.rstrip("/")
72
+ self.username = username
73
+ self.password = password
74
+
75
+ match = _REPO_URL_RE.match(self.repo_url)
76
+ if not match:
77
+ raise PublishError(
78
+ f"无法解析 repo_url: {repo_url!r},期望形如 "
79
+ "https://packages.aliyun.com/api/protocol/{org_id}/generic/{repo}"
80
+ )
81
+ self.host, self.org_id, self.repo_id = match.groups()
82
+
83
+ self._session = new_session(
84
+ timeout=timeout,
85
+ headers={"Authorization": _basic_auth_header(username, password)},
86
+ )
87
+
88
+ def close(self) -> None:
89
+ self._session.close()
90
+
91
+ def __enter__(self) -> "AliyunClient":
92
+ return self
93
+
94
+ def __exit__(self, *exc: Any) -> None:
95
+ self.close()
96
+
97
+ # ------------------------------------------------------------------ #
98
+ # 简单上传/下载(小文件,见 API上传.md)
99
+ # ------------------------------------------------------------------ #
100
+
101
+ def _files_url(self, path: str) -> str:
102
+ return f"{self.repo_url}/files/{quote(path.lstrip('/'))}"
103
+
104
+ def simple_upload(
105
+ self,
106
+ filepath: str,
107
+ path: str,
108
+ version: str,
109
+ filename: Optional[str] = None,
110
+ description: Optional[str] = None,
111
+ ) -> Dict[str, Any]:
112
+ """一次性上传整个文件,返回响应中的 ``object`` 字段"""
113
+ params: Dict[str, str] = {"version": version}
114
+ if filename:
115
+ params["fileName"] = filename
116
+ if description:
117
+ params["versionDescription"] = description
118
+
119
+ with open(filepath, "rb") as fp:
120
+ resp = self._session.post(
121
+ self._files_url(path),
122
+ params=params,
123
+ files={"file": (filename or os.path.basename(filepath), fp)},
124
+ )
125
+ self._raise_for_status(resp, "上传")
126
+ payload = self._safe_json(resp)
127
+ if not payload.get("successful", True):
128
+ raise PublishError(f"上传失败: {payload}")
129
+ return payload.get("object", {})
130
+
131
+ def download(
132
+ self,
133
+ path: str,
134
+ version: str,
135
+ dest_path: str,
136
+ chunk_size: int = 8 * 1024 * 1024,
137
+ ) -> None:
138
+ """下载文件到 dest_path"""
139
+ with self._session.get(
140
+ self._files_url(path), params={"version": version}, stream=True
141
+ ) as resp:
142
+ self._raise_for_status(resp, "下载")
143
+ with open(dest_path, "wb") as f:
144
+ for chunk in resp.iter_content(chunk_size=chunk_size):
145
+ if chunk:
146
+ f.write(chunk)
147
+
148
+ def exist(self, path: str, version: str) -> bool:
149
+ """检查指定版本的制品是否存在"""
150
+ resp = self._session.head(self._files_url(path), params={"version": version})
151
+ if resp.status_code == 404:
152
+ return False
153
+ self._raise_for_status(resp, "查询")
154
+ return True
155
+
156
+ def get_signed_download_url(self, path: str, version: str, expiration: int) -> str:
157
+ """获取临时免密下载地址,expiration 为毫秒级过期时间戳"""
158
+ resp = self._session.head(
159
+ self._files_url(path),
160
+ params={"version": version, "signUrl": "true", "expiration": expiration},
161
+ )
162
+ self._raise_for_status(resp, "生成免密下载地址")
163
+ url = resp.headers.get("x-artlab-generic-sign-url")
164
+ if not url:
165
+ raise PublishError("响应中没有 x-artlab-generic-sign-url header")
166
+ return url
167
+
168
+ # ------------------------------------------------------------------ #
169
+ # 分块上传(大文件,见 大文件上传.md)
170
+ # ------------------------------------------------------------------ #
171
+
172
+ def chunked_upload(
173
+ self,
174
+ filepath: str,
175
+ path: str,
176
+ version: str,
177
+ filename: Optional[str] = None,
178
+ description: Optional[str] = None,
179
+ chunk_size: int = DEFAULT_CHUNK_SIZE,
180
+ poll_interval: float = DEFAULT_MERGE_POLL_INTERVAL,
181
+ poll_timeout: float = DEFAULT_MERGE_TIMEOUT,
182
+ ) -> Dict[str, Any]:
183
+ """分块上传大文件:创建会话 -> 分块 PATCH -> 异步合并 -> 轮询 -> 关联仓库"""
184
+ file_size = os.path.getsize(filepath)
185
+ file_md5 = _file_md5(filepath)
186
+ logger.info(f"开始分块上传 {filepath} ({file_size} bytes, md5={file_md5})")
187
+
188
+ upload_uuid, location = self._start_blob_upload()
189
+ self._upload_chunks(location, filepath, file_size, chunk_size)
190
+ self._async_commit(upload_uuid, file_md5)
191
+ self._wait_for_merge(upload_uuid, file_md5, poll_interval, poll_timeout)
192
+ return self._associate(path, version, filename, description, file_md5)
193
+
194
+ def _blob_uploads_url(self, suffix: str = "") -> str:
195
+ return (
196
+ f"https://{self.host}/api/external/repo/{self.org_id}"
197
+ f"/GENERIC/repos/{self.repo_id}/blobs/uploads{suffix}"
198
+ )
199
+
200
+ def _start_blob_upload(self) -> Tuple[str, str]:
201
+ resp = self._session.post(
202
+ self._blob_uploads_url(), headers={"Content-Length": "0"}
203
+ )
204
+ if resp.status_code not in (201, 202):
205
+ raise PublishError(
206
+ f"创建分块上传会话失败: {resp.status_code} {resp.text[:500]}"
207
+ )
208
+ location = resp.headers.get("location")
209
+ upload_uuid = resp.headers.get("package-upload-uuid")
210
+ if not location or not upload_uuid:
211
+ raise PublishError("创建分块上传会话响应缺少 location/package-upload-uuid")
212
+ if location.startswith("/"):
213
+ location = f"https://{self.host}{location}"
214
+ return upload_uuid, location
215
+
216
+ def _upload_chunks(
217
+ self, location: str, filepath: str, file_size: int, chunk_size: int
218
+ ) -> None:
219
+ offset = 0
220
+ with open(filepath, "rb") as f:
221
+ while offset < file_size:
222
+ chunk = f.read(chunk_size)
223
+ if not chunk:
224
+ break
225
+ start, end = offset, offset + len(chunk) - 1
226
+ resp = self._session.patch(
227
+ location,
228
+ data=chunk,
229
+ headers={
230
+ "Content-Type": "application/octet-stream",
231
+ "Content-Range": f"{start}-{end}",
232
+ "Content-Length": str(len(chunk)),
233
+ },
234
+ )
235
+ if resp.status_code not in (200, 201, 202, 204):
236
+ raise PublishError(
237
+ f"分块上传失败 [{start}-{end}]: {resp.status_code} {resp.text[:500]}"
238
+ )
239
+ offset = end + 1
240
+ logger.info(f"已上传 {offset}/{file_size} bytes")
241
+
242
+ def _async_commit(self, upload_uuid: str, file_md5: str) -> None:
243
+ resp = self._session.post(
244
+ self._blob_uploads_url(f"/{upload_uuid}/async-commit"),
245
+ params={"digest": f"md5:{file_md5}"},
246
+ headers={"Content-Length": "0"},
247
+ )
248
+ if resp.status_code != 202:
249
+ raise PublishError(
250
+ f"触发异步合并失败: {resp.status_code} {resp.text[:500]}"
251
+ )
252
+
253
+ def _wait_for_merge(
254
+ self,
255
+ upload_uuid: str,
256
+ file_md5: str,
257
+ poll_interval: float,
258
+ poll_timeout: float,
259
+ ) -> None:
260
+ deadline = time.monotonic() + poll_timeout
261
+ url = self._blob_uploads_url(f"/{upload_uuid}/merge-status")
262
+
263
+ while True:
264
+ resp = self._session.get(url)
265
+ if resp.status_code == 200:
266
+ merged_md5 = resp.headers.get("x-blob-checksum-md5")
267
+ if not merged_md5:
268
+ obj = self._safe_json(resp).get("object", {})
269
+ merged_md5 = obj.get("md5")
270
+ if merged_md5 and merged_md5.lower() != file_md5.lower():
271
+ raise ChecksumMismatchError(
272
+ f"合并后 md5 不一致: 本地={file_md5} 远端={merged_md5}"
273
+ )
274
+ logger.info("分块合并完成")
275
+ return
276
+ elif resp.status_code == 202:
277
+ status = (
278
+ self._safe_json(resp).get("object", {}).get("status", "PENDING")
279
+ )
280
+ if status == "FAILED":
281
+ raise PublishError("分块合并失败")
282
+ elif resp.status_code == 404:
283
+ raise RemoteNotFoundError("分块上传会话不存在")
284
+ elif resp.status_code == 500:
285
+ obj = self._safe_json(resp)
286
+ message = obj.get("object", {}).get("errorMessage") or obj.get(
287
+ "errorMessage"
288
+ )
289
+ raise PublishError(f"分块合并失败: {message or resp.text[:500]}")
290
+ else:
291
+ raise PublishError(
292
+ f"查询合并状态失败: {resp.status_code} {resp.text[:500]}"
293
+ )
294
+
295
+ if time.monotonic() > deadline:
296
+ raise MergeTimeoutError(f"分块合并轮询超时({poll_timeout}s)")
297
+ time.sleep(poll_interval)
298
+
299
+ def _associate(
300
+ self,
301
+ path: str,
302
+ version: str,
303
+ filename: Optional[str],
304
+ description: Optional[str],
305
+ file_md5: str,
306
+ ) -> Dict[str, Any]:
307
+ params: Dict[str, str] = {"version": version}
308
+ if filename:
309
+ params["fileName"] = filename
310
+ if description:
311
+ params["versionDescription"] = description
312
+ resp = self._session.post(
313
+ self._files_url(path),
314
+ params=params,
315
+ headers={
316
+ "x-artlab-checksum-upload": "true",
317
+ "x-artlab-checksum-md5": file_md5,
318
+ },
319
+ )
320
+ if resp.status_code not in (200, 201):
321
+ raise PublishError(
322
+ f"关联制品到仓库失败: {resp.status_code} {resp.text[:500]}"
323
+ )
324
+ payload = self._safe_json(resp)
325
+ obj = payload.get("object") or {"fileMd5": file_md5}
326
+ return obj
327
+
328
+ @staticmethod
329
+ def _safe_json(resp: Any) -> Dict[str, Any]:
330
+ try:
331
+ return resp.json()
332
+ except ValueError:
333
+ return {}
334
+
335
+ @staticmethod
336
+ def _raise_for_status(resp: Any, action: str) -> None:
337
+ if resp.status_code == 401:
338
+ raise AuthenticationError(f"{action}失败: 认证失败(401)")
339
+ if resp.status_code == 404:
340
+ raise RemoteNotFoundError(f"{action}失败: 远端制品不存在(404)")
341
+ if resp.status_code >= 400:
342
+ raise PublishError(f"{action}失败: {resp.status_code} {resp.text[:500]}")
343
+
344
+
345
+ __all__ = ["AliyunClient", "DEFAULT_CHUNK_SIZE"]
@@ -0,0 +1,207 @@
1
+ """阿里云 Packages 制品仓库发布渠道"""
2
+
3
+ import os
4
+ import time
5
+ from typing import Any, Optional
6
+
7
+ from farlog import getLogger
8
+ from funsecret import read_secret
9
+
10
+ from funpub.core.base import (
11
+ BasePublisher,
12
+ PublishResult,
13
+ ensure_parent_dir,
14
+ get_filepath,
15
+ )
16
+ from funpub.core.exceptions import PublishError
17
+
18
+ from .client import DEFAULT_CHUNK_SIZE, AliyunClient
19
+
20
+ logger = getLogger("funpub.aliyun")
21
+
22
+ DEFAULT_REPO_TYPE = "generic"
23
+
24
+
25
+ class AliyunPublisher(BasePublisher):
26
+ """
27
+ 基于阿里云 Packages generic 仓库实现的发布渠道。
28
+
29
+ 阿里云账号下可以有多个仓库,同一类型(如 generic)下也可以有多个不同
30
+ 名字的仓库,因此凭证按 (repo_type, repo_name) 两级区分后存储在
31
+ funsecret 里,一个仓库只需要配置一次:
32
+
33
+ .. code-block:: bash
34
+
35
+ funsecret write {repo_url} funpub aliyun generic funpackage repo_url
36
+ funsecret write {username} funpub aliyun generic funpackage username
37
+ funsecret write {password} funpub aliyun generic funpackage password
38
+
39
+ 之后只需要传 ``repo_name``(``repo_type`` 默认 ``generic``)即可使用:
40
+
41
+ .. code-block:: python
42
+
43
+ get_publisher("aliyun", repo_name="funpackage")
44
+
45
+ 凭证解析顺序:构造参数 > funsecret(按 repo_name/repo_type 查找)。
46
+ 底层协议细节参见 ``docs/aliyun/common/`` 下的官方文档。
47
+
48
+ Args:
49
+ repo_name: 仓库名称,用于从 funsecret 中查找该仓库的 repo_url/
50
+ username/password(配合 repo_type 一起作为查找的 key)
51
+ repo_type: 仓库类型,默认 ``generic``
52
+ repo_url: 仓库地址,形如
53
+ ``https://packages.aliyun.com/api/protocol/{org_id}/generic/{repo}``;
54
+ 不传则按 repo_name/repo_type 从 funsecret 读取
55
+ username: 认证用户名,不传则按 repo_name/repo_type 从 funsecret 读取
56
+ password: 认证密码,不传则按 repo_name/repo_type 从 funsecret 读取
57
+ chunk_size: 分块上传时每块的大小,默认 100MB
58
+ chunk_threshold: 超过该大小的文件自动走分块上传,默认等于 chunk_size
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ repo_name: Optional[str] = None,
64
+ repo_type: str = DEFAULT_REPO_TYPE,
65
+ repo_url: Optional[str] = None,
66
+ username: Optional[str] = None,
67
+ password: Optional[str] = None,
68
+ chunk_size: int = DEFAULT_CHUNK_SIZE,
69
+ chunk_threshold: Optional[int] = None,
70
+ timeout: float = 60.0,
71
+ *args: Any,
72
+ **kwargs: Any,
73
+ ) -> None:
74
+ super().__init__(*args, **kwargs)
75
+
76
+ def _secret(field: str) -> Optional[str]:
77
+ if not repo_name:
78
+ return None
79
+ return read_secret(
80
+ cate1="funpub",
81
+ cate2="aliyun",
82
+ cate3=repo_type,
83
+ cate4=repo_name,
84
+ cate5=field,
85
+ )
86
+
87
+ repo_url = repo_url or _secret("repo_url")
88
+ username = username or _secret("username")
89
+ password = password or _secret("password")
90
+
91
+ if not repo_url:
92
+ raise PublishError(
93
+ "必须提供 repo_url,或提供 repo_name 并预先通过 funsecret 配置:"
94
+ "funsecret write {repo_url} funpub aliyun "
95
+ f"{repo_type} <repo_name> repo_url"
96
+ )
97
+
98
+ self.chunk_size = chunk_size
99
+ self.chunk_threshold = chunk_threshold or chunk_size
100
+ self.client = AliyunClient(
101
+ repo_url=repo_url, username=username, password=password, timeout=timeout
102
+ )
103
+
104
+ def upload_file(
105
+ self,
106
+ filepath: str,
107
+ path: str,
108
+ version: str,
109
+ filename: Optional[str] = None,
110
+ description: Optional[str] = None,
111
+ overwrite: bool = False,
112
+ chunked: Optional[bool] = None,
113
+ *args: Any,
114
+ **kwargs: Any,
115
+ ) -> PublishResult:
116
+ if not os.path.isfile(filepath):
117
+ raise FileNotFoundError(filepath)
118
+
119
+ if not overwrite and self.exist(path, version):
120
+ raise FileExistsError(
121
+ f"{path}@{version} 已存在,如需覆盖请传 overwrite=True"
122
+ )
123
+
124
+ filename = filename or os.path.basename(filepath)
125
+ file_size = os.path.getsize(filepath)
126
+ use_chunked = (
127
+ chunked if chunked is not None else file_size > self.chunk_threshold
128
+ )
129
+
130
+ logger.info(
131
+ f"上传 {filepath} -> {path}@{version} "
132
+ f"({'分块' if use_chunked else '简单'}上传, {file_size} bytes)"
133
+ )
134
+ if use_chunked:
135
+ obj = self.client.chunked_upload(
136
+ filepath,
137
+ path,
138
+ version,
139
+ filename=filename,
140
+ description=description,
141
+ chunk_size=self.chunk_size,
142
+ )
143
+ else:
144
+ obj = self.client.simple_upload(
145
+ filepath, path, version, filename=filename, description=description
146
+ )
147
+
148
+ return PublishResult(
149
+ path=path,
150
+ version=version,
151
+ url=obj.get("url"),
152
+ size=obj.get("fileSize", file_size),
153
+ md5=obj.get("fileMd5"),
154
+ sha1=obj.get("fileSha1"),
155
+ sha256=obj.get("fileSha256"),
156
+ filename=filename,
157
+ )
158
+
159
+ def download_file(
160
+ self,
161
+ path: str,
162
+ version: str,
163
+ save_dir: Optional[str] = None,
164
+ filename: Optional[str] = None,
165
+ filepath: Optional[str] = None,
166
+ overwrite: bool = False,
167
+ *args: Any,
168
+ **kwargs: Any,
169
+ ) -> bool:
170
+ dest = get_filepath(
171
+ filedir=save_dir,
172
+ filename=filename or os.path.basename(path),
173
+ filepath=filepath,
174
+ )
175
+ if os.path.exists(dest) and not overwrite:
176
+ raise FileExistsError(f"{dest} 已存在,如需覆盖请传 overwrite=True")
177
+ ensure_parent_dir(dest)
178
+ logger.info(f"下载 {path}@{version} -> {dest}")
179
+ self.client.download(path, version, dest)
180
+ return True
181
+
182
+ def exist(self, path: str, version: str, *args: Any, **kwargs: Any) -> bool:
183
+ return self.client.exist(path, version)
184
+
185
+ def get_download_url(
186
+ self,
187
+ path: str,
188
+ version: str,
189
+ expiration: Optional[int] = None,
190
+ *args: Any,
191
+ **kwargs: Any,
192
+ ) -> str:
193
+ if expiration is None:
194
+ expiration = int((time.time() + 3600) * 1000)
195
+ return self.client.get_signed_download_url(path, version, expiration)
196
+
197
+ def close(self) -> None:
198
+ self.client.close()
199
+
200
+ def __enter__(self) -> "AliyunPublisher":
201
+ return self
202
+
203
+ def __exit__(self, *exc: Any) -> None:
204
+ self.close()
205
+
206
+
207
+ __all__ = ["AliyunPublisher"]
funpub/cli.py ADDED
@@ -0,0 +1,159 @@
1
+ """funpub 命令行工具"""
2
+
3
+ import os
4
+ import time
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import typer
9
+ from farlog import configure
10
+
11
+ from funpub.channels import (
12
+ get_publisher,
13
+ list_available_channels,
14
+ list_missing_channels,
15
+ )
16
+
17
+ app = typer.Typer(help="funpub 多渠道制品发布命令行工具")
18
+
19
+
20
+ @app.callback()
21
+ def main() -> None:
22
+ """funpub command group."""
23
+ configure()
24
+
25
+
26
+ def _build_publisher(
27
+ channel: str,
28
+ repo_name: Optional[str],
29
+ repo_type: str,
30
+ repo_url: Optional[str],
31
+ username: Optional[str],
32
+ password: Optional[str],
33
+ ):
34
+ kwargs = {}
35
+ if repo_name:
36
+ kwargs["repo_name"] = repo_name
37
+ kwargs["repo_type"] = repo_type
38
+ if repo_url:
39
+ kwargs["repo_url"] = repo_url
40
+ if username:
41
+ kwargs["username"] = username
42
+ if password:
43
+ kwargs["password"] = password
44
+ return get_publisher(channel, **kwargs)
45
+
46
+
47
+ ChannelOption = typer.Option("aliyun", "--channel", "-c", help="发布渠道")
48
+ RepoNameOption = typer.Option(
49
+ None,
50
+ "--repo-name",
51
+ "-r",
52
+ help="仓库名称,用于从 funsecret 按 (repo-type, repo-name) 查找 "
53
+ "repo-url/username/password,一个仓库只需用 funsecret write 配置一次",
54
+ )
55
+ RepoTypeOption = typer.Option("generic", "--repo-type", help="仓库类型,默认 generic")
56
+ RepoUrlOption = typer.Option(
57
+ None, "--repo-url", help="仓库地址,未传则按 repo-name/repo-type 从 funsecret 读取"
58
+ )
59
+ UsernameOption = typer.Option(
60
+ None,
61
+ "--username",
62
+ help="认证用户名,未传则按 repo-name/repo-type 从 funsecret 读取",
63
+ )
64
+ PasswordOption = typer.Option(
65
+ None, "--password", help="认证密码,未传则按 repo-name/repo-type 从 funsecret 读取"
66
+ )
67
+
68
+
69
+ @app.command()
70
+ def upload(
71
+ file: Path = typer.Argument(..., help="本地文件路径", exists=True, readable=True),
72
+ path: str = typer.Argument(..., help="远端制品路径"),
73
+ version: str = typer.Option(..., "--version", "-v", help="制品版本号"),
74
+ channel: str = ChannelOption,
75
+ filename: Optional[str] = typer.Option(None, help="制品名称,默认取本地文件名"),
76
+ description: Optional[str] = typer.Option(None, help="版本描述"),
77
+ overwrite: bool = typer.Option(False, help="是否覆盖已存在的同版本制品"),
78
+ repo_name: Optional[str] = RepoNameOption,
79
+ repo_type: str = RepoTypeOption,
80
+ repo_url: Optional[str] = RepoUrlOption,
81
+ username: Optional[str] = UsernameOption,
82
+ password: Optional[str] = PasswordOption,
83
+ ) -> None:
84
+ """上传制品文件"""
85
+ publisher = _build_publisher(
86
+ channel, repo_name, repo_type, repo_url, username, password
87
+ )
88
+ result = publisher.upload_file(
89
+ filepath=str(file),
90
+ path=path,
91
+ version=version,
92
+ filename=filename,
93
+ description=description,
94
+ overwrite=overwrite,
95
+ )
96
+ typer.echo(f"上传成功: {result.get('url')}")
97
+
98
+
99
+ @app.command()
100
+ def download(
101
+ path: str = typer.Argument(..., help="远端制品路径"),
102
+ version: str = typer.Option(..., "--version", "-v", help="制品版本号"),
103
+ output: Path = typer.Option(Path("."), "--output", "-o", help="保存目录或文件路径"),
104
+ channel: str = ChannelOption,
105
+ overwrite: bool = typer.Option(False, help="是否覆盖已存在的本地文件"),
106
+ repo_name: Optional[str] = RepoNameOption,
107
+ repo_type: str = RepoTypeOption,
108
+ repo_url: Optional[str] = RepoUrlOption,
109
+ username: Optional[str] = UsernameOption,
110
+ password: Optional[str] = PasswordOption,
111
+ ) -> None:
112
+ """下载制品文件"""
113
+ publisher = _build_publisher(
114
+ channel, repo_name, repo_type, repo_url, username, password
115
+ )
116
+ if output.is_dir() or str(output).endswith(os.sep):
117
+ publisher.download_file(
118
+ path=path, version=version, save_dir=str(output), overwrite=overwrite
119
+ )
120
+ else:
121
+ publisher.download_file(
122
+ path=path, version=version, filepath=str(output), overwrite=overwrite
123
+ )
124
+ typer.echo(f"下载完成: {output}")
125
+
126
+
127
+ @app.command(name="sign-url")
128
+ def sign_url(
129
+ path: str = typer.Argument(..., help="远端制品路径"),
130
+ version: str = typer.Option(..., "--version", "-v", help="制品版本号"),
131
+ expiration_seconds: int = typer.Option(3600, help="有效期(秒)"),
132
+ channel: str = ChannelOption,
133
+ repo_name: Optional[str] = RepoNameOption,
134
+ repo_type: str = RepoTypeOption,
135
+ repo_url: Optional[str] = RepoUrlOption,
136
+ username: Optional[str] = UsernameOption,
137
+ password: Optional[str] = PasswordOption,
138
+ ) -> None:
139
+ """生成临时免密下载地址"""
140
+ publisher = _build_publisher(
141
+ channel, repo_name, repo_type, repo_url, username, password
142
+ )
143
+ expiration = int((time.time() + expiration_seconds) * 1000)
144
+ url = publisher.get_download_url(path=path, version=version, expiration=expiration)
145
+ typer.echo(url)
146
+
147
+
148
+ @app.command(name="channels")
149
+ def channels() -> None:
150
+ """列出所有已注册的发布渠道及其可用状态"""
151
+ available = list_available_channels()
152
+ missing = list_missing_channels()
153
+ for name in sorted(set(available) | set(missing)):
154
+ status = "available" if name in available else f"missing ({missing[name]})"
155
+ typer.echo(f"{name}: {status}")
156
+
157
+
158
+ if __name__ == "__main__":
159
+ app()
@@ -0,0 +1,10 @@
1
+ from . import exceptions
2
+ from .base import BasePublisher, PublishResult, ensure_parent_dir, get_filepath
3
+
4
+ __all__ = [
5
+ "BasePublisher",
6
+ "PublishResult",
7
+ "ensure_parent_dir",
8
+ "get_filepath",
9
+ "exceptions",
10
+ ]
funpub/core/base.py ADDED
@@ -0,0 +1,147 @@
1
+ """funpub 发布渠道的通用接口定义"""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Any, Dict, Optional
6
+
7
+
8
+ def get_filepath(
9
+ filedir: Optional[str] = None,
10
+ filename: Optional[str] = None,
11
+ filepath: Optional[str] = None,
12
+ ) -> str:
13
+ """根据 (filedir, filename) 或 filepath 计算出完整的本地文件路径"""
14
+ if filepath:
15
+ return str(Path(filepath).resolve())
16
+ elif filedir and filename:
17
+ return str(Path(filedir).joinpath(filename).resolve())
18
+ raise ValueError("Either filepath or (filedir and filename) must be provided")
19
+
20
+
21
+ def ensure_parent_dir(path: str) -> str:
22
+ """确保 path 的父目录存在,返回 path 本身,方便链式调用"""
23
+ parent = os.path.dirname(path)
24
+ if parent:
25
+ os.makedirs(parent, exist_ok=True)
26
+ return path
27
+
28
+
29
+ class PublishResult(dict):
30
+ """
31
+ 一次上传操作的结果。继承自 dict,支持字典式和属性式访问。
32
+
33
+ 基础字段:path、version、url、size、md5、sha1、sha256、filename。
34
+ 各渠道可以通过 ext 或额外 kwargs 附加渠道特有的信息。
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ path: str,
40
+ version: str,
41
+ url: Optional[str] = None,
42
+ size: Optional[int] = None,
43
+ md5: Optional[str] = None,
44
+ sha1: Optional[str] = None,
45
+ sha256: Optional[str] = None,
46
+ filename: Optional[str] = None,
47
+ ext: Optional[Dict[str, Any]] = None,
48
+ **kwargs: Any,
49
+ ) -> None:
50
+ base = {
51
+ "path": path,
52
+ "version": version,
53
+ "url": url,
54
+ "size": size,
55
+ "md5": md5,
56
+ "sha1": sha1,
57
+ "sha256": sha256,
58
+ "filename": filename,
59
+ }
60
+ if ext:
61
+ base.update(ext)
62
+ base.update(kwargs)
63
+ super().__init__(base)
64
+
65
+ def __getattr__(self, name: str) -> Any:
66
+ try:
67
+ return self[name]
68
+ except KeyError:
69
+ raise AttributeError(name) from None
70
+
71
+ def __setattr__(self, name: str, value: Any) -> None:
72
+ self[name] = value
73
+
74
+ def __repr__(self) -> str:
75
+ return (
76
+ f"PublishResult(path={self.get('path')!r}, "
77
+ f"version={self.get('version')!r}, url={self.get('url')!r})"
78
+ )
79
+
80
+
81
+ class BasePublisher:
82
+ """
83
+ 发布渠道基类。
84
+
85
+ 每个渠道(aliyun / pypi / oss / github-release ...)通过子类实现下列方法,
86
+ 对上层(CLI、脚本、CI)暴露统一接口。未实现的方法调用会抛出
87
+ ``NotImplementedError``,方便接入新渠道时明确知道还差什么。
88
+ """
89
+
90
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
91
+ super().__init__()
92
+
93
+ def upload_file(
94
+ self,
95
+ filepath: str,
96
+ path: str,
97
+ version: str,
98
+ filename: Optional[str] = None,
99
+ description: Optional[str] = None,
100
+ overwrite: bool = False,
101
+ *args: Any,
102
+ **kwargs: Any,
103
+ ) -> PublishResult:
104
+ """
105
+ 上传制品文件。
106
+
107
+ Args:
108
+ filepath: 本地文件路径
109
+ path: 远端制品路径(渠道内的"包名")
110
+ version: 制品版本号
111
+ filename: 制品名称,默认取本地文件名
112
+ description: 版本描述
113
+ overwrite: 是否覆盖已存在的同版本制品
114
+
115
+ Returns:
116
+ PublishResult: 上传结果,包含远端 url、校验和等信息
117
+ """
118
+ raise NotImplementedError()
119
+
120
+ def download_file(
121
+ self,
122
+ path: str,
123
+ version: str,
124
+ save_dir: Optional[str] = None,
125
+ filename: Optional[str] = None,
126
+ filepath: Optional[str] = None,
127
+ overwrite: bool = False,
128
+ *args: Any,
129
+ **kwargs: Any,
130
+ ) -> bool:
131
+ """下载制品文件到本地,返回是否成功"""
132
+ raise NotImplementedError()
133
+
134
+ def exist(self, path: str, version: str, *args: Any, **kwargs: Any) -> bool:
135
+ """检查指定版本的制品是否已存在"""
136
+ raise NotImplementedError()
137
+
138
+ def get_download_url(
139
+ self,
140
+ path: str,
141
+ version: str,
142
+ expiration: Optional[int] = None,
143
+ *args: Any,
144
+ **kwargs: Any,
145
+ ) -> str:
146
+ """获取制品的(临时)下载地址"""
147
+ raise NotImplementedError()
@@ -0,0 +1,35 @@
1
+ """funpub 统一异常定义"""
2
+
3
+
4
+ class PublishError(Exception):
5
+ """funpub 基础异常"""
6
+
7
+
8
+ class AuthenticationError(PublishError):
9
+ """认证失败,如账号密码错误或缺失"""
10
+
11
+
12
+ class RemoteNotFoundError(PublishError):
13
+ """远端制品不存在"""
14
+
15
+
16
+ class ChecksumMismatchError(PublishError):
17
+ """本地计算的校验和与远端返回值不一致"""
18
+
19
+
20
+ class MergeTimeoutError(PublishError):
21
+ """分块上传合并轮询超时"""
22
+
23
+
24
+ class ChannelNotFoundError(PublishError):
25
+ """请求了未注册的发布渠道"""
26
+
27
+
28
+ __all__ = [
29
+ "PublishError",
30
+ "AuthenticationError",
31
+ "RemoteNotFoundError",
32
+ "ChecksumMismatchError",
33
+ "MergeTimeoutError",
34
+ "ChannelNotFoundError",
35
+ ]
funpub/core/http.py ADDED
@@ -0,0 +1,78 @@
1
+ """共享 HTTP 会话工厂
2
+
3
+ 提供一个统一入口,让各渠道客户端复用同一套默认超时 + 重试 + 连接池配置,
4
+ 而不是各写各的 ``requests`` 用法。
5
+ """
6
+
7
+ from typing import Optional
8
+
9
+ import requests
10
+ from requests.adapters import HTTPAdapter
11
+ from urllib3.util.retry import Retry
12
+
13
+ DEFAULT_TIMEOUT = 60.0
14
+ DEFAULT_MAX_RETRIES = 3
15
+ DEFAULT_RETRY_DELAY = 0.5
16
+ DEFAULT_POOL_SIZE = 10
17
+
18
+ # 幂等方法才自动重试;POST/PATCH 不重试,避免分块上传/异步合并被重复提交
19
+ _RETRY_METHODS = frozenset(["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"])
20
+ _RETRY_STATUS = (429, 500, 502, 503, 504)
21
+
22
+
23
+ class TimeoutSession(requests.Session):
24
+ """带会话级默认超时的 :class:`requests.Session`。
25
+
26
+ 调用点显式传 ``timeout`` 时以调用点为准;不传则用 ``self.timeout``。
27
+ """
28
+
29
+ def __init__(self, timeout: float = DEFAULT_TIMEOUT) -> None:
30
+ super().__init__()
31
+ self.timeout = timeout
32
+
33
+ def request(self, method: str, url: str, **kwargs): # type: ignore[override]
34
+ kwargs.setdefault("timeout", self.timeout)
35
+ return super().request(method, url, **kwargs)
36
+
37
+
38
+ def new_session(
39
+ timeout: float = DEFAULT_TIMEOUT,
40
+ retries: int = DEFAULT_MAX_RETRIES,
41
+ backoff_factor: float = DEFAULT_RETRY_DELAY,
42
+ pool_size: int = DEFAULT_POOL_SIZE,
43
+ headers: Optional[dict] = None,
44
+ ) -> TimeoutSession:
45
+ """构造一个带默认超时、幂等请求自动重试、连接池的会话。
46
+
47
+ Args:
48
+ timeout: 默认超时(秒),调用点可覆盖。
49
+ retries: 幂等请求的重试次数;0 表示不重试。
50
+ backoff_factor: 重试退避因子。
51
+ pool_size: 连接池大小。
52
+ headers: 需要附加到每个请求的默认 header(如 Authorization)。
53
+ """
54
+ session = TimeoutSession(timeout=timeout)
55
+
56
+ retry = Retry(
57
+ total=retries,
58
+ connect=retries,
59
+ read=False,
60
+ status=retries,
61
+ backoff_factor=backoff_factor,
62
+ status_forcelist=_RETRY_STATUS,
63
+ allowed_methods=_RETRY_METHODS,
64
+ raise_on_status=False,
65
+ respect_retry_after_header=True,
66
+ )
67
+ adapter = HTTPAdapter(
68
+ max_retries=retry, pool_connections=pool_size, pool_maxsize=pool_size
69
+ )
70
+ session.mount("http://", adapter)
71
+ session.mount("https://", adapter)
72
+
73
+ if headers:
74
+ session.headers.update(headers)
75
+ return session
76
+
77
+
78
+ __all__ = ["TimeoutSession", "new_session", "DEFAULT_TIMEOUT"]
funpub/py.typed ADDED
File without changes
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.5
2
+ Name: funpub
3
+ Version: 0.1.4
4
+ Summary: 多渠道制品发布工具
5
+ Project-URL: Organization, https://github.com/farfarfun
6
+ Project-URL: Repository, https://github.com/farfarfun/funpub
7
+ Project-URL: Releases, https://github.com/farfarfun/funpub/releases
8
+ Author-email: 牛哥 <niuliangtao@qq.com>, farfarfun <farfarfun@qq.com>
9
+ Maintainer-email: 牛哥 <niuliangtao@qq.com>, farfarfun <farfarfun@qq.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: farlog>=1.1.3
14
+ Requires-Dist: funsecret>=1.4.88
15
+ Requires-Dist: requests>=2.32.4
16
+ Requires-Dist: typer>=0.12.5
17
+ Description-Content-Type: text/markdown
18
+
19
+ # funpub
20
+
21
+ 多渠道制品发布工具。通过统一接口向不同的制品仓库上传/下载文件,当前支持:
22
+
23
+ - **aliyun** — 阿里云 Packages generic 仓库(协议细节见 `docs/aliyun/common/`)
24
+
25
+ 新渠道的接入方式见下方「新增渠道」。
26
+
27
+ ## 安装
28
+
29
+ ```bash
30
+ pip install funpub
31
+ ```
32
+
33
+ ## 命令行用法
34
+
35
+ 阿里云账号下可以有多个仓库,同一类型(如 generic)下也可以有多个不同名字
36
+ 的仓库,因此凭证按 `(repo-type, repo-name)` 两级区分,一个仓库只需要用
37
+ `funsecret` 配置一次,之后命令行只需要传 `--repo-name`:
38
+
39
+ ```bash
40
+ funsecret write https://packages.aliyun.com/api/protocol/{org_id}/generic/{repo} \
41
+ funpub aliyun generic {repo_name} repo_url
42
+ funsecret write {username} funpub aliyun generic {repo_name} username
43
+ funsecret write {password} funpub aliyun generic {repo_name} password
44
+ ```
45
+
46
+ ```bash
47
+ # 上传(repo-type 默认 generic,凭证从 funsecret 按 repo-name 自动读取)
48
+ funpub upload ./dist/app-1.0.0.tar.gz path/to/app \
49
+ --version 1.0.0 --repo-name {repo_name}
50
+
51
+ # 下载
52
+ funpub download path/to/app --version 1.0.0 \
53
+ --repo-name {repo_name} --output ./downloads/
54
+
55
+ # 生成临时免密下载地址
56
+ funpub sign-url path/to/app --version 1.0.0 \
57
+ --repo-name {repo_name} --expiration-seconds 3600
58
+
59
+ # 查看已注册的渠道
60
+ funpub channels
61
+ ```
62
+
63
+ 也可以不经 funsecret,直接用 `--repo-url`/`--username`/`--password` 传入:
64
+
65
+ ```bash
66
+ funpub upload ./dist/app-1.0.0.tar.gz path/to/app \
67
+ --version 1.0.0 \
68
+ --repo-url https://packages.aliyun.com/api/protocol/{org_id}/generic/{repo} \
69
+ --username {username} --password {password}
70
+ ```
71
+
72
+ ## Python 用法
73
+
74
+ ```python
75
+ from funpub import get_publisher
76
+
77
+ # 方式一:仓库信息已通过 funsecret 配置过,只需要传 repo_name
78
+ publisher = get_publisher("aliyun", repo_name="{repo_name}")
79
+
80
+ # 方式二:直接传 repo_url/username/password,不依赖 funsecret
81
+ publisher = get_publisher(
82
+ "aliyun",
83
+ repo_url="https://packages.aliyun.com/api/protocol/{org_id}/generic/{repo}",
84
+ username="...",
85
+ password="...",
86
+ )
87
+
88
+ # 文件大小超过 chunk_threshold(默认等于 chunk_size,100MB)会自动走分块上传
89
+ result = publisher.upload_file(
90
+ filepath="./dist/app-1.0.0.tar.gz",
91
+ path="path/to/app",
92
+ version="1.0.0",
93
+ )
94
+ print(result.url, result.md5)
95
+
96
+ publisher.download_file(path="path/to/app", version="1.0.0", save_dir="./downloads")
97
+ url = publisher.get_download_url(path="path/to/app", version="1.0.0")
98
+ ```
99
+
100
+ ## 设计
101
+
102
+ - `funpub.core.BasePublisher`:所有渠道实现的统一接口
103
+ (`upload_file` / `download_file` / `exist` / `get_download_url`)。
104
+ - `funpub.core.PublishResult`:上传结果,字典 + 属性双重访问
105
+ (`path` / `version` / `url` / `size` / `md5` / `sha1` / `sha256`)。
106
+ - `funpub.channels`:渠道注册表,懒加载各渠道模块 —— `import funpub` 不会
107
+ 拉入任何渠道的第三方依赖,只有真正使用某个渠道时才会导入它。
108
+
109
+ ### 新增渠道
110
+
111
+ 1. 在 `src/funpub/channels/<name>/` 下实现一个 `BasePublisher` 子类。
112
+ 2. 在 `src/funpub/channels/__init__.py` 的 `CHANNEL_SPECS` 里注册一行
113
+ `ChannelSpec`。
114
+
115
+ ## 开发
116
+
117
+ ```bash
118
+ uv sync
119
+ uv run pytest
120
+ uv run ruff check .
121
+ ```
@@ -0,0 +1,16 @@
1
+ funpub/__init__.py,sha256=eBnRSpmdTsVekbu2VHiTBTnQ0hvMd0TYaljqjejZ8RM,384
2
+ funpub/cli.py,sha256=Wt_nVGkZBxtiaD1WrcmOCBFPezr8evIwu6SjnwksJP4,5329
3
+ funpub/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ funpub/channels/__init__.py,sha256=36VtEa2rxqQioYS6aGrJlgCI7n_hagFGri3Sr1C_U20,4194
5
+ funpub/channels/aliyun/__init__.py,sha256=vErcvx7XdnEgUK8Ywahwik_qzvajmuH7SGsHSD7bbz0,70
6
+ funpub/channels/aliyun/client.py,sha256=QFPtG9JdLvd7wZhpyZrrffr9CRZLdBrxEteIu6IUdrg,12875
7
+ funpub/channels/aliyun/publisher.py,sha256=VrmnZgm7nS753VP_DOwbPCpUO-ToZz73J-fIWH1F-JY,6815
8
+ funpub/core/__init__.py,sha256=vFDsxXS9VJXDDkiPbbSzbUKdr866RUSJ14bhD-cr-lc,225
9
+ funpub/core/base.py,sha256=axNKWzFHGullCJ3Tu1WvoWbCnO0v7AJaJtE0_24W86U,4331
10
+ funpub/core/exceptions.py,sha256=E7DmApeN9fFeAO4gNrg1ZPHI1mkYnykAjsgjbRmv7TA,718
11
+ funpub/core/http.py,sha256=eonSdS68laoqYvle1PyWKzxmDG2mh2lmTee1MW1VLGc,2486
12
+ funpub-0.1.4.dist-info/METADATA,sha256=_COCGBTq5Bh96P8ZPSRTHyA3OJzNdX-ugsjXqxwpdlA,3916
13
+ funpub-0.1.4.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
14
+ funpub-0.1.4.dist-info/entry_points.txt,sha256=4my0VMPWXOZLPi-G5NWI-GbxhkzMAxDv3NFaM0aNKCk,42
15
+ funpub-0.1.4.dist-info/licenses/LICENSE,sha256=BvvS-yeQjeaYgHQW2Vh7Msedpzoc-r7mnjNCpqUUbgM,1066
16
+ funpub-0.1.4.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ funpub = funpub.cli:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 farfarfun
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.