git-send 0.1.6

Commit and push changes with a single command
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
//! Main workflow execution logic

use anyhow::{Context, Result};
use clap::Parser;

use crate::commit::{
    DEFAULT_MSG, detect_wip_commits, generate_commit_message, is_conventional_commit,
    suggest_conventional_type, validate_commit_message,
};
use crate::config::Config;
use crate::git::{
    abort_rebase_or_merge, get_commit_counts, get_current_branch, git, has_merge_conflicts,
    is_merge_in_progress, is_rebase_in_progress, validate_git_repo,
};
use crate::hooks::{run_post_push_hooks, run_pre_push_hooks};
use crate::interactive::{confirm, get_env_bool, get_env_var, prompt_with_default};
use crate::output::{Output, show_summary};
use crate::status::{
    count_files_to_stage, has_changes_to_stage, has_staged_changes, has_uncommitted_changes,
    show_status,
};
use crate::types::{
    BlockingState, ExecutionMode, PullMode, PushMode, StashMode, Summary, WorkflowConfig,
};

#[derive(Debug, Parser)]
#[command(
    name = "git-send",
    version,
    about = "Stage, commit, pull, and push changes with a single command",
    long_about = "git-send automates the common git workflow: staging all changes, committing, \
                  pulling with rebase, and pushing to remote.\n\n\
                  Examples:\n  \
                  git-send -m \"fix: resolve bug\"\n  \
                  git-send --auto-message --verbose\n  \
                  git-send --interactive\n  \
                  git-send --dry-run\n\n\
                  Environment Variables:\n  \
                  GIT_SEND_MESSAGE - Default commit message\n  \
                  GIT_SEND_AUTO_STASH - Enable auto-stash (set to '1' or 'true')\n  \
                  GIT_SEND_SKIP_HOOKS - Skip pre-push hooks (set to '1' or 'true')\n\n\
                  Exit Codes:\n  \
                  0 - Success\n  \
                  1 - Error occurred\n  \
                  2 - Invalid arguments\n\n\
                  For more information, see: https://git.sr.ht/~anhkhoakz/git-send"
)]
#[allow(clippy::struct_excessive_bools)]
pub struct Args {
    /// Commit message
    ///
    /// If not provided, uses `GIT_SEND_MESSAGE` env var or prompts in interactive mode.
    /// Falls back to default message: "update: automated commit"
    #[arg(short, long, value_name = "MESSAGE")]
    pub message: Option<String>,

    /// Show operations without executing
    ///
    /// Useful for previewing what would happen without making changes.
    #[arg(long)]
    pub dry_run: bool,

    /// Skip git pull step
    #[arg(long)]
    pub no_pull: bool,

    /// Skip git push step
    #[arg(long)]
    pub no_push: bool,

    /// Auto-stash uncommitted changes before pull
    ///
    /// Automatically stashes uncommitted changes before pulling, then restores them after.
    /// Can also be enabled via `GIT_SEND_AUTO_STASH` environment variable.
    #[arg(long)]
    pub auto_stash: bool,

    /// Verbose output showing each step
    ///
    /// Provides detailed progress information for each operation.
    #[arg(short, long)]
    pub verbose: bool,

    /// Quiet mode: minimal output for scripting
    ///
    /// Suppresses all output except errors. Useful for automation and scripts.
    #[arg(short, long)]
    pub quiet: bool,

    /// Interactive mode: show status, prompt for message, confirm push
    ///
    /// Enables interactive prompts for commit message and push confirmation.
    /// Defaults to non-interactive for scripting compatibility.
    #[arg(short, long)]
    pub interactive: bool,

    /// Amend previous commit instead of creating new one
    #[arg(long)]
    pub amend: bool,

    /// Use --force-with-lease for safer force push
    ///
    /// Safer alternative to --force that prevents overwriting remote changes.
    #[arg(long)]
    pub force_with_lease: bool,

    /// Specify upstream branch (defaults to current branch)
    ///
    /// Push to a different branch than the current one.
    #[arg(long, value_name = "BRANCH")]
    pub upstream: Option<String>,

    /// Abort ongoing rebase/merge and exit
    ///
    /// Safely aborts any in-progress rebase or merge operation.
    #[arg(long)]
    pub abort: bool,

    /// Auto-generate commit message from changed files
    ///
    /// Automatically creates a commit message based on the files that changed.
    #[arg(long)]
    pub auto_message: bool,

    /// Skip pre-push hooks (tests, validation)
    ///
    /// Bypasses pre-push validation scripts and tests.
    /// Can also be enabled via `GIT_SEND_SKIP_HOOKS` environment variable.
    #[arg(long)]
    pub skip_hooks: bool,

    /// Automatically confirm all prompts (non-interactive)
    ///
    /// Answers 'yes' to all confirmation prompts. Useful for scripting.
    /// This flag makes the tool fully non-interactive.
    #[arg(long, short = 'y')]
    pub yes: bool,

    /// Output results in JSON format
    ///
    /// Provides structured JSON output for programmatic consumption.
    /// All output goes to stdout, errors to stderr.
    #[arg(long)]
    pub json: bool,
}

/// Handles abort flag.
fn handle_abort_flag(output: &Output) -> Result<()> {
    output.info("Aborting ongoing rebase/merge...");
    abort_rebase_or_merge()?;
    output.success("Aborted successfully");
    Ok(())
}

/// Reports blocking state with appropriate instructions
fn report_blocking_state(output: &Output, state: BlockingState) -> Result<()> {
    match state {
        BlockingState::Rebase => {
            output.error("A rebase is in progress. Please complete or abort it first.");
            output.println("  To continue: git rebase --continue");
            output.println("  To abort: git rebase --abort");
            output.println("  Or use: git-send --abort");
            anyhow::bail!("Rebase in progress. Resolve conflicts or abort to continue.")
        }
        BlockingState::Merge => {
            output.error("A merge is in progress. Please complete or abort it first.");
            output.println("  To continue: git merge --continue");
            output.println("  To abort: git merge --abort");
            output.println("  Or use: git-send --abort");
            anyhow::bail!("Merge in progress. Complete or abort to continue.")
        }
        BlockingState::Conflicts => {
            output.error("Merge conflicts detected. Resolve before running git-send.");
            output.println("  1. Check conflicted files: git status");
            output.println("  2. Resolve conflicts in each file");
            output.println("  3. Stage resolved files: git add <file>");
            output.println("  4. Continue: git rebase --continue (if rebasing)");
            output.println("  5. Then re-run: git-send");
            anyhow::bail!("Merge conflicts detected. Resolve conflicts first.")
        }
    }
}

/// Validates repository state before operations
fn validate_repository_state(output: &Output) -> Result<()> {
    validate_git_repo().context(
        "Not in a git repository. Initialize with 'git init' or navigate to a git repository.",
    )?;

    if is_rebase_in_progress()? {
        return report_blocking_state(output, BlockingState::Rebase);
    }

    if is_merge_in_progress()? {
        return report_blocking_state(output, BlockingState::Merge);
    }

    Ok(())
}

/// Gets execution mode from args.
const fn get_execution_mode(args: &Args) -> ExecutionMode {
    if args.dry_run {
        return ExecutionMode::DryRun;
    }
    ExecutionMode::Execute
}

/// Gets pull mode from args.
const fn get_pull_mode(args: &Args) -> PullMode {
    if args.no_pull {
        return PullMode::Disabled;
    }
    PullMode::Enabled
}

/// Gets push mode from args.
const fn get_push_mode(args: &Args) -> PushMode {
    if args.no_push {
        return PushMode::Disabled;
    }
    PushMode::Enabled
}

/// Gets stash mode with config file support
fn get_stash_mode_with_config(args: &Args, config: &Config) -> StashMode {
    if args.auto_stash {
        return StashMode::Auto;
    }

    if get_env_bool("GIT_SEND_AUTO_STASH") {
        return StashMode::Auto;
    }

    if config.auto_stash == Some(true) {
        return StashMode::Auto;
    }

    StashMode::Disabled
}

/// Gets commit message from user input in interactive mode.
fn get_interactive_message(args: &Args, output: &Output) -> Result<String> {
    let default = if args.auto_message {
        generate_commit_message()
    } else {
        DEFAULT_MSG.to_string()
    };

    if let Some(suggested_type) = suggest_conventional_type() {
        output.info(&format!(
            "Suggested type: {suggested_type} (conventional commits)"
        ));
    }

    let input = prompt_with_default("Commit message", &default)?;

    if !input.trim().is_empty() {
        return Ok(input);
    }

    Ok(default)
}

/// Gets commit message from environment variable or default.
fn get_message_from_env() -> Option<String> {
    get_env_var("GIT_SEND_MESSAGE")
}

/// Gets commit message with config file support
fn get_commit_message_with_config(
    args: &Args,
    execution_mode: ExecutionMode,
    output: &Output,
    config: &Config,
) -> Result<String> {
    if let Some(ref m) = args.message {
        return Ok(m.clone());
    }

    if let Some(env_msg) = get_message_from_env()
        && !env_msg.trim().is_empty()
    {
        return Ok(env_msg);
    }

    if args.auto_message {
        return Ok(generate_commit_message());
    }

    if args.interactive && matches!(execution_mode, ExecutionMode::Execute) {
        return get_interactive_message(args, output);
    }

    // Fall back to config file default message
    if let Some(ref config_msg) = config.default_message
        && !config_msg.trim().is_empty()
    {
        return Ok(config_msg.clone());
    }

    Ok(DEFAULT_MSG.to_string())
}

/// Suggests conventional commit format if needed.
fn suggest_conventional_format_if_needed(msg: &str, args: &Args, output: &Output) {
    if is_conventional_commit(msg) {
        return;
    }

    if args.quiet {
        return;
    }

    if let Some(suggested_type) = suggest_conventional_type() {
        output.warning(&format!(
            "Consider using conventional commit format: {suggested_type}: <description>"
        ));
    }
}

/// Shows WIP commits if found in interactive mode.
fn show_wip_commits_if_found(
    args: &Args,
    execution_mode: ExecutionMode,
    output: &Output,
) -> Result<()> {
    if !args.interactive {
        return Ok(());
    }

    if !matches!(execution_mode, ExecutionMode::Execute) {
        return Ok(());
    }

    let wip_commits = detect_wip_commits()?;
    if wip_commits.is_empty() {
        return Ok(());
    }

    output.warning(&format!("Found {} WIP commit(s):", wip_commits.len()));
    for commit in &wip_commits {
        output.println(&format!("  - {commit}"));
    }

    if confirm("Would you like to squash these commits?", false, args.yes)? {
        output.info("Use 'git rebase -i HEAD~N' to squash commits manually");
    }

    Ok(())
}

/// Reports merge conflicts error
fn report_merge_conflicts(output: &Output) -> Result<()> {
    report_blocking_state(output, BlockingState::Conflicts)
}

/// Stages changes if any exist.
fn stage_changes_if_needed(args: &Args, summary: &mut Summary, output: &Output) -> Result<()> {
    let has_changes = has_changes_to_stage()?;
    if !has_changes {
        summary.skipped_stage = true;
        if args.verbose {
            output.warning("No changes to stage");
        }
        return Ok(());
    }

    if args.verbose {
        output.progress("Staging changes... ");
    }

    output.command("git add -A");
    git(&["add", "-A"]).context("Failed to stage changes")?;

    if args.verbose {
        output.success("Staged");
    }

    summary.files_staged = count_files_to_stage()?;
    Ok(())
}

/// Creates commit arguments based on amend flag.
fn build_commit_args(msg: &str, amend: bool) -> Vec<&str> {
    if amend {
        return vec!["commit", "--amend", "-m", msg];
    }
    vec!["commit", "-m", msg]
}

/// Commits changes if staged.
fn commit_changes_if_staged(
    args: &Args,
    msg: &str,
    summary: &mut Summary,
    output: &Output,
) -> Result<()> {
    let has_staged = has_staged_changes()?;
    if !has_staged {
        summary.skipped_commit = true;
        if args.verbose {
            output.warning("Nothing to commit (working tree clean)");
        }
        return Ok(());
    }

    if args.verbose {
        output.progress("Committing changes... ");
    }

    let commit_args = build_commit_args(msg, args.amend);
    let cmd = if args.amend {
        format!("git commit --amend -m \"{msg}\"")
    } else {
        format!("git commit -m \"{msg}\"")
    };
    output.command(&cmd);
    git(&commit_args).context("Failed to commit changes")?;

    if args.verbose {
        output.success("Committed");
    }

    summary.commits_created = 1;
    Ok(())
}

/// Determines if stashing is needed.
fn should_stash(pull_mode: PullMode, stash_mode: StashMode) -> Result<bool> {
    if !matches!(pull_mode, PullMode::Enabled) {
        return Ok(false);
    }

    if !matches!(stash_mode, StashMode::Auto) {
        return Ok(false);
    }

    has_uncommitted_changes()
}

/// Stashes uncommitted changes if needed.
fn stash_changes_if_needed(
    args: &Args,
    pull_mode: PullMode,
    stash_mode: StashMode,
    summary: &mut Summary,
    output: &Output,
) -> Result<bool> {
    let needs_stash = should_stash(pull_mode, stash_mode)?;
    if !needs_stash {
        return Ok(false);
    }

    if args.verbose {
        output.progress("Stashing uncommitted changes... ");
    }

    output.command("git stash push -u");
    git(&["stash", "push", "-u"]).context("Failed to stash changes")?;

    if args.verbose {
        output.success("Stashed");
    }

    summary.stashed = true;
    Ok(true)
}

/// Handles stash pop conflicts
fn handle_stash_conflicts(output: &Output) -> Result<()> {
    output.error("Stash pop resulted in conflicts.");
    output.println("  1. Resolve conflicts in each file");
    output.println("  2. Stage resolved files: git add <file>");
    output.println("  3. Drop the stash: git stash drop");
    output.println("  4. Re-run: git-send");
    anyhow::bail!("Stash conflicts detected. Resolve manually before continuing.")
}

/// Handles stash pop with conflict detection.
fn stash_pop_safe(output: &Output) -> Result<()> {
    output.command("git stash pop");
    let result = git(&["stash", "pop"]);
    if let Err(e) = result {
        if has_merge_conflicts().unwrap_or(false) {
            return handle_stash_conflicts(output);
        }
        return Err(e.context("Failed to restore stashed changes"));
    }
    Ok(())
}

/// Reports rebase conflict error.
fn report_rebase_conflict(output: &Output) -> Result<()> {
    output.error("Merge conflicts occurred during rebase.");
    output.println("Please resolve conflicts manually:");
    output.println("  1. Resolve conflicts in the files");
    output.println("  2. Run 'git add <file>' for each resolved file");
    output.println("  3. Run 'git rebase --continue'");
    output.println("  4. Re-run git-send when done");
    anyhow::bail!("Merge conflicts during rebase");
}

/// Pulls with rebase if behind upstream.
fn pull_if_behind(
    args: &Args,
    branch: &str,
    upstream: &str,
    pull_mode: PullMode,
    summary: &mut Summary,
    output: &Output,
) -> Result<()> {
    if !matches!(pull_mode, PullMode::Enabled) {
        return Ok(());
    }

    if args.verbose {
        output.progress(&format!("Pulling with rebase from origin/{upstream}... "));
    }

    let (_ahead, behind) = get_commit_counts(branch, &format!("origin/{upstream}"));

    if behind == 0 {
        summary.skipped_pull = true;
        if args.verbose {
            output.warning(&format!("Already up to date with origin/{upstream}"));
        }
        return Ok(());
    }

    output.command(&format!("git pull --rebase origin {upstream}"));
    let result = git(&["pull", "--rebase", "origin", upstream]);
    if let Err(e) = result {
        if has_merge_conflicts().unwrap_or(false) {
            return report_rebase_conflict(output);
        }
        return Err(e.context("Failed to pull changes"));
    }

    if args.verbose {
        output.success(&format!("Pulled {behind} commit(s)"));
    }

    summary.commits_pulled = behind;
    Ok(())
}

/// Warns about force push and confirms if interactive.
fn warn_and_confirm_force_push(args: &Args, output: &Output) -> Result<bool> {
    if !args.force_with_lease {
        return Ok(true);
    }

    output.warning("Warning: Using --force-with-lease. This will overwrite remote history.");

    if !args.interactive {
        return Ok(true);
    }

    if !confirm("Continue with force push?", false, args.yes)? {
        output.info("Push cancelled by user");
        return Ok(false);
    }

    Ok(true)
}

/// Builds push arguments based on force flag.
fn build_push_args(upstream: &str, force_with_lease: bool) -> Vec<&str> {
    if force_with_lease {
        return vec!["push", "--force-with-lease", "origin", upstream];
    }
    vec!["push", "origin", upstream]
}

/// Confirms push in interactive mode.
fn confirm_push_if_interactive(
    args: &Args,
    ahead: usize,
    upstream: &str,
    output: &Output,
) -> Result<bool> {
    if !args.interactive {
        return Ok(true);
    }

    let confirmed = confirm(
        &format!("Push {} commit(s) to origin/{}?", ahead.max(1), upstream),
        true,
        args.yes,
    )?;

    if confirmed {
        return Ok(true);
    }

    output.info("Push cancelled by user");
    Ok(false)
}

/// Pushes changes if ahead of upstream.
fn push_if_ahead(
    args: &Args,
    branch: &str,
    upstream: &str,
    push_mode: PushMode,
    summary: &mut Summary,
    stashed: bool,
    output: &Output,
) -> Result<()> {
    if !matches!(push_mode, PushMode::Enabled) {
        return Ok(());
    }

    let (ahead, _) = get_commit_counts(branch, &format!("origin/{upstream}"));

    if ahead == 0 && summary.commits_created == 0 {
        summary.skipped_push = true;
        if args.verbose {
            output.warning("Nothing to push (already up to date)");
        }
        return Ok(());
    }

    let should_continue = warn_and_confirm_force_push(args, output)?;
    if !should_continue {
        if stashed {
            stash_pop_safe(output)?;
        }
        return Ok(());
    }

    let should_skip_hooks = args.skip_hooks || get_env_bool("GIT_SEND_SKIP_HOOKS");
    if !should_skip_hooks && let Err(e) = run_pre_push_hooks(output) {
        if stashed {
            stash_pop_safe(output)?;
        }
        return Err(e);
    }

    let confirmed = confirm_push_if_interactive(args, ahead, upstream, output)?;
    if !confirmed {
        if stashed {
            stash_pop_safe(output)?;
        }
        return Ok(());
    }

    if args.verbose {
        output.progress(&format!("Pushing to origin/{upstream}... "));
    }

    let push_args = build_push_args(upstream, args.force_with_lease);
    let cmd = if args.force_with_lease {
        format!("git push --force-with-lease origin {upstream}")
    } else {
        format!("git push origin {upstream}")
    };
    output.command(&cmd);
    git(&push_args).context("Failed to push changes")?;

    if args.verbose {
        output.success("Pushed");
    }

    summary.pushed = true;

    let should_skip_hooks = args.skip_hooks || get_env_bool("GIT_SEND_SKIP_HOOKS");
    if !should_skip_hooks {
        run_post_push_hooks(output)?;
    }

    Ok(())
}

/// Restores stash if it was created.
fn restore_stash_if_needed(args: &Args, stashed: bool, output: &Output) -> Result<()> {
    if !stashed {
        return Ok(());
    }

    if args.verbose {
        output.progress("Restoring stashed changes... ");
    }

    stash_pop_safe(output)?;

    if args.verbose {
        output.success("Restored");
    }

    Ok(())
}

/// Executes dry run mode.
fn execute_dry_run(
    args: &Args,
    pull_mode: PullMode,
    push_mode: PushMode,
    msg: &str,
    upstream: &str,
    output: &Output,
) {
    output.println("Would execute:");
    output.println("  git add -A");

    if args.amend {
        output.println(&format!("  git commit --amend -m '{msg}'"));
    } else {
        output.println(&format!("  git commit -m '{msg}'"));
    }

    if matches!(pull_mode, PullMode::Enabled) {
        output.println(&format!("  git pull --rebase origin {upstream}"));
    }

    if matches!(push_mode, PushMode::Enabled) {
        if args.force_with_lease {
            output.println(&format!("  git push --force-with-lease origin {upstream}"));
        } else {
            output.println(&format!("  git push origin {upstream}"));
        }
    }
}

/// Executes main workflow
fn execute_workflow(args: &Args, config: &WorkflowConfig, output: &Output) -> Result<()> {
    let mut summary = Summary::default();

    if has_merge_conflicts()? {
        return report_merge_conflicts(output);
    }

    stage_changes_if_needed(args, &mut summary, output)?;
    commit_changes_if_staged(args, config.message, &mut summary, output)?;

    let stashed = stash_changes_if_needed(
        args,
        config.pull_mode,
        config.stash_mode,
        &mut summary,
        output,
    )?;

    pull_if_behind(
        args,
        config.branch,
        config.upstream,
        config.pull_mode,
        &mut summary,
        output,
    )?;

    push_if_ahead(
        args,
        config.branch,
        config.upstream,
        config.push_mode,
        &mut summary,
        stashed,
        output,
    )?;

    restore_stash_if_needed(args, stashed, output)?;

    show_summary(&summary, output);
    Ok(())
}

/// Main execution logic that orchestrates the git operations
pub fn run() -> Result<()> {
    let args = Args::parse();
    let config = Config::load();
    let output = Output::new(args.quiet, args.json);

    if args.abort {
        return handle_abort_flag(&output);
    }

    validate_repository_state(&output)?;

    if let Some(ref msg) = args.message {
        validate_commit_message(msg)?;
    }

    let execution_mode = get_execution_mode(&args);
    let pull_mode = get_pull_mode(&args);
    let push_mode = get_push_mode(&args);
    let stash_mode = get_stash_mode_with_config(&args, &config);

    let branch = get_current_branch()?;
    let upstream = args.upstream.as_deref().unwrap_or(&branch);

    if args.interactive && matches!(execution_mode, ExecutionMode::Execute) {
        show_status(args.verbose, &output)?;
        output.println("");
    }

    show_wip_commits_if_found(&args, execution_mode, &output)?;

    let msg = get_commit_message_with_config(&args, execution_mode, &output, &config)?;
    validate_commit_message(&msg)?;

    suggest_conventional_format_if_needed(&msg, &args, &output);

    if matches!(execution_mode, ExecutionMode::DryRun) {
        execute_dry_run(&args, pull_mode, push_mode, &msg, upstream, &output);
        return Ok(());
    }

    let workflow_config = WorkflowConfig {
        message: &msg,
        branch: &branch,
        upstream,
        pull_mode,
        push_mode,
        stash_mode,
    };

    execute_workflow(&args, &workflow_config, &output)
}