gitflow-cli 1.1.0

跨平台 Git 工程化工作流编排框架 CLI:统一封装 GitHub / GitLab / GitCode,配合 AI Agent Skills 覆盖需求到发布的完整工程循环。Cross-platform Git engineering workflow CLI.
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! gf CLI entrypoint.
//!
//! Provides a subcommand-based CLI with:
//! - TTY-aware tracing (human-readable for terminals, JSON for pipes)
//! - `NO_COLOR` / `CLICOLOR_FORCE` support
//! - SIGPIPE reset on Unix for clean pipe-exit behaviour
//! - Graceful shutdown via `tokio::signal`
//! - Top-level error display with `miette` formatting

// Tests legitimately need to unwrap fixture data and invoke sync FS helpers.
#![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"
    )
)]

/// Build-time metadata generated by the `built` crate.
///
/// Exposes `PKG_VERSION`, `GIT_COMMIT_HASH`, `TARGET`, and similar
/// constants. Unused fields are expected because the `built` crate
/// generates a fixed set of metadata regardless of what the binary
/// actually reads.
///
/// The lint suppressions are required because the `built` crate's
/// generated source uses unhashed raw string literals, reason-less
/// `#[allow(dead_code)]` attributes, and identifier-like tokens in
/// doc comments that would otherwise fail under the workspace's
/// pedantic lint configuration.
#[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 {
    // Reset SIGPIPE on Unix so broken pipes exit cleanly
    #[cfg(unix)]
    reset_sigpipe();

    // Initialize tracing subscriber (TTY-aware, respects NO_COLOR)
    init_tracing();

    // Build version string: pkg version
    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(),
    };

    // Capture the command name before `cli` is consumed by `async_main`.
    let command_name = cli.command_name();

    // Completions are purely synchronous -- generate and exit
    if let Commands::Completions(ref args) = cli.command {
        return commands::completions::generate::<Cli>(args);
    }

    // Build the async runtime
    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);
        }
    };

    // Resolve platform and repository early so they are available in the
    // error handler below. Skills, Completions, Workflow, and Update commands
    // don't need platform info, so skip resolve_platform for them (allows
    // running outside a git repository).
    let platform_needed = !matches!(
        cli.command,
        Commands::Skills(_)
            | Commands::Completions(_)
            | Commands::Workflow(_)
            | Commands::Update(_)
    );
    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())
    };

    // Block on the async main, handling graceful shutdown signals
    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)
        }
    }
}

/// Best-effort error reporting for non-interactive mode.
///
/// Delegates to [`error_reporter::maybe_report_error`], silently
/// discarding any I/O errors. The error report is a diagnostic aid;
/// a failure to write it must never block or alter the exit code.
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 entry point that wires graceful shutdown into the main flow.
///
/// Flow: check prerequisites → dispatch command.
///
/// The `platform` and `repo` are resolved in `main()` before this
/// function is called so they remain available in the error handler.
async fn async_main(cli: Cli, platform: &str, repo: &str) -> miette::Result<()> {
    // Skills/Completions/Workflow/Update don't need native CLI — skip prerequisite check
    if !matches!(
        cli.command,
        Commands::Skills(_)
            | Commands::Completions(_)
            | Commands::Workflow(_)
            | Commands::Update(_)
    ) {
        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(())
        }
    }
}

/// Dispatch a subcommand to the appropriate handler.
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::Update(cmd) => {
            // `handle_update` uses `self_update` (reqwest::blocking), which creates its own
            // tokio runtime. Running it on the async runtime thread panics on nested runtime
            // drop, so dispatch it to a blocking worker thread.
            tokio::task::spawn_blocking(move || commands::update::handle_update(&cmd))
                .await
                .map_err(|e| miette::miette!("update task panicked: {e}"))?
        }
        Commands::Run(_args) => Err(miette::miette!(
            "run command is deprecated; use specific subcommands"
        )),
        Commands::Completions(_) => Ok(()),
    }
}

/// Resolve the target platform and repository from CLI args and git remote.
///
/// Priority:
/// 1. `--platform` flag (explicit override)
/// 2. `git remote get-url origin` auto-detection
/// 3. Both fail → error with hint to use `--platform`
///
/// # Errors
///
/// - Git remote URL cannot be obtained → hint to run inside a git repo
/// - Platform cannot be detected → hint to use `--platform`
/// - `owner/repo` cannot be parsed from remote URL → parse error
#[allow(
    clippy::disallowed_types,
    reason = "Invoked before the tokio runtime is constructed"
)]
fn resolve_platform(cli_platform: Option<PlatformArg>) -> miette::Result<(String, String)> {
    // Get git remote URL
    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();

    // Determine platform
    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_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()
    };

    // Extract owner/repo
    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))
}

/// Extract repository path from a git remote URL.
///
/// Supports both HTTPS and SSH remote formats:
/// - `https://github.com/owner/repo.git` → `owner/repo`
/// - `git@github.com:owner/repo.git` → `owner/repo`
/// - `https://gitlab.example.com/group/project` → `group/project`
/// - `git@xyun.git.nyuncloud.com:fusion-cdn/bff/admin.git` → `fusion-cdn/bff/admin`
/// - `https://oauth2:token@gitlab.example.com/group/project.git` → `group/project`
///
/// Returns the full path after the domain, preserving multi-level paths
/// for self-hosted GitLab instances. Returns `None` if the URL cannot
/// be parsed into at least two path segments after stripping the scheme,
/// authentication info, and host.
#[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@");

    // Remove authentication info (user:pass@ or token@) if present
    let without_auth = if let Some((_auth, host_and_path)) = without_prefix.split_once('@') {
        host_and_path
    } else {
        without_prefix
    };

    // For SSH URLs like `host:owner/repo`, take the part after `:`.
    // For HTTPS URLs like `host/owner/repo`, split by `/` and skip the host.
    let path = if let Some((_before, after)) = without_auth.split_once(':') {
        // SSH format: `host:owner/repo`
        after.to_string()
    } else {
        // HTTPS format: `host/owner/repo` - skip the first segment (host)
        // segments[1..] is safe here because we check `segments.len() >= 2` on the previous line
        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 {
        // Preserve the full path for multi-level GitLab namespaces
        Some(segments.join("/"))
    } else {
        None
    }
}

/// Initialize the `tracing-subscriber` with TTY-aware output.
///
/// - **TTY (terminal)**: human-readable output. ANSI colours are enabled unless `NO_COLOR` is set.
/// - **Pipe / redirect**: JSON-formatted output for machine consumption, unless `CLICOLOR_FORCE` is
///   set (non-zero), which forces human-readable output with colour.
/// - `NO_COLOR` always disables ANSI escape sequences regardless of output target or
///   `CLICOLOR_FORCE`.
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();
    }
}

/// Reset `SIGPIPE` to the default handler so the process exits
/// cleanly when the output pipe is broken, instead of panicking
/// with an `EPIPE` error.
///
/// This is a well-established pattern for CLI tools (used by
/// ripgrep, fd, bat, and others).
///
/// NOTE: Disabled due to `#![forbid(unsafe_code)]` policy.
/// SIGPIPE handling would require a separate crate or allow-listing unsafe code.
#[cfg(unix)]
fn reset_sigpipe() {
    // Intentionally empty - unsafe SIGPIPE reset disabled to comply with forbid(unsafe_code)
}

/// Platform argument for the `--platform` CLI flag.
///
/// Maps to the three supported hosting platforms. Used as a
/// `clap::ValueEnum` so clap generates value completions and
/// validation automatically.
#[derive(Debug, Clone, clap::ValueEnum)]
enum PlatformArg {
    /// GitHub (github.com or Enterprise).
    #[value(name = "github")]
    Github,
    /// GitLab (gitlab.com or self-hosted).
    #[value(name = "gitlab")]
    Gitlab,
    /// `GitCode` (gitcode.com or self-hosted).
    #[value(name = "gitcode")]
    Gitcode,
}

/// Output format for CLI command results.
///
/// Controls how command output is rendered to the terminal.
#[derive(Debug, Default, Clone, clap::ValueEnum)]
pub enum OutputFormat {
    /// Structured JSON output (for machine consumption by skills).
    Json,
    /// Human-readable plain text output.
    Text,
    /// TOON (Token-Oriented Object Notation) — compact format for LLM consumption.
    Toon,
    /// Automatically select the best format based on data structure analysis (default).
    #[default]
    Auto,
}

/// gf command-line interface.
#[derive(Debug, Parser)]
#[command(name = "gf", about = "gf CLI tool", author)]
struct Cli {
    /// Override platform auto-detection.
    #[arg(long, global = true)]
    platform: Option<PlatformArg>,

    /// Output format (json, text, toon, or auto).
    #[arg(long, global = true, default_value = "auto")]
    output: OutputFormat,

    /// Enable verbose output.
    #[arg(short, long, global = true)]
    verbose: bool,

    #[command(subcommand)]
    command: Commands,
}

impl Cli {
    /// Return the top-level subcommand name for error reporting.
    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::Update(_) => "update",
            Commands::Run(_) => "run",
            Commands::Completions(_) => "completions",
            Commands::Label(_) => "label",
            Commands::Milestone(_) => "milestone",
            Commands::Commit(_) => "commit",
            Commands::Pipeline(_) => "pipeline",
            Commands::Workflow(_) => "workflow",
        }
        .into()
    }
}

/// Available subcommands.
#[derive(Debug, Subcommand)]
enum Commands {
    /// Issue operations (create, list, view).
    #[command(subcommand)]
    Issue(IssueCommand),

    /// Pull request operations (create, list, view).
    #[command(subcommand)]
    Pr(PrCommand),

    /// Release operations (create, list, view, edit, upload, download, delete).
    #[command(subcommand)]
    Release(ReleaseCommand),

    /// Code review operations (comment, approve, request-changes, submit).
    #[command(subcommand)]
    Review(ReviewCommand),

    /// Authentication operations (login, logout, status, token).
    #[command(subcommand)]
    Auth(AuthCommand),

    /// Label operations (create, list, edit, delete).
    #[command(subcommand)]
    Label(LabelCommand),

    /// Milestone operations (create, list, edit, close, reopen).
    #[command(subcommand)]
    Milestone(MilestoneCommand),

    /// Commit operations (view, diff, patch, comment).
    #[command(subcommand)]
    Commit(CommitCommand),

    /// Pipeline operations (status, logs, jobs, report).
    #[command(subcommand)]
    Pipeline(PipelineCommand),

    /// Workflow contract and gate management.
    #[command(subcommand)]
    Workflow(WorkflowCommand),

    /// Skills management operations (install, list, uninstall, update).
    #[command(subcommand)]
    Skills(commands::skills::SkillsCommand),

    /// Update the gf binary to the latest GitHub release.
    Update(commands::update::UpdateArgs),

    /// Run the main application workflow (deprecated).
    Run(commands::run::RunArgs),

    /// Generate shell completion scripts.
    #[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() {
        // GitLab self-hosted with multi-level namespace
        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() {
        // GitLab with subgroup
        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() {
        // HTTPS URL with authentication info
        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())
        );

        // HTTPS URL with simple token
        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);
    }
}