tbdflow 0.28.0

A CLI to streamline your Git workflow for Trunk-Based Development.
Documentation
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
use crate::commands;
use crate::config::Config;
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use colored::Colorize;
use std::process::{Command, Stdio};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum GitError {
    #[error("Git command failed: {0}")]
    Git(String),
    #[error("Working directory is not clean: {0}")]
    DirectoryNotClean(String),
    #[error("Invalid branch type: {0}.")]
    InvalidBranchType(String),
    #[error("Branch '{0}' does not exist locally.")]
    BranchNotFound(String),
    #[error("Tag '{0}' already exists.")]
    TagAlreadyExists(String),
    #[error("Cannot complete the main branch. This is a protected branch.")]
    CannotCompleteMainBranch,
    #[error("Not on main branch: {0}")]
    NotOnMainBranch(String),
    #[error("Not a Git repository: {0}")]
    NotAGitRepository(String),
}

/// Runs a Git command with the specified subcommand and arguments.
fn run_git_command(command: &str, args: &[&str], verbose: bool, dry_run: bool) -> Result<String> {
    if verbose || dry_run {
        if dry_run {
            println!(
                "{}",
                "[DRY RUN] Command would execute but no changes made".yellow()
            );
            println!("git {} {}", command, args.join(" "));
            println!(); // Add blank line for spacing
            return Ok(String::new());
        } else {
            println!("{} git {} {}", "[RUNNING] ".cyan(), command, args.join(" "));
        }
    }

    let output = Command::new("git")
        .arg(command)
        .args(args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .with_context(|| format!("Failed to execute 'git {}'", command))?;

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        Err(GitError::Git(String::from_utf8_lossy(&output.stderr).trim().to_string()).into())
    }
}

/// Checks if the git working directory is clean.
pub fn is_working_directory_clean(verbose: bool, dry_run: bool) -> Result<()> {
    let output = run_git_command("status", &["--porcelain"], verbose, dry_run)?;
    if output.is_empty() {
        Ok(())
    } else {
        Err(GitError::DirectoryNotClean(
            "You have unstaged changes. Please commit or stash them first.".to_string(),
        )
        .into())
    }
}

/// Runs a git command, suppressing stdout/stderr. Returns the exit status.
fn run_git_status_check(
    command: &str,
    args: &[&str],
    verbose: bool,
    _dry_run: bool,
) -> Result<std::process::ExitStatus> {
    if verbose {
        println!(
            "{} git {} {}",
            "[CHECKING] ".dimmed(),
            command,
            args.join(" ")
        );
    }
    Command::new("git")
        .arg(command)
        .args(args)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .with_context(|| format!("Failed to execute 'git {}'", command))
}

/// Checks if there are any changes in the staging area.
pub fn has_staged_changes(verbose: bool, dry_run: bool) -> Result<bool> {
    let status = run_git_status_check("diff", &["--staged", "--quiet"], verbose, dry_run)?;
    // git diff --quiet exits 1 if there are changes, 0 if clean.
    Ok(status.code() == Some(1))
}

pub fn add_remote(
    remote_name: &str,
    remote_url: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<String> {
    run_git_command(
        "remote",
        &["add", remote_name, remote_url],
        verbose,
        dry_run,
    )
}

pub fn checkout_main(verbose: bool, dry_run: bool, main_branch: &str) -> Result<String> {
    run_git_command("checkout", &[main_branch], verbose, dry_run)
}

pub fn pull_latest_with_rebase(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("pull", &["--rebase", "--autostash"], verbose, dry_run)
}

/// Fast-forward only — preserves existing commit SHAs.
/// Fails if the local branch has diverged.
pub fn pull_fast_forward_only(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("pull", &["--ff-only"], verbose, dry_run)
}

pub fn fetch_origin(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("fetch", &["origin"], verbose, dry_run)
}

pub fn remote_branch_exists(branch_name: &str, verbose: bool, dry_run: bool) -> Result<()> {
    let output = run_git_command(
        "ls-remote",
        &["--exit-code", "--heads", "origin", branch_name],
        verbose,
        dry_run,
    );
    match output {
        Ok(_) => Ok(()),
        Err(e) => Err(e),
    }
}

pub fn rebase_onto_main(main_branch_name: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command(
        "rebase",
        &["--autostash", &format!("origin/{}", main_branch_name)],
        verbose,
        dry_run,
    )
}

pub fn add_all(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("add", &["."], verbose, dry_run)
}

/// Stages everything except the given project directories using `:(exclude)` pathspec.
pub fn add_excluding_projects(
    project_dirs: &[String],
    verbose: bool,
    dry_run: bool,
) -> Result<String> {
    let mut args = vec!["."];
    // Use the more explicit and robust `:(exclude)` pathspec syntax.
    let exclude_args: Vec<String> = project_dirs
        .iter()
        .map(|dir| format!(":(exclude){}/", dir))
        .collect();

    let exclude_args_str: Vec<&str> = exclude_args.iter().map(|s| s.as_str()).collect();

    args.extend_from_slice(&exclude_args_str);

    if verbose {
        println!("Excluded dirs: \n{:#?}", args);
    }

    run_git_command("add", &args, verbose, dry_run)
}

pub fn commit(message: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("commit", &["-m", message], verbose, dry_run)
}

pub fn push(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("push", &[], verbose, dry_run)
}

pub fn push_tags(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("push", &["--tags"], verbose, dry_run)
}

pub fn branch_exists_locally(branch_name: &str, verbose: bool, dry_run: bool) -> Result<()> {
    let output = run_git_command(
        "rev-parse",
        &["--verify", "--quiet", branch_name],
        verbose,
        dry_run,
    )?;
    match output {
        _ if output.is_empty() => Err(GitError::BranchNotFound(branch_name.to_string()).into()),
        _ => Ok(()),
    }
}

/// Fuzzy-matches a branch by type prefix and trailing name.
/// Handles branches with or without issue IDs in the middle.
pub fn find_branch(
    name: &str,
    r#type: &str,
    config: &Config,
    verbose: bool,
    dry_run: bool,
) -> Result<String> {
    let prefix = commands::get_branch_prefix_or_error(&config.branch_types, r#type)?;

    let all_branches = run_git_command("branch", &["--list"], verbose, dry_run)?;
    let mut found_branches: Vec<String> = Vec::new();

    for branch in all_branches.lines() {
        let trimmed_branch = branch.trim().trim_start_matches('*').trim();
        let lower_branch = trimmed_branch.to_lowercase();
        let lower_name = name.to_lowercase();
        let lower_prefix = prefix.to_lowercase();

        // Check if the branch starts with the correct prefix and ends with the name.
        // This correctly handles branches with or without issue IDs in the middle.
        if lower_branch.starts_with(&lower_prefix) && lower_branch.ends_with(&lower_name) {
            found_branches.push(trimmed_branch.to_string());
        }
    }

    match found_branches.len() {
        0 => Err(GitError::BranchNotFound(name.to_string()).into()),
        1 => Ok(found_branches.remove(0)),
        _ => Err(anyhow::anyhow!(
            "Multiple branches found matching type '{}' and name '{}':\n{}",
            r#type,
            name,
            found_branches.join("\n")
        )),
    }
}

pub fn tag_exists(tag_name: &str, verbose: bool, dry_run: bool) -> Result<bool> {
    let output = run_git_command("tag", &["-l", tag_name], verbose, dry_run)?;
    Ok(!output.is_empty())
}

pub fn merge_branch(branch_name: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("merge", &["--no-ff", branch_name], verbose, dry_run)
}

pub fn delete_local_branch(branch_name: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("branch", &["-d", branch_name], verbose, dry_run)
}

pub fn delete_remote_branch(branch_name: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command(
        "push",
        &["origin", "--delete", branch_name],
        verbose,
        dry_run,
    )
}

pub fn get_current_branch(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("branch", &["--show-current"], verbose, dry_run)
}

pub fn create_branch(
    branch_name: &str,
    from_point: Option<&str>,
    verbose: bool,
    dry_run: bool,
) -> Result<String> {
    let mut args = vec!["-b", branch_name];
    if let Some(point) = from_point {
        args.push(point);
    }
    run_git_command("checkout", &args, verbose, dry_run)
}

pub fn get_head_commit_hash(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("rev-parse", &["HEAD"], verbose, dry_run)
}

pub fn get_latest_tag(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("describe", &["--tags", "--abbrev=0"], verbose, dry_run)
}

pub fn get_commit_history(range: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("log", &[range, "--pretty=format:%H|%s"], verbose, dry_run)
}

pub fn get_remote_url(verbose: bool, dry_run: bool) -> Result<String> {
    let url = run_git_command("remote", &["get-url", "origin"], verbose, dry_run)?;
    Ok(url.trim_end_matches(".git").to_string())
}

pub fn create_tag(
    tag_name: &str,
    message: &str,
    commit_hash: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<String> {
    run_git_command(
        "tag",
        &["-a", tag_name, "-m", message, commit_hash],
        verbose,
        dry_run,
    )
}

pub fn push_set_upstream(branch_name: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command(
        "push",
        &["--set-upstream", "origin", branch_name],
        verbose,
        dry_run,
    )
}

pub fn get_status_short(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("status", &["--short"], verbose, dry_run)
}

pub fn get_status_full(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("status", &[], verbose, dry_run)
}

pub fn status(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("status", &["--short"], verbose, dry_run)
}

pub fn status_for_path(relative_path: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command(
        "status",
        &["--short", "--", relative_path],
        verbose,
        dry_run,
    )
}

/// Status excluding the given project directories (monorepo root use).
pub fn status_excluding_projects(
    project_dirs: &[String],
    verbose: bool,
    dry_run: bool,
) -> Result<String> {
    let mut args = vec!["--short", "--"];
    let exclude_args: Vec<String> = project_dirs
        .iter()
        .map(|dir| format!(":(exclude){}/", dir))
        .collect();

    let exclude_args_str: Vec<&str> = exclude_args.iter().map(|s| s.as_str()).collect();

    args.extend_from_slice(&exclude_args_str);

    run_git_command("status", &args, verbose, dry_run)
}

/// Monorepo-aware status: scoped to sub-project, root-only, or full.
pub fn get_scoped_status(config: &Config, verbose: bool, dry_run: bool) -> Result<String> {
    let git_root = std::path::PathBuf::from(get_git_root(verbose, dry_run)?);
    let current_dir = std::env::current_dir()?;
    let project_root = crate::config::find_project_root()?;

    if let Some(proj_root) = project_root {
        if current_dir == proj_root {
            status_for_path(".", verbose, dry_run)
        } else {
            let relative_path = proj_root.strip_prefix(&git_root).unwrap_or(&proj_root);
            status_for_path(relative_path.to_str().unwrap(), verbose, dry_run)
        }
    } else if crate::config::is_monorepo_root(config, &current_dir, &git_root) {
        println!(
            "{}",
            "Monorepo root detected. Showing status for root-level files only.".yellow()
        );
        status_excluding_projects(&config.monorepo.project_dirs, verbose, dry_run)
    } else {
        status(verbose, dry_run)
    }
}

/// Monorepo-aware staging. At the repo root, excludes project dirs unless `include_projects` is set.
pub fn stage_scoped_changes(
    config: &Config,
    include_projects: bool,
    verbose: bool,
    dry_run: bool,
) -> Result<()> {
    let git_root = std::path::PathBuf::from(get_git_root(verbose, dry_run)?);
    let current_dir = std::env::current_dir()?;

    if current_dir == git_root
        && config.monorepo.enabled
        && !config.monorepo.project_dirs.is_empty()
    {
        if include_projects {
            println!(
                "{}",
                "Including all project directories in commit.".yellow()
            );
            add_all(verbose, dry_run)?;
        } else {
            println!(
                "{}",
                "Monorepo root detected. Staging root-level files only.".yellow()
            );
            add_excluding_projects(&config.monorepo.project_dirs, verbose, dry_run)?;
        }
    } else {
        add_all(verbose, dry_run)?;
    }

    Ok(())
}

pub fn log_graph(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command(
        "log",
        &["--graph", "--oneline", "-n", "15"],
        verbose,
        dry_run,
    )
}

pub fn get_commit_count_ahead(
    branch: &str,
    main_branch: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<String> {
    let range = format!("origin/{}..{}", main_branch, branch);
    run_git_command("rev-list", &["--count", &range], verbose, dry_run)
}

pub fn get_branch_log(
    branch: &str,
    main_branch: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<String> {
    let range = format!("origin/{}..{}", main_branch, branch);
    run_git_command("log", &["--oneline", "-n", "10", &range], verbose, dry_run)
}

pub fn is_git_repository(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("rev-parse", &["--is-inside-work-tree"], verbose, dry_run)
}

pub fn get_git_root(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("rev-parse", &["--show-toplevel"], verbose, dry_run)
}

pub fn init_git_repository(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("init", &[], verbose, dry_run)
}

pub fn get_stale_branches(
    verbose: bool,
    dry_run: bool,
    main_branch: &str,
    stale_days: i64,
) -> Result<Vec<(String, i64)>> {
    let now = Utc::now();
    let day_in_seconds = stale_days * 24 * 60 * 60;

    let output = run_git_command(
        "for-each-ref",
        &[
            "--format",
            "%(refname:short)|%(committerdate:iso8601-strict)",
            "refs/heads/",
        ],
        verbose,
        dry_run,
    )?;
    let stale_branches = output
        .lines()
        .filter_map(|line| {
            let parts: Vec<&str> = line.split('|').collect();
            if parts.len() == 2 {
                let branch_name = parts[0].to_string();
                if branch_name == main_branch {
                    return None; // Skip the main branch
                }
                if let Ok(date) = DateTime::parse_from_rfc3339(parts[1]) {
                    let duration = now.signed_duration_since(date);
                    if duration.num_seconds() > day_in_seconds {
                        return Some(Ok((branch_name, duration.num_days())));
                    }
                }
            }
            None
        })
        .collect::<Result<Vec<_>, anyhow::Error>>()?;

    Ok(stale_branches)
}

pub fn get_user_name(verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("config", &["user.name"], verbose, dry_run)
}

pub fn get_commit_message(commit_hash: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("log", &["-1", "--format=%s", commit_hash], verbose, dry_run)
}

/// Returns format: `hash|author|subject`
pub fn get_log_since(since: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command(
        "log",
        &["--since", since, "--pretty=format:%H|%an|%s"],
        verbose,
        dry_run,
    )
}

pub fn get_latest_commit_time(
    branch: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<Option<DateTime<Utc>>> {
    let ref_name = format!("origin/{}", branch);
    let output = run_git_command("log", &["-1", "--format=%cI", &ref_name], verbose, dry_run)?;
    if output.is_empty() {
        return Ok(None);
    }
    match DateTime::parse_from_rfc3339(output.trim()) {
        Ok(dt) => Ok(Some(dt.with_timezone(&Utc))),
        Err(_) => Ok(None),
    }
}

pub fn get_file_churn(
    branch: &str,
    hours: u64,
    limit: usize,
    verbose: bool,
    dry_run: bool,
) -> Result<Vec<(String, usize)>> {
    let since = format!("{} hours ago", hours);
    let ref_name = format!("origin/{}", branch);
    let output = run_git_command(
        "log",
        &[
            &ref_name,
            "--since",
            &since,
            "--name-only",
            "--pretty=format:",
        ],
        verbose,
        dry_run,
    )?;

    let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for line in output.lines() {
        let trimmed = line.trim();
        if !trimmed.is_empty() {
            *counts.entry(trimmed.to_string()).or_insert(0) += 1;
        }
    }

    let mut sorted: Vec<(String, usize)> = counts.into_iter().collect();
    sorted.sort_by(|a, b| b.1.cmp(&a.1));
    sorted.truncate(limit);
    Ok(sorted)
}

pub fn get_changed_files(commit_hash: &str, verbose: bool, dry_run: bool) -> Result<Vec<String>> {
    let output = run_git_command(
        "diff-tree",
        &["--no-commit-id", "--name-only", "-r", commit_hash],
        verbose,
        dry_run,
    )?;

    Ok(output
        .lines()
        .filter(|line| !line.is_empty())
        .map(|line| line.to_string())
        .collect())
}

pub fn revert_commit(commit_hash: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("revert", &["--no-edit", commit_hash], verbose, dry_run)
}

/// Remote branches not yet merged into main, without `origin/` prefix.
pub fn get_active_remote_branches(
    main_branch: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<Vec<String>> {
    let main_ref = format!("origin/{}", main_branch);
    let output = run_git_command(
        "branch",
        &["-r", "--no-merged", &main_ref],
        verbose,
        dry_run,
    )?;
    let branches = output
        .lines()
        .map(|l| l.trim())
        .filter(|l| !l.contains("->")) // skip HEAD -> origin/main
        .filter(|l| l.starts_with("origin/"))
        .filter(|l| l.trim_start_matches("origin/") != main_branch)
        .map(|l| l.trim_start_matches("origin/").to_string())
        .collect();
    Ok(branches)
}

/// Three-dot diff: files changed by `head` relative to its fork point from `base`.
pub fn get_diff_files_between_refs(
    base: &str,
    head: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<Vec<String>> {
    let range = format!("{}...{}", base, head);
    let output = run_git_command("diff", &["--name-only", &range], verbose, dry_run)?;
    Ok(output
        .lines()
        .filter(|l| !l.is_empty())
        .map(|s| s.to_string())
        .collect())
}

/// A range of lines touched in a diff hunk.
#[derive(Debug, Clone)]
pub struct HunkRange {
    pub start_line: u32,
    pub line_count: u32,
}

impl HunkRange {
    pub fn overlaps(&self, other: &HunkRange) -> bool {
        let self_end = self.start_line + self.line_count.max(1) - 1;
        let other_end = other.start_line + other.line_count.max(1) - 1;
        self.start_line <= other_end && other.start_line <= self_end
    }
}

/// Parse unified-diff `@@ -a,b +c,d @@` headers into `HunkRange` values.
/// When `side` is `New`, returns the `+c,d` (new file) ranges.
/// When `side` is `Old`, returns the `-a,b` (old file) ranges.
#[derive(Debug, Clone, Copy)]
pub enum DiffSide {
    Old,
    New,
}

fn parse_hunk_headers(diff_output: &str, side: DiffSide) -> Vec<HunkRange> {
    diff_output
        .lines()
        .filter(|l| l.starts_with("@@"))
        .filter_map(|line| {
            // Format: @@ -a,b +c,d @@
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() < 4 {
                return None;
            }
            let token = match side {
                DiffSide::Old => parts[1].trim_start_matches('-'),
                DiffSide::New => parts[2].trim_start_matches('+'),
            };
            let nums: Vec<&str> = token.split(',').collect();
            let start: u32 = nums[0].parse().ok()?;
            let count: u32 = if nums.len() > 1 {
                nums[1].parse().ok()?
            } else {
                1
            };
            Some(HunkRange {
                start_line: start,
                line_count: count,
            })
        })
        .collect()
}

pub fn get_diff_hunks_between_refs(
    base: &str,
    head: &str,
    file: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<Vec<HunkRange>> {
    let range = format!("{}...{}", base, head);
    let output = run_git_command("diff", &["-U0", &range, "--", file], verbose, dry_run)?;
    Ok(parse_hunk_headers(&output, DiffSide::New))
}

pub fn get_branch_author(branch: &str, verbose: bool, dry_run: bool) -> Result<String> {
    let ref_name = format!("origin/{}", branch);
    run_git_command("log", &["-1", "--format=%an", &ref_name], verbose, dry_run)
}

pub fn get_remote_branch_commit_count(
    branch: &str,
    main_branch: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<u32> {
    let range = format!("origin/{}..origin/{}", main_branch, branch);
    let output = run_git_command("rev-list", &["--count", &range], verbose, dry_run)?;
    Ok(output.trim().parse().unwrap_or(0))
}

pub fn get_local_changed_files(verbose: bool, dry_run: bool) -> Result<Vec<String>> {
    let mut files = std::collections::HashSet::new();

    // Unstaged modifications
    let unstaged = run_git_command("diff", &["--name-only"], verbose, dry_run)?;
    for f in unstaged.lines().filter(|l| !l.is_empty()) {
        files.insert(f.to_string());
    }

    // Staged modifications
    let staged = run_git_command("diff", &["--name-only", "--staged"], verbose, dry_run)?;
    for f in staged.lines().filter(|l| !l.is_empty()) {
        files.insert(f.to_string());
    }

    Ok(files.into_iter().collect())
}

pub fn get_local_diff_hunks(file: &str, verbose: bool, dry_run: bool) -> Result<Vec<HunkRange>> {
    let mut hunks = Vec::new();

    // Unstaged changes
    let unstaged = run_git_command("diff", &["-U0", "--", file], verbose, dry_run)?;
    hunks.extend(parse_hunk_headers(&unstaged, DiffSide::New));

    // Staged changes
    let staged = run_git_command("diff", &["-U0", "--staged", "--", file], verbose, dry_run)?;
    hunks.extend(parse_hunk_headers(&staged, DiffSide::New));

    Ok(hunks)
}

/// Check if a commit is an ancestor of the given branch (i.e. the commit exists on that branch).
/// Resolves the commit hash and uses the fully-qualified branch ref to avoid ambiguity
/// (e.g. when a tag has the same name as the branch).
pub fn is_ancestor_of(
    commit_hash: &str,
    branch: &str,
    verbose: bool,
    dry_run: bool,
) -> Result<bool> {
    // Resolve to a full hash — short SHAs can be unreliable with merge-base
    let full_hash = run_git_command("rev-parse", &["--verify", commit_hash], verbose, dry_run)?;
    // In dry-run mode rev-parse returns "" so we just assume it's fine
    if full_hash.is_empty() {
        return Ok(true);
    }
    // Use refs/heads/ to unambiguously refer to the local branch,
    // avoiding conflicts with tags or other refs that share the same name.
    let qualified_branch = format!("refs/heads/{}", branch);
    let status = run_git_status_check(
        "merge-base",
        &["--is-ancestor", &full_hash, &qualified_branch],
        verbose,
        dry_run,
    )?;
    Ok(status.code() == Some(0))
}

pub fn get_commit_subject(commit_hash: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("log", &["-1", "--format=%s", commit_hash], verbose, dry_run)
}

pub fn commit_exists(commit_hash: &str, verbose: bool, dry_run: bool) -> Result<bool> {
    // Use rev-parse --verify which exits non-zero if the ref doesn't exist.
    // run_git_command respects dry-run (returns Ok("")) so we assume it exists in that mode.
    match run_git_command("rev-parse", &["--verify", commit_hash], verbose, dry_run) {
        Ok(_) => Ok(true),
        Err(_) => Ok(false),
    }
}

pub fn resolve_commit_hash(short_sha: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("rev-parse", &["--verify", short_sha], verbose, dry_run)
        .with_context(|| format!("Could not resolve commit '{}'", short_sha))
}

/// The CI status of the latest commit on a branch.
#[derive(Debug, PartialEq)]
pub enum CiStatus {
    /// All checks passed.
    Green,
    /// One or more checks failed.
    Failed,
    /// Checks are still running.
    Pending,
    /// Unable to determine status (gh CLI missing, no CI configured, etc.).
    Unknown(String),
}

/// Check the CI status of the latest commit on the given branch using the `gh` CLI.
///
/// Uses `gh api` to query the combined commit status and check-runs for the
/// branch tip. Falls back gracefully if `gh` is not installed or if the repo
/// has no CI configured.
pub fn check_ci_status(branch: &str, verbose: bool, dry_run: bool) -> CiStatus {
    if dry_run {
        if verbose {
            println!("{}", "[DRY RUN] Would check CI status via gh CLI".yellow());
        }
        return CiStatus::Green;
    }

    // First, check if `gh` CLI is available
    if Command::new("gh")
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .is_err()
    {
        return CiStatus::Unknown("gh CLI is not installed".to_string());
    }

    if verbose {
        println!(
            "{} Checking CI status for branch '{}'...",
            "[PRE-FLIGHT]".cyan(),
            branch
        );
    }

    // Use `gh run list` to query the status of the latest workflow run on the branch.
    // This gives us the overall conclusion of the most recent CI run.
    let output = Command::new("gh")
        .args([
            "run",
            "list",
            "--branch",
            branch,
            "--limit",
            "1",
            "--json",
            "status,conclusion",
            "--jq",
            ".[0] | .status + \"/\" + .conclusion",
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output();

    let output = match output {
        Ok(o) => o,
        Err(e) => {
            return CiStatus::Unknown(format!("Failed to run gh CLI: {}", e));
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        // If the command failed because there are no workflow runs, treat as unknown
        return CiStatus::Unknown(format!("gh run list failed: {}", stderr));
    }

    let result = String::from_utf8_lossy(&output.stdout).trim().to_string();

    if verbose {
        println!("{} gh run status: {}", "[PRE-FLIGHT]".cyan(), result);
    }

    if result.is_empty() || result == "/" || result == "null/null" {
        return CiStatus::Unknown("No CI runs found for this branch".to_string());
    }

    // Parse the status/conclusion pair
    let parts: Vec<&str> = result.splitn(2, '/').collect();
    let status = parts.first().unwrap_or(&"");
    let conclusion = parts.get(1).unwrap_or(&"");

    match (*status, *conclusion) {
        ("completed", "success") => CiStatus::Green,
        ("completed", "failure") | ("completed", "timed_out") | ("completed", "cancelled") => {
            CiStatus::Failed
        }
        ("in_progress", _) | ("queued", _) | ("waiting", _) | ("pending", _) => CiStatus::Pending,
        ("completed", "skipped") | ("completed", "neutral") => CiStatus::Green,
        _ => CiStatus::Unknown(format!("Unexpected CI state: {}/{}", status, conclusion)),
    }
}

/// Creates an immutable stash snapshot without touching the stash reflog.
pub fn stash_create(verbose: bool, dry_run: bool) -> Result<Option<String>> {
    let hash = run_git_command("stash", &["create"], verbose, dry_run)?;
    if hash.is_empty() {
        Ok(None)
    } else {
        Ok(Some(hash))
    }
}

pub fn stash_apply(hash: &str, verbose: bool, dry_run: bool) -> Result<String> {
    run_git_command("stash", &["apply", hash], verbose, dry_run)
}

pub fn is_working_directory_dirty(verbose: bool, dry_run: bool) -> Result<bool> {
    let output = run_git_command("status", &["--porcelain"], verbose, dry_run)?;
    Ok(!output.is_empty())
}

pub fn check_git_operation_in_progress(verbose: bool, dry_run: bool) -> Result<Option<String>> {
    let git_dir = run_git_command("rev-parse", &["--git-dir"], verbose, dry_run)?;
    let git_path = std::path::Path::new(&git_dir);

    if git_path.join("rebase-apply").is_dir() || git_path.join("rebase-merge").is_dir() {
        return Ok(Some("A rebase is already in progress.".to_string()));
    }
    if git_path.join("MERGE_HEAD").exists() {
        return Ok(Some("A merge is already in progress.".to_string()));
    }
    if git_path.join("CHERRY_PICK_HEAD").exists() {
        return Ok(Some("A cherry-pick is already in progress.".to_string()));
    }
    if git_path.join("REBASE_HEAD").exists() {
        return Ok(Some("A rebase is already in progress.".to_string()));
    }
    Ok(None)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_git_is_installed() {
        let result = Command::new("git").arg("--version").output();
        assert!(result.is_ok(), "Git is not installed or not in PATH");
        let output = result.unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains("git version"),
            "Unexpected output: {}",
            stdout
        );
    }

    #[test]
    fn test_run_git_command_version() {
        let verbose = true;
        let dry_run = false;
        let result = run_git_command("--version", &[], verbose, dry_run);
        assert!(result.is_ok(), "Expected Ok, got {:?}", result);
        let output = result.unwrap();
        assert!(output.contains("git version"), "Output was: {}", output);
    }

    #[test]
    fn test_status() {
        let verbose = true;
        let dry_run = false;
        let result = status(verbose, dry_run);
        assert!(result.is_ok(), "Expected Ok, got {:?}", result);
        let output = result.unwrap();
        // Accept any output (including empty if clean)
        assert!(
            output.is_empty()
                || output.contains("M ")
                || output.contains("A ")
                || output.contains("D "),
            "Unexpected status output: {}",
            output
        );
    }

    #[test]
    fn test_ci_status_dry_run_returns_green() {
        let result = check_ci_status("main", false, true);
        assert_eq!(result, CiStatus::Green);
    }

    #[test]
    fn test_ci_status_equality() {
        assert_eq!(CiStatus::Green, CiStatus::Green);
        assert_eq!(CiStatus::Failed, CiStatus::Failed);
        assert_eq!(CiStatus::Pending, CiStatus::Pending);
        assert_ne!(CiStatus::Green, CiStatus::Failed);
        assert_ne!(CiStatus::Green, CiStatus::Pending);
        assert_ne!(CiStatus::Failed, CiStatus::Pending);
    }
}