#![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 commands;
mod error_reporter;
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
use commands::{
auth::AuthCommand,
commit::CommitCommand,
completions::CompletionsArgs,
issue::IssueCommand,
label::{LabelCommand, MilestoneCommand},
pipeline::PipelineCommand,
pr::PrCommand,
release::ReleaseCommand,
review::ReviewCommand,
workflow::WorkflowCommand,
};
use is_terminal::IsTerminal;
fn main() -> std::process::ExitCode {
#[cfg(unix)]
reset_sigpipe();
init_tracing();
let matches = match Cli::command()
.version(built_info::PKG_VERSION)
.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(),
};
let command_name = cli.command_name();
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}");
report_error_noninteractive(
&command_name,
"unknown",
&report.to_string(),
"RUNTIME_ERROR",
);
eprintln!("{report:?}");
return std::process::ExitCode::from(1);
}
};
let platform_needed = !matches!(
cli.command,
Commands::Skills(_) | Commands::Completions(_) | Commands::Workflow(_)
);
let (platform, repo) = if platform_needed {
match resolve_platform(cli.platform.clone()) {
Ok(pr) => pr,
Err(e) => {
report_error_noninteractive(
&command_name,
"unknown",
&e.to_string(),
"PLATFORM_ERROR",
);
eprintln!("{e:?}");
return std::process::ExitCode::from(1);
}
}
} else {
("unknown".to_string(), String::new())
};
match rt.block_on(async_main(cli, &platform, &repo)) {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
if platform_needed {
report_error_noninteractive(&command_name, &platform, &e.to_string(), "CLI_ERROR");
}
eprintln!("{e:?}");
std::process::ExitCode::from(1)
}
}
}
fn report_error_noninteractive(
command: &str,
platform: &str,
error_message: &str,
error_code: &str,
) {
let _ = error_reporter::maybe_report_error(command, platform, error_message, error_code);
}
async fn async_main(cli: Cli, platform: &str, repo: &str) -> miette::Result<()> {
if !matches!(
cli.command,
Commands::Skills(_) | Commands::Completions(_) | Commands::Workflow(_)
) {
commands::prerequisites::check(platform).map_err(|e| miette::miette!("{e}"))?;
}
tokio::select! {
result = router(cli.command, platform, repo, 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,
output: OutputFormat,
) -> miette::Result<()> {
match command {
Commands::Issue(cmd) => commands::issue::handle(cmd, platform, repo, output).await,
Commands::Pr(cmd) => commands::pr::handle(cmd, platform, repo, output).await,
Commands::Release(cmd) => commands::release::handle(cmd, platform, repo, 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, 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, output).await,
Commands::Workflow(cmd) => commands::workflow::handle(cmd),
Commands::Skills(ref cmd) => commands::skills::handle(cmd),
Commands::Run(_args) => Err(miette::miette!(
"run command is deprecated; use specific subcommands"
)),
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)> {
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 detected = gitflow_cli_core::platform::Platform::detect_from_remote_url(&remote_url)
.ok_or_else(|| {
miette::miette!(
"Unable to detect platform from remote URL: {remote_url}\nUse --platform to \
specify explicitly."
)
})?;
format!("{detected:?}").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))
}
#[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 = "gitflow-cli", about = "gitflow-cli 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,
}
impl Cli {
fn command_name(&self) -> String {
match self.command {
Commands::Issue(_) => "issue",
Commands::Pr(_) => "pr",
Commands::Release(_) => "release",
Commands::Review(_) => "review",
Commands::Auth(_) => "auth",
Commands::Skills(_) => "skills",
Commands::Run(_) => "run",
Commands::Completions(_) => "completions",
Commands::Label(_) => "label",
Commands::Milestone(_) => "milestone",
Commands::Commit(_) => "commit",
Commands::Pipeline(_) => "pipeline",
Commands::Workflow(_) => "workflow",
}
.into()
}
}
#[derive(Debug, Subcommand)]
enum Commands {
#[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),
#[command(subcommand)]
Skills(commands::skills::SkillsCommand),
Run(commands::run::RunArgs),
#[command(hide = true)]
Completions(CompletionsArgs),
}
#[cfg(test)]
mod tests {
use super::*;
#[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())
);
}
}