mendao-cli 1.2.1__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.
mendao_cli/parser.py ADDED
@@ -0,0 +1,249 @@
1
+ """The one definition of the command line. `commands` reads this same parser, so help and behaviour cannot drift."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import re
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, NoReturn
9
+
10
+ from mendao_cli import account, admin, config, library, owner, update
11
+ from mendao_cli.errors import CliError, close_matches
12
+ from mendao_cli.http import DEFAULT_TIMEOUT
13
+ from mendao_cli.result import Result
14
+
15
+ #: Some operator commands run a model. The gateway gives up at about 125 seconds.
16
+ OPS_TIMEOUT = 120.0
17
+ #: `login` waits for the reader to approve in the browser (design 3.5); single requests inside it keep DEFAULT_TIMEOUT.
18
+ LOGIN_TIMEOUT = 300.0
19
+ #: `update` runs an installer, which downloads.
20
+ UPDATE_TIMEOUT = 180.0
21
+ _INVALID_CHOICE = re.compile(r"invalid choice: '([^']*)'")
22
+ _UNRECOGNIZED = re.compile(r"unrecognized arguments: (.*)")
23
+
24
+
25
+ class JsonParser(argparse.ArgumentParser):
26
+ """Parse errors join the error contract: JSON on stdout through CliError, never usage on stderr."""
27
+
28
+ def error(self, message: str) -> NoReturn:
29
+ raise CliError("validation", _chinese(message), suggestion="mendao commands 查看全部命令", did_you_mean=_candidates(self, message))
30
+
31
+
32
+ def _chinese(message: str) -> str:
33
+ choice = _INVALID_CHOICE.search(message)
34
+ if choice:
35
+ return "没有这个命令或取值:" + choice.group(1)
36
+ unknown = _UNRECOGNIZED.search(message)
37
+ if unknown:
38
+ return "没有这个参数:" + unknown.group(1)
39
+ return "参数不对:" + message
40
+
41
+
42
+ def _flags_of(parser: argparse.ArgumentParser) -> list[str]:
43
+ found = [flag for action in parser._actions for flag in action.option_strings]
44
+ for action in parser._actions:
45
+ if isinstance(action, argparse._SubParsersAction):
46
+ for child in action.choices.values():
47
+ found += _flags_of(child)
48
+ return sorted(set(found))
49
+
50
+
51
+ def _choices_of(parser: argparse.ArgumentParser) -> list[str]:
52
+ found: list[str] = []
53
+ for action in parser._actions:
54
+ if action.choices:
55
+ found += [str(choice) for choice in action.choices]
56
+ return found
57
+
58
+
59
+ def _candidates(parser: argparse.ArgumentParser, message: str) -> list[str]:
60
+ """Only from the parser's own definitions, so user input never comes back as advice."""
61
+ choice = _INVALID_CHOICE.search(message)
62
+ if choice:
63
+ return close_matches(choice.group(1), _choices_of(parser))
64
+ unknown = _UNRECOGNIZED.search(message)
65
+ if unknown:
66
+ flags = _flags_of(parser)
67
+ words = [word.split("=")[0] for word in unknown.group(1).split()]
68
+ return sorted({match for word in words for match in close_matches(word, flags)})[:3]
69
+ return []
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Spec:
74
+ name: str
75
+ description: str
76
+ group: str
77
+ handler: Callable[[argparse.Namespace], Result]
78
+ example: str
79
+ configure: Callable[[argparse.ArgumentParser], None] = field(default=lambda _parser: None)
80
+ timeout: float = DEFAULT_TIMEOUT
81
+ timeout_help: str = "网络超时秒数(含重试)"
82
+
83
+
84
+ def _shape_flags(parser: argparse.ArgumentParser, *, full: bool = True) -> None:
85
+ if full:
86
+ parser.add_argument("--full", action="store_true", help="展开完整字段")
87
+ parser.add_argument("--fields", help="只要这些字段,逗号分隔,如 id,title,url")
88
+
89
+
90
+ def _filters(parser: argparse.ArgumentParser) -> None:
91
+ parser.add_argument("--industry", help="领域编号,见 mendao questions")
92
+ parser.add_argument("--question", help="问题编号,见 mendao questions")
93
+ parser.add_argument("--platform", help="平台,如 x、youtube、article;可选值见输出的 platforms")
94
+ parser.add_argument("--tag", help="做法类型(旧),如 实测、步骤、踩坑;新的用 --practice")
95
+ parser.add_argument("--form", help="形式,逗号分开表示任一:short_post article short_video long_video repo official_doc podcast")
96
+ parser.add_argument("--level", help="难度:starter intermediate expert(也认 入门、进阶、专家)")
97
+ parser.add_argument("--practice", help="做法类型:tutorial prompt benchmark pitfall case tool_pick template framework other")
98
+ parser.add_argument("--evidence", help="证据:data demo code experience")
99
+ parser.add_argument("--source", help="来源性质:official practitioner media community")
100
+ parser.add_argument("--scale", help="规模:solo team enterprise")
101
+ parser.add_argument("--tool", help="工具编号,见 mendao tags;厂商含其下产品,如 anthropic 含 claude-code")
102
+ parser.add_argument("--topic", help="自由词,见 mendao tags 的 topics")
103
+ parser.add_argument("--since", help="发布日期起,YYYY-MM-DD")
104
+ parser.add_argument("--until", help="发布日期止(含当天),YYYY-MM-DD")
105
+ parser.add_argument("--sort", type=str.lower, choices=("top", "new", "added"), default="top", help="top 最值得看,new 最新发布,added 最新入库")
106
+ parser.add_argument("--limit", type=int, default=20, help=f"每页条数,1 到 {library.MAX_PAGE}")
107
+ parser.add_argument("--cursor", help="上一次输出里的 next_cursor,原样传回")
108
+ _shape_flags(parser)
109
+
110
+
111
+ def _configure_search(parser: argparse.ArgumentParser) -> None:
112
+ parser.add_argument("query", help="搜索词,中英文都行,空格分开表示都要出现")
113
+ _filters(parser)
114
+
115
+
116
+ def _configure_tags(parser: argparse.ArgumentParser) -> None:
117
+ parser.add_argument("--industry", help="只数这个领域的条数")
118
+ parser.add_argument("--all", action="store_true", help="连没有做法的工具也列出")
119
+
120
+
121
+ def _configure_post(parser: argparse.ArgumentParser) -> None:
122
+ parser.add_argument("post_id", help="帖子编号,来自 mendao posts 的 id")
123
+ parser.add_argument("--industry", help="领域编号;同一条在多个领域时用")
124
+ _shape_flags(parser)
125
+
126
+
127
+ def _configure_questions(parser: argparse.ArgumentParser) -> None:
128
+ parser.add_argument("--industry", help="只看这个领域")
129
+ parser.add_argument("--limit", type=int, default=0, help=f"最多几道问题,默认 {library.DEFAULT_QUESTIONS}")
130
+ parser.add_argument("--cursor", help="上一次输出里的 next_cursor,原样传回")
131
+ _shape_flags(parser, full=False)
132
+
133
+
134
+ def _configure_calendar(parser: argparse.ArgumentParser) -> None:
135
+ parser.add_argument("--industry", help="只看这个领域")
136
+ parser.add_argument("--question", help="只看这道问题")
137
+ parser.add_argument("--limit", type=int, default=0, help=f"最多几个月,默认 {library.DEFAULT_MONTHS}")
138
+ parser.add_argument("--cursor", help="上一次输出里的 next_cursor,原样传回")
139
+
140
+
141
+ def _configure_changes(parser: argparse.ArgumentParser) -> None:
142
+ parser.add_argument("--limit", type=int, default=50, help=f"一次最多几条,1 到 {library.MAX_CHANGES}")
143
+ parser.add_argument("--cursor", help="从这个位置重放,不改变记住的位置")
144
+ parser.add_argument("--peek", action="store_true", help="看下一批,但不移动记住的位置")
145
+ parser.add_argument("--reset", action="store_true", help="把记住的位置清零,下次从头同步")
146
+ parser.add_argument("--consumer", default="default", help="同步方的名字,不同名字各记各的位置")
147
+ _shape_flags(parser)
148
+
149
+
150
+ def _configure_login(parser: argparse.ArgumentParser) -> None:
151
+ parser.add_argument("--key-file", help="存着密钥的文件,- 表示从标准输入读。都没给时读环境变量 MENDAO_API_KEY;也没有就在浏览器里确认登录")
152
+ parser.add_argument("--wait", action="store_true", help="接着上一次返回 pending 的 mendao login:等读者在浏览器里确认,取回密钥")
153
+ parser.add_argument("--no-browser", action="store_true", help="在终端里登录时不自动打开浏览器,只显示地址和代码")
154
+ parser.add_argument("--no-verify", action="store_true", help="不向服务器确认就保存")
155
+
156
+
157
+ def _configure_update(parser: argparse.ArgumentParser) -> None:
158
+ parser.add_argument("--dry-run", action="store_true", help="只说会运行哪条命令,不运行")
159
+
160
+
161
+ def _configure_status(parser: argparse.ArgumentParser) -> None:
162
+ _shape_flags(parser, full=False)
163
+
164
+
165
+ def _configure_run(parser: argparse.ArgumentParser) -> None:
166
+ parser.add_argument("--dry-run", action="store_true", help="只说会做什么,不发请求")
167
+
168
+
169
+ def _configure_ops(parser: argparse.ArgumentParser) -> None:
170
+ parser.add_argument("--industry", help="命令针对的领域")
171
+ parser.add_argument("--dry-run", action="store_true", help="只说会发什么,不发请求")
172
+ parser.add_argument("line", nargs=argparse.REMAINDER, help="运维命令,如 question rename q1 --title 新标题;mendao ops help 列出全部")
173
+
174
+
175
+ def _configure_admin(parser: argparse.ArgumentParser) -> None:
176
+ parser.add_argument("words", nargs=argparse.REMAINDER, help="操作和参数,如 posts withdraw x:1 --reason 原因 --apply;mendao admin ops 列出全部")
177
+
178
+
179
+ PUBLIC: tuple[Spec, ...] = (
180
+ Spec("questions", "列出领域和问题,带条数", "library", library.questions, "mendao questions --industry ai-video", _configure_questions),
181
+ Spec("posts", "按领域、问题、平台、标签、日期取做法", "library", library.posts, "mendao posts --industry automation --form long_video --level starter --tool n8n", _filters),
182
+ Spec("search", "搜整个库", "library", library.search, 'mendao search "分镜 一致性" --industry ai-video', _configure_search),
183
+ Spec("tags", "列出可筛选的标签:形式、难度、做法类型、证据、工具词表、常用自由词", "library", library.tags, "mendao tags --industry automation", _configure_tags),
184
+ Spec("post", "取单条的详情:标题、编辑说明、原文链接", "library", library.post, "mendao post x:1234567890", _configure_post),
185
+ Spec("calendar", "按月、按天看每天有多少条", "library", library.calendar, "mendao calendar --industry ai-video", _configure_calendar),
186
+ Spec("changes", "增量同步:上次之后的新增和下架,本地记住位置", "library", library.changes, "mendao changes --consumer my-agent", _configure_changes),
187
+ Spec("login", "登录:在浏览器里确认,或保存已有的 Agent 密钥(mendao login --key-file ~/.config/mendao/key)", "account", account.login, "mendao login", _configure_login,
188
+ LOGIN_TIMEOUT, "最多等浏览器里的确认多少秒;单个请求仍按 30 秒超时"),
189
+ Spec("logout", "删除本机保存的密钥;浏览器登录得到的那把同时在服务器上作废,自己创建的只从本机删除", "account", account.logout, "mendao logout"),
190
+ Spec("whoami", "看现在用哪把密钥、存在哪、怎么来的、能读多少、今天用了多少次", "account", account.whoami, "mendao whoami"),
191
+ Spec("update", "把 mendao-cli 原地升到最新版:看出是用 uv tool、pipx 还是 pip 装的,就用同一种升级", "tool", update.update, "mendao update --dry-run", _configure_update, UPDATE_TIMEOUT,
192
+ "升级命令最多运行多少秒"),
193
+ )
194
+ OWNER: tuple[Spec, ...] = (
195
+ Spec("status", "看系统是否活着:运行、花费、告警、库大小", "owner", owner.status, "mendao status --fields library,runs", _configure_status),
196
+ Spec("run", "立即触发一次运行", "owner", owner.run, "mendao run", _configure_run),
197
+ Spec("ops", "运维命令:领域、问题、提示词、信源", "owner", owner.ops, "mendao ops question rename q1 --title 新标题", _configure_ops, OPS_TIMEOUT),
198
+ )
199
+
200
+
201
+ ADMIN = Spec("admin", "管理接口:撤下、恢复、导入、下架登记、审计与撤销;默认演练,加 --apply 才执行", "owner", admin.admin, "mendao admin posts withdraw x:1 --reason 原因", _configure_admin, OPS_TIMEOUT)
202
+
203
+
204
+ def specs() -> tuple[Spec, ...]:
205
+ if config.internal_secret():
206
+ return PUBLIC + OWNER + (ADMIN,)
207
+ return PUBLIC + (ADMIN,) if config.admin_key() else PUBLIC
208
+
209
+
210
+ def build() -> tuple[JsonParser, dict[str, Spec]]:
211
+ parser = JsonParser(prog="mendao", description="门道:按问题查做法的累积库。输出一份 JSON,出错也是。", epilog="先运行 mendao commands 看全部命令;mendao commands <命令> 看参数。")
212
+ parser.add_argument("-V", "--version", action="store_true", help="显示版本")
213
+ commands = parser.add_subparsers(dest="command", metavar="<命令>", parser_class=JsonParser)
214
+ catalogue = commands.add_parser("commands", help="列出命令和参数(JSON)")
215
+ catalogue.add_argument("path", nargs="*", help="只看这个命令的完整参数")
216
+ catalogue.add_argument("--full", action="store_true", help="全部命令的完整参数")
217
+ catalogue.add_argument("--search", help="按说明搜命令")
218
+ catalogue.add_argument("--group", help="按分组筛选:library account tool owner")
219
+ catalogue.add_argument("--explain", help="解释一条错误或提示的编号,如 mendao.free-limit")
220
+ table: dict[str, Spec] = {}
221
+ for spec in specs():
222
+ child = commands.add_parser(spec.name, help=spec.description, description=spec.description, epilog="示例:" + spec.example)
223
+ spec.configure(child)
224
+ child.add_argument("--timeout", type=float, default=spec.timeout, help=spec.timeout_help)
225
+ table[spec.name] = spec
226
+ return parser, table
227
+
228
+
229
+ def parameters(parser: argparse.ArgumentParser) -> list[dict[str, Any]]:
230
+ out: list[dict[str, Any]] = []
231
+ for action in parser._actions:
232
+ if isinstance(action, argparse._SubParsersAction):
233
+ continue
234
+ is_flag = isinstance(action, (argparse._StoreTrueAction, argparse._HelpAction))
235
+ kind = "option" if action.option_strings else "argument"
236
+ type_name = "boolean" if is_flag else "integer" if action.type is int else "number" if action.type is float else "string"
237
+ out.append({
238
+ "name": action.dest, "flags": list(action.option_strings), "kind": kind, "type": type_name,
239
+ "required": bool(action.required) or (kind == "argument" and action.nargs is None),
240
+ "default": None if action.default in (None, False, argparse.SUPPRESS) else action.default,
241
+ "choices": list(action.choices) if action.choices else None,
242
+ "nargs": 0 if is_flag else action.nargs, "description": action.help or "",
243
+ })
244
+ return out
245
+
246
+
247
+ def options_of(parser: argparse.ArgumentParser) -> tuple[list[str], list[str]]:
248
+ params = parameters(parser)
249
+ return [p["name"] for p in params if p["kind"] == "argument"], [flag for p in params for flag in p["flags"]]
mendao_cli/py.typed ADDED
File without changes
mendao_cli/result.py ADDED
@@ -0,0 +1,21 @@
1
+ """What a command hands back: the data, its envelope fields, and what to do once it has been delivered."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Callable
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+
9
+ @dataclass
10
+ class Result:
11
+ data: Any
12
+ meta: dict[str, Any] = field(default_factory=dict)
13
+ notices: list[dict[str, str]] = field(default_factory=list)
14
+ #: Runs only after the answer reached stdout, so a lost answer moves nothing.
15
+ delivered: Callable[[], None] | None = None
16
+
17
+ def envelope(self) -> dict[str, Any]:
18
+ out: dict[str, Any] = {"code": 200, "data": self.data, **self.meta}
19
+ if self.notices:
20
+ out["notices"] = self.notices
21
+ return out
mendao_cli/shape.py ADDED
@@ -0,0 +1,167 @@
1
+ """What Agents get to read: concise by default, a byte budget, cursors that survive trimming."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from collections.abc import Mapping
6
+ import base64
7
+ import hashlib
8
+ import json
9
+ from collections.abc import Callable, Iterable, Sequence
10
+ from dataclasses import dataclass
11
+ from typing import Any
12
+
13
+ from mendao_cli.errors import CliError
14
+
15
+ #: About the largest single answer an Agent can take in.
16
+ TOKEN_BUDGET = 25_000
17
+ #: Room kept for the envelope and the facets around the items.
18
+ ENVELOPE_RESERVE = 1_000
19
+ EXCERPT_CHARS = 280
20
+ FULL_LIST_FIELD_CHARS = 3_000
21
+ DETAIL_FIELD_CHARS = 5_000
22
+ _LONG_FIELDS = ("text", "note", "description", "descriptionZh")
23
+
24
+
25
+ def headline(post: Mapping[str, Any]) -> str:
26
+ """X posts have no title: their first sentence stands in, so an Agent always sees what a post is."""
27
+ title = post.get("titleZh") or post.get("title")
28
+ if title:
29
+ return str(title)
30
+ text = re.sub(r"https?://\S+", "", str(post.get("note") or post.get("text") or "")).strip()
31
+ parts = [part.strip() for part in re.split(r"[\n。!?!?]", text)]
32
+ return next((part for part in parts if len(part) > 4), text)[:80]
33
+
34
+
35
+ def estimate_tokens(value: Any) -> int:
36
+ """Deliberately high: a Chinese character costs more than one Latin letter, and the real limit is hard."""
37
+ text = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
38
+ wide = sum(1 for ch in text if ord(ch) > 0x7F)
39
+ return (len(text) - wide) // 4 + wide * 3 // 2 + 1
40
+
41
+
42
+ def fit_budget(items: Sequence[Any], budget: int = TOKEN_BUDGET - ENVELOPE_RESERVE) -> int:
43
+ """How many leading items fit. At least one, so a single large item never blocks progress."""
44
+ used = 0
45
+ for count, item in enumerate(items):
46
+ used += estimate_tokens(item)
47
+ if used > budget:
48
+ return max(count, 1)
49
+ return len(items)
50
+
51
+
52
+ def clip(text: str, limit: int) -> tuple[str, bool]:
53
+ return (text, False) if len(text) <= limit else (text[:limit] + "…", True)
54
+
55
+
56
+ def _excerpt(post: dict[str, Any]) -> str:
57
+ return str(post.get("note") or post.get("descriptionZh") or post.get("text") or "")
58
+
59
+
60
+ def concise_post(post: dict[str, Any], *, excerpt: bool = False) -> dict[str, Any]:
61
+ """The high-signal view: enough to decide whether to open it. `excerpt` stands in for a missing note; beside a note it would
62
+ only repeat it (D12), so it is left out unless asked for by name (`--fields excerpt`)."""
63
+ author = post.get("author")
64
+ shaped: dict[str, Any] = {
65
+ "id": post.get("id"),
66
+ "industryId": post.get("industryId"),
67
+ "questionId": post.get("questionId"),
68
+ "platform": post.get("platform"),
69
+ "title": headline(post),
70
+ "excerpt": clip(_excerpt(post), EXCERPT_CHARS)[0],
71
+ "note": post.get("note"),
72
+ "author": author.get("name") or author.get("handle") if isinstance(author, dict) else None,
73
+ "url": post.get("url"),
74
+ "page": post.get("page"),
75
+ "publishedAt": post.get("publishedAt"),
76
+ "admittedAt": post.get("admittedAt"),
77
+ "rank": post.get("rank"),
78
+ }
79
+ if not excerpt and shaped["note"]:
80
+ del shaped["excerpt"]
81
+ # The source's own counts (likes, reposts, replies, bookmarks, views), so a caller can weigh heat without a second call.
82
+ metrics = {k: v for k, v in (post.get("metrics") or {}).items() if isinstance(v, int) and v > 0}
83
+ if metrics:
84
+ shaped["metrics"] = metrics
85
+ if post.get("tags"):
86
+ shaped["tags"] = post["tags"]
87
+ facets = {k: v for k, v in (post.get("facets") or {}).items() if v} if isinstance(post.get("facets"), dict) else {}
88
+ if facets:
89
+ shaped["facets"] = facets
90
+ if post.get("videoId"):
91
+ shaped["videoId"] = post["videoId"]
92
+ return shaped
93
+
94
+
95
+ def clip_fields(post: dict[str, Any], limit: int) -> dict[str, Any]:
96
+ out = dict(post)
97
+ clipped = False
98
+ for name in _LONG_FIELDS:
99
+ value = out.get(name)
100
+ if isinstance(value, str):
101
+ out[name], was = clip(value, limit)
102
+ clipped = clipped or was
103
+ if clipped:
104
+ out["_truncated"] = True
105
+ return out
106
+
107
+
108
+ def parse_fields(raw: str | None) -> list[str] | None:
109
+ if raw is None:
110
+ return None
111
+ names = [name.strip() for name in raw.split(",") if name.strip()]
112
+ if not names:
113
+ raise CliError("validation", "--fields 是空的", suggestion="--fields id,title,url")
114
+ return names
115
+
116
+
117
+ def mask(item: dict[str, Any], fields: Iterable[str]) -> dict[str, Any]:
118
+ return {name: item[name] for name in fields if name in item}
119
+
120
+
121
+ def view_post(post: dict[str, Any], *, full: bool, fields: list[str] | None) -> dict[str, Any]:
122
+ if fields:
123
+ return mask({**concise_post(post, excerpt=True), **clip_fields(post, FULL_LIST_FIELD_CHARS)}, fields)
124
+ return clip_fields(post, FULL_LIST_FIELD_CHARS) if full else concise_post(post)
125
+
126
+
127
+ def missing_fields(items: Iterable[dict[str, Any]], fields: list[str] | None) -> list[str]:
128
+ """Names no returned item had: most likely a typo, and worth saying so."""
129
+ if not fields:
130
+ return []
131
+ seen: set[str] = set()
132
+ empty = True
133
+ for item in items:
134
+ empty = False
135
+ seen.update(item)
136
+ return [] if empty else [name for name in fields if name not in seen]
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class Cursor:
141
+ """Opaque to callers. `skip` holds the place when the budget cut a page short."""
142
+
143
+ page: int
144
+ skip: int
145
+ size: int
146
+ query: str
147
+
148
+ def encode(self) -> str:
149
+ raw = json.dumps({"p": self.page, "s": self.skip, "z": self.size, "q": self.query}, separators=(",", ":"))
150
+ return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
151
+
152
+
153
+ def query_digest(query: dict[str, Any]) -> str:
154
+ return hashlib.sha256(json.dumps(query, sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:12]
155
+
156
+
157
+ def decode_cursor(token: str, query: str, example: Callable[[], str]) -> Cursor:
158
+ try:
159
+ value = json.loads(base64.urlsafe_b64decode(token + "=" * (-len(token) % 4)))
160
+ cursor = Cursor(int(value["p"]), int(value["s"]), int(value["z"]), str(value["q"]))
161
+ except (ValueError, KeyError, TypeError):
162
+ raise CliError("validation", "--cursor 不是这个命令给出的游标", suggestion=example()) from None
163
+ if cursor.page < 1 or cursor.skip < 0 or cursor.size < 1:
164
+ raise CliError("validation", "--cursor 不是这个命令给出的游标", suggestion=example())
165
+ if cursor.query != query:
166
+ raise CliError("validation", "--cursor 属于另一组筛选条件", suggestion="筛选条件要和拿到游标时一样;或去掉 --cursor 从头取")
167
+ return cursor
mendao_cli/update.py ADDED
@@ -0,0 +1,225 @@
1
+ """Newer versions: a notice when one exists, and `mendao update` to install it the way this copy was installed.
2
+
3
+ The site says which version is current (`/cli/latest.txt`: version, wheel, sha256; written by scripts/site_release.py). The notice
4
+ asks at most once a day, `MENDAO_NO_UPDATE_CHECK=1` turns it off, and nothing in it can fail a command."""
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import json
9
+ import re
10
+ import shlex
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ import time
15
+ from collections.abc import Callable
16
+ from dataclasses import dataclass
17
+ from importlib import metadata
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ import httpx
22
+
23
+ from mendao_cli import __version__, config
24
+ from mendao_cli.errors import CliError
25
+ from mendao_cli.http import USER_AGENT
26
+ from mendao_cli.result import Result
27
+
28
+ #: JSON in a .txt: the site serves .txt as a static file.
29
+ LATEST_PATH = "/cli/latest.txt"
30
+ CHECK_EVERY_SECONDS = 86_400
31
+ TIMEOUT_SECONDS = 1.5
32
+ PACKAGE = "mendao-cli"
33
+ _STDERR_LINES = 20
34
+ _REQUIREMENT = re.compile(r'\{[^{}]*name\s*=\s*"mendao-cli"[^{}]*\}')
35
+
36
+ #: Indirections the tests replace.
37
+ _run = subprocess.run
38
+ _which = shutil.which
39
+
40
+
41
+ def _prefix() -> Path:
42
+ return Path(sys.prefix)
43
+
44
+
45
+ def _dist_file(name: str) -> str | None:
46
+ try:
47
+ return metadata.distribution(PACKAGE).read_text(name)
48
+ except metadata.PackageNotFoundError:
49
+ return None
50
+
51
+
52
+ def _on_windows() -> bool:
53
+ return sys.platform == "win32"
54
+
55
+
56
+ def _newer(latest: str, current: str) -> bool:
57
+ def parts(version: str) -> tuple[int, ...]:
58
+ return tuple(int(p) for p in version.split("."))
59
+
60
+ try:
61
+ return parts(latest) > parts(current)
62
+ except ValueError:
63
+ return False
64
+
65
+
66
+ def _get_latest(url: str, timeout: float) -> dict[str, Any] | None:
67
+ """No key goes with this: it is a public file."""
68
+ response = httpx.get(url + LATEST_PATH, timeout=timeout, headers={"user-agent": USER_AGENT}, follow_redirects=False, trust_env=not config.is_loopback(url))
69
+ value = response.json() if response.status_code == 200 else None
70
+ return value if isinstance(value, dict) else None
71
+
72
+
73
+ def _fetch(url: str) -> dict[str, Any] | None:
74
+ try:
75
+ return _get_latest(url, TIMEOUT_SECONDS)
76
+ except (httpx.HTTPError, ValueError):
77
+ return None
78
+
79
+
80
+ def notice(fetch: Callable[[str], dict[str, Any] | None] = _fetch, now: Callable[[], float] = time.time) -> dict[str, str] | None:
81
+ """Only the real site over https: a local or test address has no release to announce."""
82
+ try:
83
+ if config.update_check_disabled():
84
+ return None
85
+ url = config.base_url()
86
+ if not url.startswith("https://"):
87
+ return None
88
+ path = config.config_dir() / "update-check.json"
89
+ try:
90
+ seen = json.loads(path.read_text("utf-8"))
91
+ except (OSError, ValueError):
92
+ seen = {}
93
+ if not isinstance(seen, dict) or "checkedAt" not in seen or now() - float(seen["checkedAt"]) >= CHECK_EVERY_SECONDS:
94
+ seen = {"checkedAt": now(), "latest": fetch(url) or {}}
95
+ path.parent.mkdir(parents=True, exist_ok=True)
96
+ path.write_text(json.dumps(seen), "utf-8")
97
+ latest = seen.get("latest") or {}
98
+ version, wheel = str(latest.get("version", "")), str(latest.get("wheel", ""))
99
+ if wheel.startswith("/") and _newer(version, __version__):
100
+ return {"id": "mendao.update", "text": f"mendao-cli 有新版 {version},你现在是 {__version__}。", "fix": "mendao update"}
101
+ except Exception: # A courtesy never costs the reader their answer, whatever broke in it.
102
+ return None
103
+ return None
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class Install:
108
+ """How this copy was installed. `kind`: uv-tool, pipx, pip, uv-pip, uvx, source, unknown. `origin`: url (a wheel, such as the
109
+ site's), pypi, or None when it cannot be told."""
110
+
111
+ kind: str
112
+ origin: str | None = None
113
+
114
+
115
+ def detect() -> Install:
116
+ """From what the installers leave behind: uv's receipt, pipx's metadata, the INSTALLER and direct_url.json of the package."""
117
+ prefix = _prefix()
118
+ receipt = prefix / "uv-receipt.toml"
119
+ if receipt.is_file():
120
+ found = _REQUIREMENT.search(receipt.read_text("utf-8", errors="replace"))
121
+ if found is None:
122
+ return Install("uv-tool")
123
+ entry = found.group(0)
124
+ if re.search(r"\b(editable|directory|git)\s*=", entry):
125
+ return Install("source")
126
+ return Install("uv-tool", "url" if re.search(r"\b(url|path)\s*=", entry) else "pypi")
127
+ pipx = prefix / "pipx_metadata.json"
128
+ if pipx.is_file():
129
+ try:
130
+ spec = str(json.loads(pipx.read_text("utf-8"))["main_package"]["package_or_url"])
131
+ except (OSError, ValueError, KeyError, TypeError):
132
+ return Install("pipx")
133
+ return Install("pipx", "url" if "://" in spec or spec.endswith(".whl") else "pypi")
134
+ if "archive-v0" in prefix.parts:
135
+ return Install("uvx")
136
+ direct = _dist_file("direct_url.json")
137
+ origin = "pypi"
138
+ if direct:
139
+ try:
140
+ record = json.loads(direct)
141
+ except ValueError:
142
+ record = {}
143
+ if isinstance(record, dict) and (record.get("dir_info") or {}).get("editable"):
144
+ return Install("source")
145
+ origin = "url" if isinstance(record, dict) and record.get("url") else "pypi"
146
+ installer = (_dist_file("INSTALLER") or "").strip()
147
+ return Install({"pip": "pip", "uv": "uv-pip"}.get(installer, "unknown"), origin if installer in ("pip", "uv") else None)
148
+
149
+
150
+ def command_for(install: Install, wheel_url: str | None) -> list[str] | None:
151
+ """The upgrade through the same installer and the same source. None when that cannot be done from here."""
152
+ pypi = install.origin == "pypi"
153
+ target = PACKAGE if pypi else wheel_url
154
+ if target is None:
155
+ return None
156
+ if install.kind == "uv-tool" and install.origin:
157
+ return ["uv", "tool", "upgrade", PACKAGE] if pypi else ["uv", "tool", "install", "--force", target]
158
+ if install.kind == "pipx" and install.origin:
159
+ return ["pipx", "upgrade", PACKAGE] if pypi else ["pipx", "install", "--force", target]
160
+ if install.kind == "pip":
161
+ return [sys.executable, "-m", "pip", "install", "--upgrade", target]
162
+ if install.kind == "uv-pip":
163
+ return ["uv", "pip", "install", "--python", sys.executable, "--upgrade", target]
164
+ return None
165
+
166
+
167
+ _WHY_NOT = {
168
+ "uvx": "这一份是 uvx 临时运行的,没有装在哪里:下次运行时加 --refresh 就会用最新版",
169
+ "source": "这一份是从源码目录装的(editable):在源码目录里更新",
170
+ "unknown": "看不出这一份是怎么装的,没有运行任何命令;照 command 自己运行",
171
+ "windows": "Windows 上不能替换正在运行的 mendao,没有运行任何命令;退出后照 command 运行",
172
+ }
173
+
174
+
175
+ def _installed_version(timeout: float) -> str | None:
176
+ """Asked of the interpreter this copy runs on, after the installer finished: what is there now, not what was hoped for."""
177
+ try:
178
+ done = _run([sys.executable, "-c", f"from importlib.metadata import version; print(version({PACKAGE!r}))"], capture_output=True, text=True, timeout=timeout)
179
+ except (OSError, subprocess.SubprocessError):
180
+ return None
181
+ if done.returncode != 0:
182
+ return None
183
+ return done.stdout.strip() or None
184
+
185
+
186
+ def update(args: argparse.Namespace) -> Result:
187
+ url = config.base_url()
188
+ install = detect()
189
+ try:
190
+ latest = _get_latest(url, min(args.timeout, 30.0))
191
+ except (httpx.HTTPError, ValueError):
192
+ latest = None
193
+ version = str((latest or {}).get("version") or "") or None
194
+ wheel = str((latest or {}).get("wheel") or "")
195
+ wheel_url = url + wheel if wheel.startswith("/cli/") and wheel.endswith(".whl") else None
196
+ data: dict[str, Any] = {"current": __version__, "latest": version, "installer": install.kind, "source": install.origin}
197
+ if latest and wheel_url and latest.get("sha256"):
198
+ data["sha256"] = latest["sha256"]
199
+ if version and not _newer(version, __version__):
200
+ return Result({**data, "updated": False, "ran": False, "command": None, "reason": "已是最新版"})
201
+ if wheel_url is None and install.origin != "pypi":
202
+ raise CliError("network", f"取不到最新版本的信息({url}{LATEST_PATH})", error_code="mendao.offline")
203
+ command = command_for(install, wheel_url)
204
+ if command is None:
205
+ fallback = None if install.kind in ("uvx", "source") else ["uv", "tool", "install", "--force", wheel_url or PACKAGE]
206
+ return Result({**data, "updated": False, "ran": False, "command": shlex.join(fallback) if fallback else None, "reason": _WHY_NOT.get(install.kind, _WHY_NOT["unknown"])})
207
+ data["command"] = shlex.join(command)
208
+ if args.dry_run:
209
+ return Result({**data, "updated": False, "ran": False}, {"_dry_run": True})
210
+ if _on_windows():
211
+ return Result({**data, "updated": False, "ran": False, "reason": _WHY_NOT["windows"]})
212
+ program = command[0] if command[0] == sys.executable else _which(command[0])
213
+ if program is None:
214
+ return Result({**data, "updated": False, "ran": False, "reason": f"找不到 {command[0]},没有运行任何命令;装好 {command[0]} 后照 command 运行"})
215
+ try:
216
+ done = _run([program, *command[1:]], capture_output=True, text=True, timeout=args.timeout)
217
+ except subprocess.TimeoutExpired:
218
+ raise CliError("timeout", f"升级命令 {args.timeout:g} 秒内没有结束", suggestion=data["command"]) from None
219
+ except OSError as error:
220
+ raise CliError("dependency", f"升级命令没能运行({type(error).__name__})", suggestion=data["command"]) from None
221
+ if done.returncode != 0:
222
+ tail = "\n".join((done.stderr or "").strip().splitlines()[-_STDERR_LINES:])
223
+ raise CliError("dependency", f"升级命令失败(退出码 {done.returncode})", suggestion=data["command"], details={"command": data["command"], "exitCode": done.returncode, "stderr": tail})
224
+ installed = _installed_version(30.0)
225
+ return Result({**data, "ran": True, "installed": installed, "updated": bool(installed) and installed != __version__})