gitflow-cli 1.3.0

跨平台 Git 工程化工作流编排框架:统一封装 GitHub / GitLab / GitCode 三大平台,配合 AI Agent Skills,覆盖从需求到发布的完整工程循环。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! 原生 CLI 前置检查。
//!
//! 在执行任何 gitflow 命令之前,检查目标平台对应的原生 CLI
//! 是否已安装、版本满足最低要求,以及是否已登录。
//!
//! 错误消息包含 Agent 可解析的标记:
//! - `[[INSTALL_COMMAND]]` — Agent 可直接运行的单一安装命令
//! - `[[LOGIN_COMMAND]]` — Agent 提示用户在终端输入 token 的登录命令
//! - `[[LOGIN_WITH_TOKEN]]` — Agent 可通过 stdin 传入 token 的登录命令

#![allow(
    clippy::disallowed_types,
    reason = "Pre-runtime sync `Command` invocations for version probing"
)]

use std::process::Command;

/// 原生 CLI 版本要求。
#[derive(Debug, Clone)]
#[allow(dead_code, reason = "Fields reserved for future use")]
pub struct CliRequirement {
    /// CLI 可执行文件名。
    pub binary: &'static str,
    /// 最低版本号(semver)。
    pub min_version: &'static str,
    /// 官方安装指引链接。
    pub install_url: &'static str,
    /// 常见包管理器安装命令。
    pub install_hint: &'static str,
    /// Agent 可直接执行的一键安装命令。
    pub install_cmd: &'static str,
    /// 交互式登录命令。
    pub login_cmd: &'static str,
    /// 非交互式登录命令(从 stdin 读取 token)。
    pub login_with_token: &'static str,
    /// 相关文档链接。
    pub doc_link: &'static str,
}

/// 平台 → CLI 要求映射。
#[must_use]
pub fn requirement_for(platform: &str) -> Option<CliRequirement> {
    match platform {
        "github" => Some(CliRequirement {
            binary: "gh",
            min_version: "2.0.0",
            install_url: "https://github.com/cli/cli#installation",
            install_hint: "brew install gh       # macOS/Linux\n\
                           choco install gh      # Windows\n\
                           sudo apt install gh  # Debian/Ubuntu",
            install_cmd: "brew install gh",
            login_cmd: "gh auth login",
            login_with_token: "echo TOKEN | gh auth login --with-token",
            doc_link: "https://cli.github.com/manual/",
        }),
        "gitlab" => Some(CliRequirement {
            binary: "glab",
            min_version: "1.30.0",
            install_url: "https://gitlab.com/gitlab-org/cli#installation",
            install_hint: "brew install glab   # macOS/Linux\n\
                           sudo apt install glab  # Debian/Ubuntu",
            install_cmd: "brew install glab",
            login_cmd: "glab auth login",
            login_with_token: "glab auth login --token TOKEN",
            doc_link: "https://gitlab.com/gitlab-org/cli/-/blob/main/docs/",
        }),
        "gitcode" => Some(CliRequirement {
            // 优先使用 gc(Linux/macOS 原生名称),gitcode 作为回退
            binary: "gc",
            min_version: "0.6.0",
            install_url: "https://gitcode.com/gitcode-cli/cli",
            install_hint: "# 方式 1 — Wheel 包(推荐,内置全平台二进制):\n\
                           pip install https://gitcode.com/gitcode-cli/cli/releases/download/v0.6.1/gitcode_cli-0.6.1-py3-none-any.whl\n\n\
                           # 方式 2 — PyPI:\n\
                           pip install gitcode-cli\n\n\
                           # 方式 3 — Linux DEB:\n\
                           sudo dpkg -i gitcode_0.6.1_amd64.deb\n\n\
                           # 方式 4 — 源码构建(Go 1.22+):\n\
                           git clone https://gitcode.com/gitcode-cli/cli.git && cd cli\n\
                           make build && mkdir -p ~/.local/bin && mv bin/gitcode ~/.local/bin/",
            install_cmd: "pip install gitcode-cli",
            login_cmd: "gc auth login",
            login_with_token: "echo TOKEN | gc auth login --with-token",
            doc_link: "https://gitcode.com/gitcode-cli/cli/blob/main/README.md",
        }),
        _ => None,
    }
}

/// 格式化平台名称用于显示。
fn format_platform(platform: &str) -> String {
    match platform {
        "github" => "[GitHub]".to_string(),
        "gitlab" => "[GitLab]".to_string(),
        "gitcode" => "[GitCode]".to_string(),
        other => format!("[{other}]"),
    }
}

/// 前置检查失败错误。
#[derive(Debug)]
pub enum PrerequisiteError {
    /// 底层 CLI 未安装。
    NotFound {
        /// CLI 可执行文件名。
        binary: String,
        /// 平台标识。
        platform: String,
        /// 安装选项。
        install_hint: String,
        /// 一键安装命令。
        install_cmd: String,
        /// 文档链接。
        doc_link: String,
    },

    /// 底层 CLI 版本过低。
    VersionTooLow {
        /// CLI 可执行文件名。
        binary: String,
        /// 平台标识。
        platform: String,
        /// 当前版本。
        found: String,
        /// 最低要求版本。
        required: String,
        /// 升级命令。
        install_cmd: String,
        /// 文档链接。
        doc_link: String,
    },

    /// 版本信息解析失败。
    VersionParseFailed {
        /// CLI 可执行文件名。
        binary: String,
        /// 平台标识。
        platform: String,
        /// 安装命令。
        install_cmd: String,
        /// 文档链接。
        doc_link: String,
    },

    /// 未认证。
    NotAuthenticated {
        /// CLI 可执行文件名。
        binary: String,
        /// 平台标识。
        platform: String,
        /// 失败原因。
        reason: String,
        /// 修复命令。
        hint: String,
    },

    /// 不支持的平台。
    UnsupportedPlatform {
        /// 平台标识。
        platform: String,
    },
}

impl std::fmt::Display for PrerequisiteError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound {
                binary,
                platform,
                install_cmd,
                doc_link,
                install_hint,
                ..
            } => write!(
                f,
                "{} 未检测到 {binary}。\n\n📦 安装:{install_cmd}\n📖 \
                 文档:{doc_link}\n\n其他安装方式:\n{install_hint}",
                format_platform(platform)
            ),
            Self::VersionTooLow {
                binary,
                platform,
                found,
                required,
                install_cmd,
                doc_link,
            } => write!(
                f,
                "{} {binary} 版本过低:当前 v{found},需要 v{required}+。\n\n📦 \
                 升级:{install_cmd}\n📖 文档:{doc_link}",
                format_platform(platform)
            ),
            Self::VersionParseFailed {
                binary,
                platform,
                install_cmd,
                doc_link,
            } => write!(
                f,
                "{} {binary} 版本信息解析失败。\n\n📦 重新安装:{install_cmd}\n📖 文档:{doc_link}",
                format_platform(platform)
            ),
            Self::NotAuthenticated {
                binary,
                platform,
                reason,
                hint,
            } => write!(
                f,
                "{} {binary} 未认证。\n\n🔍 原因:{reason}\n🔧 修复:运行 `{hint}` 完成登录",
                format_platform(platform)
            ),
            Self::UnsupportedPlatform { platform } => {
                write!(
                    f,
                    "不支持的平台:{platform}。支持的平台:github、gitlab、gitcode"
                )
            }
        }
    }
}

impl std::error::Error for PrerequisiteError {}

/// 检查原生 CLI 是否可用、版本满足要求且已登录。
#[allow(
    clippy::result_large_err,
    reason = "PrerequisiteError carries structured install hints; boxing would lose ergonomic \
              matching"
)]
pub fn check(platform: &str) -> Result<(), PrerequisiteError> {
    let req = requirement_for(platform).ok_or_else(|| PrerequisiteError::UnsupportedPlatform {
        platform: platform.into(),
    })?;

    // 1. PATH 检查(gitcode 平台会搜索 pip 路径等非标准位置)
    let (binary, path, version) = if platform == "gitcode" {
        find_gitcode_cli(platform)?
    } else {
        let path = which::which(req.binary).map_err(|_| PrerequisiteError::NotFound {
            binary: req.binary.into(),
            platform: platform.into(),
            install_hint: req.install_hint.into(),
            install_cmd: req.install_cmd.into(),
            doc_link: req.doc_link.into(),
        })?;
        let version = get_version(req.binary, platform)?;
        (req.binary, path, version)
    };

    tracing::debug!(binary, path = %path.display(), "Found native CLI");

    // 2. 版本检查
    if !version_meets_minimum(&version, req.min_version) {
        return Err(PrerequisiteError::VersionTooLow {
            binary: binary.into(),
            platform: platform.into(),
            found: version,
            required: req.min_version.into(),
            install_cmd: req.install_cmd.into(),
            doc_link: req.doc_link.into(),
        });
    }

    tracing::debug!(
        binary,
        found = version,
        minimum = req.min_version,
        "Version OK"
    );

    // 3. 认证检查(使用 AuthChecker)
    let auth_checker = create_auth_checker(platform);
    if !auth_checker.is_authenticated() {
        let result = auth_checker.check_status();
        return Err(PrerequisiteError::NotAuthenticated {
            binary: binary.into(),
            platform: platform.into(),
            reason: result.reason.unwrap_or_else(|| "未知原因".into()),
            hint: result.hint.unwrap_or_else(|| req.login_cmd.into()),
        });
    }

    tracing::debug!(binary, "Authenticated");
    Ok(())
}

/// 创建平台特定的认证检查器。
fn create_auth_checker(platform: &str) -> Box<dyn gitflow_core::AuthChecker> {
    match platform {
        "github" => Box::new(gitflow_github::GitHubAuthProvider::new()),
        "gitlab" => Box::new(gitflow_gitlab::GitLabAuthProvider::new()),
        "gitcode" => Box::new(gitflow_gitcode::GitCodeAuthProvider::new()),
        _ => unreachable!("Platform already validated by requirement_for"),
    }
}

/// Try to locate and validate a `GitCode` CLI binary.
///
/// `GitCode` has two binary names (`gc` on Linux/macOS, `gitcode` cross-platform).
/// This function tries `gc` first, then `gitcode`, returning the first one that
/// passes version detection.
#[allow(
    clippy::disallowed_methods,
    reason = "binary discovery runs at startup before async runtime is ready"
)]
#[allow(
    clippy::result_large_err,
    reason = "Same PrerequisiteError size as check()"
)]
fn find_gitcode_cli(
    platform: &str,
) -> Result<(&'static str, std::path::PathBuf, String), PrerequisiteError> {
    let install_cmd = requirement_for(platform).map_or("", |r| r.install_cmd);

    for &binary in &["gc", "gitcode"] {
        // 1. 常规 PATH 搜索
        if let Ok(path) = which::which(binary)
            && let Ok(v) = get_version(binary, platform)
        {
            return Ok((binary, path, v));
        }

        // 2. pip 用户安装路径(macOS ~/Library/Python/X.Y/bin/)
        if let Ok(home) = std::env::var("HOME") {
            let lib = std::path::PathBuf::from(&home).join("Library/Python");
            if let Ok(entries) = std::fs::read_dir(&lib) {
                for entry in entries.flatten() {
                    let p = entry.path().join("bin").join(binary);
                    if p.exists()
                        && let Ok(v) = get_version(&p.to_string_lossy(), platform)
                    {
                        return Ok((binary, p, v));
                    }
                }
            }
        }
    }

    Err(PrerequisiteError::NotFound {
        binary: "gc".into(),
        platform: platform.into(),
        install_hint: requirement_for(platform)
            .map_or("", |r| r.install_hint)
            .into(),
        install_cmd: install_cmd.into(),
        doc_link: requirement_for(platform).map_or("", |r| r.doc_link).into(),
    })
}

#[allow(
    clippy::result_large_err,
    reason = "Same PrerequisiteError size as check()"
)]
fn get_version(binary: &str, platform: &str) -> Result<String, PrerequisiteError> {
    let install_cmd = requirement_for(platform).map_or("", |r| r.install_cmd);

    // 尝试两种版本命令:`--version` flag(gh/glab)和 `version` 子命令(gitcode)
    for version_arg in ["--version", "version"] {
        let output = match Command::new(binary).arg(version_arg).output() {
            Ok(o) if o.status.success() => o,
            _ => continue,
        };

        let stdout = String::from_utf8_lossy(&output.stdout);
        if let Some(v) = extract_semver(&stdout) {
            return Ok(v);
        }
    }

    Err(PrerequisiteError::VersionParseFailed {
        binary: binary.into(),
        platform: platform.into(),
        install_cmd: install_cmd.into(),
        doc_link: requirement_for(platform).map_or("", |r| r.doc_link).into(),
    })
}

#[must_use]
pub fn extract_semver(s: &str) -> Option<String> {
    let re = regex::Regex::new(r"\d+\.\d+\.\d+").ok()?;
    re.find(s).map(|m| m.as_str().to_owned())
}

#[must_use]
pub fn version_meets_minimum(found: &str, minimum: &str) -> bool {
    let parse = |v: &str| -> Vec<u32> { v.split('.').filter_map(|s| s.parse().ok()).collect() };
    parse(found).cmp(&parse(minimum)) != std::cmp::Ordering::Less
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used, reason = "test code")]
mod tests {
    use super::*;

    #[test]
    fn test_should_return_requirement_for_github() {
        let req = requirement_for("github").expect("github requirement");
        assert_eq!(req.binary, "gh");
        assert_eq!(req.min_version, "2.0.0");
        assert_eq!(req.install_cmd, "brew install gh");
        assert_eq!(req.login_cmd, "gh auth login");
        assert_eq!(
            req.login_with_token,
            "echo TOKEN | gh auth login --with-token"
        );
    }

    #[test]
    fn test_should_return_requirement_for_gitcode() {
        let req = requirement_for("gitcode").expect("gitcode requirement");
        assert_eq!(req.binary, "gc");
        assert_eq!(req.min_version, "0.6.0");
        assert_eq!(req.install_cmd, "pip install gitcode-cli");
        assert_eq!(req.login_cmd, "gc auth login");
        assert_eq!(
            req.login_with_token,
            "echo TOKEN | gc auth login --with-token"
        );
    }

    #[test]
    fn test_should_extract_semver_from_gh_version_output() {
        assert_eq!(
            extract_semver("gh version 2.50.0 (2024-01-01)").as_deref(),
            Some("2.50.0")
        );
    }

    #[test]
    fn test_should_extract_semver_from_glab_version_output() {
        assert_eq!(
            extract_semver("glab version 1.35.0 (2024-01-01)").as_deref(),
            Some("1.35.0")
        );
    }

    #[test]
    fn test_should_version_meets_minimum() {
        assert!(version_meets_minimum("2.50.0", "2.0.0"));
        assert!(version_meets_minimum("2.0.0", "2.0.0"));
        assert!(!version_meets_minimum("1.9.0", "2.0.0"));
    }

    #[test]
    fn test_should_display_github_in_not_authenticated_error() {
        let err = PrerequisiteError::NotAuthenticated {
            binary: "gh".into(),
            platform: "github".into(),
            reason: "token expired".into(),
            hint: "gh auth login".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("[GitHub]"), "Expected [GitHub] in: {msg}");
        assert!(
            !msg.contains("[[PLATFORM]]"),
            "Found literal [[PLATFORM]] in: {msg}"
        );
    }

    #[test]
    fn test_should_display_gitlab_in_not_found_error() {
        let err = PrerequisiteError::NotFound {
            binary: "glab".into(),
            platform: "gitlab".into(),
            install_hint: "brew install glab".into(),
            install_cmd: "brew install glab".into(),
            doc_link: "https://docs.gitlab.com".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("[GitLab]"), "Expected [GitLab] in: {msg}");
        assert!(
            !msg.contains("[[PLATFORM]]"),
            "Found literal [[PLATFORM]] in: {msg}"
        );
    }

    #[test]
    fn test_should_display_gitcode_in_version_too_low_error() {
        let err = PrerequisiteError::VersionTooLow {
            binary: "gc".into(),
            platform: "gitcode".into(),
            found: "0.5.0".into(),
            required: "0.6.0".into(),
            install_cmd: "pip install gitcode-cli".into(),
            doc_link: "https://gitcode.com/cli".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("[GitCode]"), "Expected [GitCode] in: {msg}");
        assert!(
            !msg.contains("[[PLATFORM]]"),
            "Found literal [[PLATFORM]] in: {msg}"
        );
    }
}