gitflow_gitcode/lib.rs
1//! `gitflow-gitcode` —— GitCode 平台实现。
2//!
3//! 本 crate 实现了 `gitflow-core` 中定义的 [`IssueProvider`]、[`PrProvider`]、
4//! [`ReleaseProvider`]、[`ReviewProvider`]、[`AuthProvider`]、[`LabelProvider`]、
5//! [`MilestoneProvider`]、[`CommitProvider`] 与 [`PipelineProvider`] trait,
6//! 通过调用 `gc` CLI 获取数据并解析其 JSON 输出。
7//!
8//! # 主要类型
9//!
10//! - [`GitCodeIssueProvider`]:操作 GitCode Issue。
11//! - [`GitCodePrProvider`]:操作 GitCode Pull Request。
12//! - [`GitCodeReleaseProvider`]:操作 GitCode Release。
13//! - [`GitCodeReviewProvider`]:操作 GitCode PR Review。
14//! - [`GitCodeAuthProvider`]:处理 GitCode 认证(登录、登出、状态、Token)。
15//! - [`GitCodeLabelProvider`]:管理 GitCode 仓库标签。
16//! - [`GitCodeMilestoneProvider`]:管理 GitCode 仓库里程碑。
17//! - [`GitCodeCommitProvider`]:查看 GitCode Commit 及 Diff/Patch。
18//! - [`GitCodePipelineProvider`]:查看 GitCode CI/CD 流水线。
19//!
20//! # 错误处理
21//!
22//! 所有平台调用失败时,`gc` 的 stderr 会通过 [`error::parse_gitcode_error`] 解析,
23//! 并统一映射为 [`CoreError::Platform`]。
24//!
25//! [`IssueProvider`]: gitflow_core::issue::IssueProvider
26//! [`PrProvider`]: gitflow_core::pr::PrProvider
27//! [`ReleaseProvider`]: gitflow_core::release::ReleaseProvider
28//! [`ReviewProvider`]: gitflow_core::review::ReviewProvider
29//! [`AuthProvider`]: gitflow_core::auth::AuthProvider
30//! [`LabelProvider`]: gitflow_core::label::LabelProvider
31//! [`MilestoneProvider`]: gitflow_core::label::MilestoneProvider
32//! [`CommitProvider`]: gitflow_core::commit::CommitProvider
33//! [`PipelineProvider`]: gitflow_core::pipeline::PipelineProvider
34//! [`CoreError::Platform`]: gitflow_core::CoreError::Platform
35
36#![forbid(unsafe_code)]
37#![allow(
38 clippy::doc_markdown,
39 reason = "GitCode is a platform brand name, not a Rust code item"
40)]
41#![cfg_attr(
42 test,
43 allow(
44 clippy::expect_used,
45 clippy::unwrap_used,
46 clippy::indexing_slicing,
47 clippy::useless_format,
48 clippy::clone_on_copy,
49 reason = "Tests legitimately need to unwrap fixture data and index into known-shape \
50 collections"
51 )
52)]
53
54use std::sync::OnceLock;
55
56use tracing::debug;
57
58/// gitcode 分页端点的单页最大条目数。
59///
60/// **实测样本**(gitcode-cli 0.12.0,`openharmony/docs` 的 **issues** 端点):
61/// `per_page` 超限不报错,而是被服务端**静默封顶**在 100 —— `per_page=101` 与
62/// `per_page=1001` 均实回 100 条;`--page` 是真实翻页,`--per-page 3 --page 1/2`
63/// 返回的编号不重叠。
64///
65/// 该上限是平台 API 层面的约定而非单个端点的特性,因此 `issue` / `pr` / `label` /
66/// `milestone` / `release` 的分页路径共用它钳住页大小:
67/// `cap.saturating_add(1).min(GITCODE_API_MAX_PER_PAGE)`。
68///
69/// 若某端点不遵守约定的分页语义,后果取决于具体是哪种偏离:
70/// - `per_page` 与 `page` **都被忽略**:首页短于请求的 `per_page` ⇒ 翻页循环因短页
71/// 提前终止——不会死循环也不会丢数据。
72/// - `per_page` 被遵守但 `page` **被忽略**:每次都原样返回第一页的满页,循环判定 「拿到的条目数 <
73/// 目标数」为真而不断继续,直到凑够 `cap + 1` 条为止——不会死循环;
74/// 已取到的条目不会被丢弃,但第一页之后的真实条目永远取不到,返回的是同一批条目的
75/// 多次重复,且会被报告为 `truncated: true`,结果具有误导性。
76/// - `page` 被遵守,但 `per_page` 被**静默调低**(例如请求 100、端点实际按 50 返回):
77/// 首页会短于请求的 `per_page`,`fetch_capped`(`crates/core/src/paging.rs`)把 「本页条目数 <
78/// per_page」直接当作「已取尽」而提前终止循环,于是只取到 实际存在数据的一小部分却报告
79/// `truncated: false`——这是**静默丢数据**,且与第一种
80/// 情形(两者都被忽略)产生完全相同的「首页短于 per_page」现象,无法仅凭这一观测区分。
81/// 换言之,短页本身**不能**证明数据已取尽。
82///
83/// **`/releases` 端点本身未被单独采样过非空响应**:上述几种偏离分页约定的情形均未被
84/// 实测排除,因此不能断言该端点属于第一种(安全)、第二种(重复但不丢数据)还是
85/// 第三种(静默丢数据)。
86pub(crate) const GITCODE_API_MAX_PER_PAGE: u32 = 100;
87
88pub mod auth;
89pub mod commit;
90pub mod error;
91pub mod issue;
92pub mod label;
93pub mod pipeline;
94pub mod pr;
95pub mod release;
96pub mod review;
97pub mod runner;
98
99pub use auth::GitCodeAuthProvider;
100pub use commit::GitCodeCommitProvider;
101pub use error::parse_gitcode_error;
102pub use issue::GitCodeIssueProvider;
103pub use label::{GitCodeLabelProvider, GitCodeMilestoneProvider};
104pub use pipeline::GitCodePipelineProvider;
105pub use pr::GitCodePrProvider;
106pub use release::GitCodeReleaseProvider;
107pub use review::GitCodeReviewProvider;
108
109/// Binary name used when no usable GitCode CLI is discovered.
110///
111/// Deliberately the unambiguous `gitcode` rather than `gc`: on macOS,
112/// Graphviz installs an unrelated `/opt/homebrew/bin/gc`, so falling back to
113/// `gc` would hand every call to a graph-counting utility instead of failing
114/// cleanly with "command not found".
115pub(crate) const FALLBACK_BINARY: &str = "gitcode";
116
117/// Cached result of binary discovery, so the `--help` probe runs at most once
118/// per process instead of forking a subprocess on every CLI call.
119static GITCODE_BINARY: OnceLock<String> = OnceLock::new();
120
121/// Return the GitCode CLI binary path.
122///
123/// Prefers `gitcode` (unambiguous) over `gc` (short native name, but collides
124/// with Graphviz's `gc` on macOS). Every discovered candidate must identify
125/// itself as the GitCode CLI via [`identifies_as_gitcode_cli`] before it is
126/// accepted; a candidate that fails the probe is rejected and discovery moves
127/// on to the **next candidate name**. It does not keep searching other
128/// locations for the same name — [`locate_candidate`] yields only the first
129/// hit per name, so a failing `gitcode` earlier on PATH shadows a working one
130/// in `~/.local/bin`. Rejections are logged at `debug` level with the
131/// candidate path so this case is diagnosable.
132///
133/// Searches PATH first, then pip user install directories
134/// (`~/Library/Python/*/bin/` on macOS, `~/.local/bin/` on Linux).
135///
136/// The result is memoized in a [`OnceLock`]: the probe runs once per process,
137/// and subsequent calls only clone the cached string. This matters because
138/// callers are overwhelmingly `async fn` bodies, where a per-call
139/// `std::process::Command` would block a Tokio worker thread.
140pub(crate) fn gitcode_binary() -> String {
141 GITCODE_BINARY
142 .get_or_init(|| resolve_gitcode_binary(locate_candidate, identifies_as_gitcode_cli))
143 .clone()
144}
145
146/// Pick the first candidate that both resolves to a path and passes `probe`.
147///
148/// Split out from [`gitcode_binary`] so the ordering and rejection logic can
149/// be unit-tested without touching PATH or spawning processes.
150fn resolve_gitcode_binary<L, P>(lookup: L, probe: P) -> String
151where
152 L: Fn(&str) -> Option<std::path::PathBuf>,
153 P: Fn(&std::path::Path) -> bool,
154{
155 const CANDIDATES: &[&str] = &["gitcode", "gc"];
156
157 for &candidate in CANDIDATES {
158 if let Some(path) = lookup(candidate)
159 && probe(&path)
160 {
161 return path.to_string_lossy().into_owned();
162 }
163 }
164 FALLBACK_BINARY.into()
165}
166
167/// Locate `candidate` on PATH, then in pip user install directories.
168#[allow(
169 clippy::disallowed_methods,
170 reason = "one-time synchronous PATH lookup, memoized behind `GITCODE_BINARY`"
171)]
172fn locate_candidate(candidate: &str) -> Option<std::path::PathBuf> {
173 if let Ok(path) = which::which(candidate) {
174 return Some(path);
175 }
176
177 let home = std::env::var("HOME").ok()?;
178
179 // pip user install paths (e.g. ~/Library/Python/3.9/bin/)
180 let lib = std::path::PathBuf::from(&home).join("Library/Python");
181 if let Ok(entries) = std::fs::read_dir(&lib) {
182 for entry in entries.flatten() {
183 let path = entry.path().join("bin").join(candidate);
184 if path.exists() {
185 return Some(path);
186 }
187 }
188 }
189
190 let path = std::path::PathBuf::from(&home)
191 .join(".local/bin")
192 .join(candidate);
193 path.exists().then_some(path)
194}
195
196/// Report whether `path` identifies itself as the GitCode CLI.
197///
198/// Probes with `--help` rather than `--version`: the real CLI rejects
199/// `--version` with `unknown flag` (exit 2), so a version probe would discard
200/// the very binary it is meant to find.
201/// A candidate that runs but does not identify as the GitCode CLI is rejected
202/// silently from the user's perspective, so the rejection is recorded via
203/// `tracing` with the candidate path — otherwise a version change in GitCode's
204/// help text would surface only as `command not found: gitcode`.
205#[allow(
206 clippy::disallowed_types,
207 reason = "one-time synchronous probe, memoized behind `GITCODE_BINARY`, called from sync \
208 context"
209)]
210fn identifies_as_gitcode_cli(path: &std::path::Path) -> bool {
211 let Ok(output) = std::process::Command::new(path).arg("--help").output() else {
212 debug!(
213 candidate = %path.display(),
214 "candidate could not be executed for the --help probe"
215 );
216 return false;
217 };
218
219 let stdout = String::from_utf8_lossy(&output.stdout);
220 let stderr = String::from_utf8_lossy(&output.stderr);
221 let accepted = is_gitcode_help_output(output.status.success(), &stdout, &stderr);
222
223 if !accepted {
224 debug!(
225 candidate = %path.display(),
226 exit_success = output.status.success(),
227 "candidate rejected: `--help` did not identify it as the GitCode CLI"
228 );
229 }
230
231 accepted
232}
233
234/// Decide whether a `--help` probe result came from the GitCode CLI.
235///
236/// Requires both a successful exit and a `gitcode` marker in the output.
237/// Graphviz's `gc` fails on both counts: it exits 1 and prints
238/// `gc: option -- unrecognized`.
239fn is_gitcode_help_output(success: bool, stdout: &str, stderr: &str) -> bool {
240 success
241 && format!("{stdout}{stderr}")
242 .to_lowercase()
243 .contains("gitcode")
244}
245
246#[cfg(test)]
247mod tests {
248 use std::path::{Path, PathBuf};
249
250 use super::*;
251
252 #[test]
253 fn test_should_return_non_empty_binary_name() {
254 let binary = gitcode_binary();
255 assert!(!binary.is_empty());
256 }
257
258 #[test]
259 fn test_should_cache_binary_discovery_across_calls() {
260 assert_eq!(
261 gitcode_binary(),
262 gitcode_binary(),
263 "discovery is memoized, so repeated calls must not re-probe"
264 );
265 assert!(
266 GITCODE_BINARY.get().is_some(),
267 "the first call must populate the cache so no later call forks a subprocess"
268 );
269 }
270
271 #[test]
272 fn test_should_prefer_gitcode_over_gc_when_both_resolve() {
273 let lookup = |candidate: &str| Some(PathBuf::from(format!("/usr/bin/{candidate}")));
274 let probe = |_: &Path| true;
275
276 assert_eq!(
277 resolve_gitcode_binary(lookup, probe),
278 "/usr/bin/gitcode",
279 "the unambiguous name must win so an unrelated `gc` cannot shadow the CLI"
280 );
281 }
282
283 #[test]
284 fn test_should_reject_candidate_that_fails_probe() {
285 // Graphviz ships /opt/homebrew/bin/gc, which is not the GitCode CLI.
286 let lookup =
287 |candidate: &str| (candidate == "gc").then(|| PathBuf::from("/opt/homebrew/bin/gc"));
288 let probe = |_: &Path| false;
289
290 assert_eq!(
291 resolve_gitcode_binary(lookup, probe),
292 FALLBACK_BINARY,
293 "a binary that does not identify as the GitCode CLI must be rejected"
294 );
295 }
296
297 #[test]
298 fn test_should_accept_gc_when_it_passes_probe() {
299 let lookup =
300 |candidate: &str| (candidate == "gc").then(|| PathBuf::from("/usr/local/bin/gc"));
301 let probe = |_: &Path| true;
302
303 assert_eq!(resolve_gitcode_binary(lookup, probe), "/usr/local/bin/gc");
304 }
305
306 #[test]
307 fn test_should_fall_back_to_unambiguous_name_when_nothing_resolves() {
308 let lookup = |_: &str| None;
309 let probe = |_: &Path| true;
310
311 assert_eq!(
312 resolve_gitcode_binary(lookup, probe),
313 "gitcode",
314 "falling back to `gc` would re-introduce the shadowing bug"
315 );
316 }
317
318 #[test]
319 fn test_should_identify_real_gitcode_cli_from_help_output() {
320 // Captured verbatim from `gitcode --help` (exit 0).
321 let stdout = "gitcode is a command line tool for GitCode.\n\nIt provides convenient \
322 access to GitCode features including:\n - Authentication management (auth \
323 login, auth status)\n";
324
325 assert!(is_gitcode_help_output(true, stdout, ""));
326 }
327
328 #[test]
329 fn test_should_reject_graphviz_gc_help_output() {
330 // Captured verbatim from Graphviz `gc --help` (exit 1).
331 let stdout = "Usage: gc [-necCaDUrsv?] <files>\n -n - print number of nodes\n";
332 let stderr = "gc: option -- unrecognized\n";
333
334 assert!(
335 !is_gitcode_help_output(false, stdout, stderr),
336 "Graphviz gc must never be mistaken for the GitCode CLI"
337 );
338 }
339
340 #[test]
341 fn test_should_reject_successful_help_without_gitcode_marker() {
342 assert!(
343 !is_gitcode_help_output(true, "Usage: gc [-necCaDUrsv?] <files>", ""),
344 "exit 0 alone is not enough — the output must name GitCode"
345 );
346 }
347
348 #[test]
349 fn test_should_match_gitcode_marker_case_insensitively() {
350 assert!(is_gitcode_help_output(true, "A CLI for GitCode.", ""));
351 }
352}