#![cfg_attr(
test,
allow(
clippy::expect_used,
clippy::unwrap_used,
clippy::indexing_slicing,
clippy::disallowed_methods,
reason = "Tests legitimately need to unwrap fixture data and invoke sync FS helpers"
)
)]
#[allow(
dead_code,
reason = "Generated by `built` crate; fields referenced via built_info::"
)]
#[allow(clippy::needless_raw_string_hashes)]
#[allow(clippy::allow_attributes_without_reason)]
#[allow(clippy::doc_markdown)]
pub mod built_info {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
mod build_git {
include!(concat!(env!("OUT_DIR"), "/git_sha.rs"));
}
mod commands;
mod errors;
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
use commands::{
auth::AuthCommand,
commit::CommitCommand,
completions::CompletionsArgs,
decide::DecideCommand,
issue::IssueCommand,
label::{LabelCommand, MilestoneCommand},
pipeline::PipelineCommand,
pr::PrCommand,
regression_semantic::RegressionCommand,
release::ReleaseCommand,
review::ReviewCommand,
workflow::WorkflowCommand,
};
use is_terminal::IsTerminal;
fn main() -> std::process::ExitCode {
#[cfg(unix)]
reset_sigpipe();
init_tracing();
let version_string: &'static str =
Box::leak(format!("{} ({})", built_info::PKG_VERSION, build_git::GIT_SHA).into_boxed_str());
let matches = match Cli::command().version(version_string).try_get_matches() {
Ok(m) => m,
Err(e) => e.exit(),
};
let cli = match Cli::from_arg_matches(&matches) {
Ok(c) => c,
Err(e) => e.exit(),
};
if let Commands::Completions(ref args) = cli.command {
return commands::completions::generate::<Cli>(args);
}
let rt = match tokio::runtime::Runtime::new() {
Ok(rt) => rt,
Err(e) => {
let report = miette::miette!("Failed to create async runtime: {e}");
eprintln!("{report:?}");
return std::process::ExitCode::from(1);
}
};
let platform_needed = !matches!(
cli.command,
Commands::Skills(_)
| Commands::Decide(_)
| Commands::Regression(_)
| Commands::Issue(IssueCommand::Precheck { .. })
| Commands::Pr(PrCommand::Precheck { .. })
| Commands::Pipeline(PipelineCommand::AnalyzeFailures { .. })
| Commands::Completions(_)
| Commands::Workflow(_)
| Commands::Update(_)
| Commands::Doctor(_)
);
let (platform, repo, remote_url) = if platform_needed {
match resolve_platform(cli.platform.clone()) {
Ok(pr) => pr,
Err(e) => {
eprintln!("{e:?}");
return std::process::ExitCode::from(1);
}
}
} else {
("unknown".to_string(), String::new(), String::new())
};
match rt.block_on(async_main(cli, &platform, &repo, &remote_url)) {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
eprintln!("{e:?}");
std::process::ExitCode::from(1)
}
}
}
async fn async_main(cli: Cli, platform: &str, repo: &str, remote_url: &str) -> miette::Result<()> {
if !matches!(
cli.command,
Commands::Skills(_)
| Commands::Decide(_)
| Commands::Regression(_)
| Commands::Issue(IssueCommand::Precheck { .. } | IssueCommand::Search(_))
| Commands::Pr(PrCommand::Precheck { .. } | PrCommand::Search(_))
| Commands::Pipeline(PipelineCommand::AnalyzeFailures { .. })
| Commands::Completions(_)
| Commands::Workflow(_)
| Commands::Update(_)
| Commands::Doctor(_)
) {
commands::prerequisites::check(platform).map_err(|e| miette::miette!("{e}"))?;
}
tokio::select! {
result = router(cli.command, platform, repo, remote_url, cli.output) => result,
() = async {
match tokio::signal::ctrl_c().await {
Ok(()) => tracing::info!("Received shutdown signal, exiting gracefully"),
Err(e) => tracing::warn!("Failed to install Ctrl+C handler: {e}"),
}
} => {
Ok(())
}
}
}
async fn router(
command: Commands,
platform: &str,
repo: &str,
remote_url: &str,
output: OutputFormat,
) -> miette::Result<()> {
match command {
Commands::Issue(cmd) => {
commands::issue::handle(cmd, platform, repo, remote_url, output).await
}
Commands::Pr(cmd) => commands::pr::handle(cmd, platform, repo, remote_url, output).await,
Commands::Release(cmd) => {
commands::release::handle(cmd, platform, repo, remote_url, output).await
}
Commands::Review(cmd) => commands::review::handle(cmd, platform, repo, output).await,
Commands::Auth(cmd) => commands::auth::handle(cmd, platform, repo, output).await,
Commands::Label(cmd) => {
commands::label::handle_label(cmd, platform, repo, remote_url, output).await
}
Commands::Milestone(cmd) => {
commands::label::handle_milestone(cmd, platform, repo, output).await
}
Commands::Commit(cmd) => commands::commit::handle(cmd, platform, repo, output).await,
Commands::Pipeline(cmd) => {
commands::pipeline::handle(cmd, platform, repo, remote_url, output).await
}
Commands::Workflow(cmd) => commands::workflow::handle(cmd).await,
Commands::Doctor(ref args) => commands::doctor::handle(args),
Commands::Skills(ref cmd) => commands::skills::handle(cmd, output).await,
Commands::Decide(cmd) => commands::decide::handle(cmd, output).await,
Commands::Regression(cmd) => commands::regression_semantic::handle(cmd).await,
Commands::Update(cmd) => {
tokio::task::spawn_blocking(move || commands::update::handle_update(&cmd))
.await
.map_err(|e| miette::miette!("update task panicked: {e}"))?
}
Commands::Completions(_) => Ok(()),
}
}
#[allow(
clippy::disallowed_types,
reason = "Invoked before the tokio runtime is constructed"
)]
fn resolve_platform(cli_platform: Option<PlatformArg>) -> miette::Result<(String, String, String)> {
let output = std::process::Command::new("git")
.args(["remote", "get-url", "origin"])
.output()
.map_err(|e| {
miette::miette!("Failed to get git remote URL: {e}\nAre you in a git repository?")
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(miette::miette!(
"git remote get-url origin failed: {}\nAre you in a git repository?",
stderr.trim()
));
}
let remote_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
let platform = if let Some(p) = cli_platform {
match p {
PlatformArg::Github => "github",
PlatformArg::Gitlab => "gitlab",
PlatformArg::Gitcode => "gitcode",
}
.to_string()
} else {
let detection = gitflow_core::platform::Platform::detect_from_remote_url(&remote_url);
if !detection.is_explicit() {
eprintln!(
"warning: unrecognized domain in remote URL: {remote_url}\nDefaulting to GitLab \
adapter. Use --platform to specify explicitly."
);
}
format!("{:?}", detection.platform).to_lowercase()
};
let repo = extract_repo_from_url(&remote_url)
.ok_or_else(|| miette::miette!("Unable to parse owner/repo from URL: {remote_url}"))?;
Ok((platform, repo, remote_url))
}
#[must_use]
fn extract_repo_from_url(url: &str) -> Option<String> {
let without_prefix = url
.trim_start_matches("https://")
.trim_start_matches("http://")
.trim_start_matches("git@");
let without_auth = if let Some((_auth, host_and_path)) = without_prefix.split_once('@') {
host_and_path
} else {
without_prefix
};
let path = if let Some((_before, after)) = without_auth.split_once(':') {
after.to_string()
} else {
let segments: Vec<&str> = without_auth.split('/').filter(|s| !s.is_empty()).collect();
if segments.len() >= 2 {
#[allow(
clippy::indexing_slicing,
reason = "Safe: segments.len() >= 2 checked above"
)]
segments[1..].join("/")
} else {
return None;
}
};
let no_suffix = path.trim_end_matches(".git");
let segments: Vec<&str> = no_suffix.split('/').filter(|s| !s.is_empty()).collect();
if segments.len() >= 2 {
Some(segments.join("/"))
} else {
None
}
}
fn init_tracing() {
let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
let is_tty = std::io::stderr().is_terminal();
let no_color = std::env::var("NO_COLOR").is_ok();
let force_color = std::env::var("CLICOLOR_FORCE").is_ok_and(|v| v != "0");
let use_json = !is_tty && !force_color;
let use_ansi = !no_color && (is_tty || force_color);
if use_json {
tracing_subscriber::fmt()
.with_env_filter(env_filter)
.json()
.init();
} else {
tracing_subscriber::fmt()
.with_env_filter(env_filter)
.with_ansi(use_ansi)
.with_target(false)
.init();
}
}
#[cfg(unix)]
fn reset_sigpipe() {
}
#[derive(Debug, Clone, clap::ValueEnum)]
enum PlatformArg {
#[value(name = "github")]
Github,
#[value(name = "gitlab")]
Gitlab,
#[value(name = "gitcode")]
Gitcode,
}
#[derive(Debug, Default, Clone, clap::ValueEnum)]
pub enum OutputFormat {
Json,
Text,
Toon,
#[default]
Auto,
}
#[derive(Debug, Parser)]
#[command(name = "gf", about = "gf CLI tool", author)]
struct Cli {
#[arg(long, global = true)]
platform: Option<PlatformArg>,
#[arg(long, global = true, default_value = "auto")]
output: OutputFormat,
#[arg(short, long, global = true)]
verbose: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Debug, Subcommand)]
enum Commands {
#[command(subcommand)]
Decide(DecideCommand),
#[command(subcommand)]
Regression(RegressionCommand),
#[command(subcommand)]
Issue(IssueCommand),
#[command(subcommand)]
Pr(PrCommand),
#[command(subcommand)]
Release(ReleaseCommand),
#[command(subcommand)]
Review(ReviewCommand),
#[command(subcommand)]
Auth(AuthCommand),
#[command(subcommand)]
Label(LabelCommand),
#[command(subcommand)]
Milestone(MilestoneCommand),
#[command(subcommand)]
Commit(CommitCommand),
#[command(subcommand)]
Pipeline(PipelineCommand),
#[command(subcommand)]
Workflow(WorkflowCommand),
Doctor(commands::doctor::DoctorArgs),
#[command(subcommand)]
Skills(commands::skills::SkillsCommand),
Update(commands::update::UpdateArgs),
#[command(hide = true)]
Completions(CompletionsArgs),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_should_parse_skill_suggestion_without_provider() {
let parsed =
Cli::try_parse_from(["gf", "skills", "suggest", "--query", "审查这个 PR"]).unwrap();
assert!(matches!(
parsed.command,
Commands::Skills(commands::skills::SkillsCommand::Suggest(_))
));
assert!(
Cli::try_parse_from(["gf", "skills", "suggest", "--stdin", "--query", "review PR"])
.is_err()
);
}
#[test]
fn test_should_parse_workflow_recommendation_without_live_provider() {
let parsed =
Cli::try_parse_from(["gf", "workflow", "recommend", "--input", "task.json"]).unwrap();
assert!(matches!(
parsed.command,
Commands::Workflow(WorkflowCommand::Recommend {
live: false,
response: None,
..
})
));
assert!(
Cli::try_parse_from([
"gf",
"workflow",
"recommend",
"--input",
"task.json",
"--response",
"saved.json",
"--live"
])
.is_err()
);
}
#[test]
fn test_should_parse_offline_decision_evaluation_commands() {
let eval = Cli::try_parse_from([
"gf",
"decide",
"eval",
"--fixtures",
"cases.json",
"--responses",
"saved.json",
])
.unwrap();
assert!(matches!(
eval.command,
Commands::Decide(DecideCommand::Eval(_))
));
let calibrate = Cli::try_parse_from([
"gf",
"decide",
"calibrate",
"--report",
"report.json",
"--question",
"type",
"--target-accuracy",
"0.9",
])
.unwrap();
assert!(matches!(
calibrate.command,
Commands::Decide(DecideCommand::Calibrate(_))
));
let compare = Cli::try_parse_from([
"gf",
"decide",
"compare",
"--baseline",
"base.json",
"--candidate",
"new.json",
])
.unwrap();
assert!(matches!(
compare.command,
Commands::Decide(DecideCommand::Compare(_))
));
}
#[test]
fn test_should_extract_repo_from_https_url() {
let url = "https://github.com/owner/repo.git";
assert_eq!(extract_repo_from_url(url), Some("owner/repo".to_string()));
}
#[test]
fn test_should_extract_repo_from_ssh_url() {
let url = "git@github.com:owner/repo.git";
assert_eq!(extract_repo_from_url(url), Some("owner/repo".to_string()));
}
#[test]
fn test_should_extract_repo_without_dot_git_suffix() {
let url = "https://github.com/owner/repo";
assert_eq!(extract_repo_from_url(url), Some("owner/repo".to_string()));
}
#[test]
fn test_should_return_none_for_invalid_url() {
assert_eq!(extract_repo_from_url("just-a-string"), None);
assert_eq!(extract_repo_from_url(""), None);
assert_eq!(extract_repo_from_url("https://github.com"), None);
}
#[test]
fn test_should_preserve_multilevel_gitlab_path() {
let url = "git@xyun.git.nyuncloud.com:fusion-cdn/bff/admin.git";
assert_eq!(
extract_repo_from_url(url),
Some("fusion-cdn/bff/admin".to_string())
);
}
#[test]
fn test_should_preserve_gitlab_subgroup_path() {
let url = "https://gitlab.example.com/group/subgroup/project.git";
assert_eq!(
extract_repo_from_url(url),
Some("group/subgroup/project".to_string())
);
}
#[test]
fn test_should_handle_https_with_authentication() {
let url = "https://oauth2:token@xyun.git.nyuncloud.com/fusion-cdn/bff/admin.git";
assert_eq!(
extract_repo_from_url(url),
Some("fusion-cdn/bff/admin".to_string())
);
let url = "https://token@gitlab.example.com/group/project.git";
assert_eq!(
extract_repo_from_url(url),
Some("group/project".to_string())
);
}
#[test]
fn test_should_parse_update_command() {
let cli = Cli::try_parse_from(["gf", "update", "--check"]).expect("parse update");
assert!(matches!(cli.command, Commands::Update(ref a) if a.check));
}
#[test]
fn test_update_does_not_need_platform() {
let cli = Cli::try_parse_from(["gf", "update"]).expect("parse update");
let platform_needed = !matches!(
cli.command,
Commands::Skills(_)
| Commands::Completions(_)
| Commands::Workflow(_)
| Commands::Update(_)
);
assert!(!platform_needed);
}
}