#![allow(
clippy::disallowed_types,
reason = "Pre-runtime sync `Command` invocations for version probing"
)]
use std::process::Command;
#[derive(Debug, Clone)]
#[allow(dead_code, reason = "Fields reserved for future use")]
pub struct CliRequirement {
pub binary: &'static str,
pub min_version: &'static str,
pub install_url: &'static str,
pub install_hint: &'static str,
pub install_cmd: &'static str,
pub login_cmd: &'static str,
pub login_with_token: &'static str,
}
#[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",
}),
"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",
}),
"gitcode" => Some(CliRequirement {
binary: "gitcode",
min_version: "0.5.9",
install_url: "https://gitcode.com/gitcode-cli/cli",
install_hint: "# 方式 1 — Wheel 包(推荐,内置全平台二进制):\n\
pip install https://gitcode.com/gitcode-cli/cli/releases/download/v0.5.9/gitcode_cli-0.5.9-py3-none-any.whl\n\n\
# 方式 2 — PyPI:\n\
pip install gitcode-cli\n\n\
# 方式 3 — Linux DEB:\n\
sudo dpkg -i gitcode_0.5.9_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: "gitcode auth login",
login_with_token: "echo TOKEN | gitcode auth login --with-token",
}),
_ => None,
}
}
#[derive(Debug, thiserror::Error)]
pub enum PrerequisiteError {
#[error(
"[[PLATFORM]] {binary} is not installed.\n\n📦 Install: {install_cmd}\n\nFull \
options:\n{install_hint}\n\n🌐 Official: {install_url}"
)]
NotFound {
binary: String,
platform: String,
install_hint: String,
install_url: String,
install_cmd: String,
},
#[error(
"[[PLATFORM]] {binary} v{found} is too old (need v{required}+).\n\n📦 Upgrade: \
{install_cmd}"
)]
VersionTooLow {
binary: String,
platform: String,
found: String,
required: String,
install_cmd: String,
},
#[error(
"[[PLATFORM]] `{binary}` was found but ` --version` output was invalid.\n\n📦 Reinstall: \
{install_cmd}"
)]
VersionParseFailed {
binary: String,
platform: String,
install_cmd: String,
},
#[error("[[PLATFORM]] Not authenticated.\n\n🔍 Reason: {reason}\n\n🔧 Fix: {hint}")]
NotAuthenticated {
binary: String,
platform: String,
reason: String,
hint: String,
},
#[error("Unsupported platform: {platform}. Supported: github, gitlab, gitcode")]
UnsupportedPlatform { platform: String },
}
pub fn check(platform: &str) -> Result<(), PrerequisiteError> {
let req = requirement_for(platform).ok_or_else(|| PrerequisiteError::UnsupportedPlatform {
platform: platform.into(),
})?;
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_url: req.install_url.into(),
install_cmd: req.install_cmd.into(),
})?;
let version = get_version(req.binary, platform)?;
(req.binary, path, version)
};
tracing::debug!(binary, path = %path.display(), "Found native CLI");
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(),
});
}
tracing::debug!(
binary,
found = version,
minimum = req.min_version,
"Version OK"
);
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(|| "Unknown reason".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_cli_core::AuthChecker> {
match platform {
"github" => Box::new(gitflow_cli_github::GitHubAuthProvider::new()),
"gitlab" => Box::new(gitflow_cli_gitlab::GitLabAuthProvider::new()),
"gitcode" => Box::new(gitflow_cli_gitcode::GitCodeAuthProvider::new()),
_ => unreachable!("Platform already validated by requirement_for"),
}
}
#[allow(
clippy::disallowed_methods,
reason = "binary discovery runs at startup before async runtime is ready"
)]
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 &["gitcode"] {
if let Ok(path) = which::which(binary)
&& let Ok(v) = get_version(binary, platform)
{
return Ok((binary, path, v));
}
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: "gitcode".into(),
platform: platform.into(),
install_hint: requirement_for(platform)
.map_or("", |r| r.install_hint)
.into(),
install_url: requirement_for(platform)
.map_or("", |r| r.install_url)
.into(),
install_cmd: install_cmd.into(),
})
}
fn get_version(binary: &str, platform: &str) -> Result<String, PrerequisiteError> {
let install_cmd = requirement_for(platform).map_or("", |r| r.install_cmd);
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(),
})
}
#[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, "gitcode");
assert_eq!(req.min_version, "0.5.9");
assert_eq!(req.install_cmd, "pip install gitcode-cli");
assert_eq!(req.login_cmd, "gitcode auth login");
assert_eq!(
req.login_with_token,
"echo TOKEN | gitcode 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"));
}
}