git-workflow 0.9.0

Git guardrails for AI coding agents - safe git workflows with clear state feedback
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
//! `gw cleanup` command - Delete merged branch and return to home
//!
//! Uses GitHub PR information to make smart decisions about branch deletion.

use super::helpers;
use crate::error::{GwError, Result};
use crate::git;
use crate::github::{self, PrState};
use crate::output;
use crate::state::{RepoType, SyncState, WorkingDirState, classify_branch};

/// Execute the `cleanup` command
pub fn run(branch_name: Option<String>, verbose: bool) -> Result<()> {
    // Ensure we're in a git repo
    if !git::is_git_repo() {
        return Err(GwError::NotAGitRepository);
    }

    let repo_type = RepoType::detect()?;
    let home_branch = repo_type.home_branch();
    let current = git::current_branch()?;

    // Determine which branch to delete
    let branch_to_delete = match branch_name {
        Some(name) => name,
        None => {
            if current == home_branch {
                return Err(GwError::AlreadyOnHomeBranch(home_branch.to_string()));
            }
            current.clone()
        }
    };

    println!();
    output::info(&format!(
        "Branch to delete: {}",
        output::bold(&branch_to_delete)
    ));
    output::info(&format!("Home branch: {}", output::bold(home_branch)));

    // Determine if we need to switch branches after cleanup
    let needs_switch = current == branch_to_delete;

    // Safety: check if branch is protected (compile-time typestate enforced)
    let branch = classify_branch(&branch_to_delete, &repo_type);
    let deletable_branch = branch.try_deletable()?;

    // Check if branch exists locally
    let branch_exists = git::branch_exists(&branch_to_delete);
    if !branch_exists {
        output::warn(&format!(
            "Branch '{}' does not exist locally",
            branch_to_delete
        ));
    }

    // Safety check: uncommitted changes (only needed if switching branches)
    if needs_switch {
        let working_dir = WorkingDirState::detect();
        if !working_dir.is_clean() {
            output::error(&format!(
                "You have uncommitted changes ({}).",
                working_dir.description()
            ));
            println!();
            output::action("git add <files> && git commit -m \"...\"  # commit first");
            output::action("gw pause                                  # or park the work as WIP");
            output::action("gw abandon                                # or discard it");
            return Err(GwError::UncommittedChanges);
        }
    }

    // Query PR information from GitHub
    let pr_info = query_pr_info(&branch_to_delete);
    let force_delete_allowed = should_allow_force_delete(&pr_info);

    // Safety check: unpushed commits (skip if PR is merged)
    if branch_exists && !force_delete_allowed {
        check_unpushed_commits(&branch_to_delete)?;
    }

    // Fetch and prune
    output::info("Fetching from origin...");
    git::fetch_prune(verbose)?;
    output::success("Fetched");

    // Detect default remote branch
    let default_remote = git::get_default_remote_branch()?;
    let default_branch = default_remote.strip_prefix("origin/").unwrap_or("main");

    // Switch to home branch first (only if on the branch to delete)
    if needs_switch {
        if !git::branch_exists(home_branch) {
            git::checkout_new_branch(home_branch, &default_remote, verbose)?;
            output::success(&format!(
                "Created and switched to {}",
                output::bold(home_branch)
            ));
        } else {
            git::checkout(home_branch, verbose)?;
            output::success(&format!("Switched to {}", output::bold(home_branch)));
        }

        // Sync home branch with default remote (only after switching).
        // Fast-forward only: if home has diverged from origin we stop rather
        // than silently creating a merge commit.
        helpers::pull_with_output(&default_remote, default_branch, verbose)?;
    }

    // Delete the local branch
    if branch_exists {
        delete_local_branch(
            deletable_branch,
            &branch_to_delete,
            force_delete_allowed,
            verbose,
        );
    }

    // Handle remote branch
    handle_remote_branch(&branch_to_delete, &pr_info, verbose);

    // Check for stashes
    let stash_count = git::stash_count();
    if stash_count > 0 {
        output::warn(&format!(
            "You have {} stash(es). Don't forget about them:",
            stash_count
        ));
        output::action("git stash list");
    }

    if needs_switch {
        output::ready("Cleanup complete", home_branch);
        output::hints(&["gw new feature/your-feature  # Create new branch"]);
    } else {
        output::success(&format!(
            "Cleanup complete (stayed on {})",
            output::bold(&current)
        ));
    }

    Ok(())
}

/// Query PR information from GitHub
fn query_pr_info(branch: &str) -> Option<github::PrInfo> {
    if !github::is_gh_available() {
        output::info("GitHub CLI (gh) not available, skipping PR lookup");
        return None;
    }

    output::info("Checking PR status...");

    match github::get_pr_for_branch(branch) {
        Ok(Some(pr)) => {
            display_pr_info(&pr);
            Some(pr)
        }
        Ok(None) => {
            output::info("No PR found for this branch");
            None
        }
        Err(e) => {
            output::warn(&format!("Could not fetch PR info: {}", e));
            None
        }
    }
}

/// Display PR information
fn display_pr_info(pr: &github::PrInfo) {
    let state_display = match &pr.state {
        PrState::Open => "OPEN".to_string(),
        PrState::Merged { method, .. } => format!("MERGED ({})", method),
        PrState::Closed => "CLOSED".to_string(),
    };

    output::success(&format!(
        "PR #{}: {} [{}]",
        pr.number, pr.title, state_display
    ));
}

/// Determine if force delete should be allowed based on PR state.
///
/// `cleanup` is the "tidy up a merged branch" command, not "throw away local
/// work". So force delete is allowed ONLY when we can positively confirm the PR
/// was merged. Every other situation — open PR, closed-without-merge, no PR
/// found, gh unavailable, or a network failure querying GitHub — is treated as
/// "could not confirm it's safe", and we refuse to force-delete. The caller
/// still attempts a plain `git branch -d`; if that fails the user is told to
/// discard the work explicitly (`git branch -D` or `gw abandon`).
fn should_allow_force_delete(pr_info: &Option<github::PrInfo>) -> bool {
    match pr_info {
        Some(pr) => match &pr.state {
            PrState::Merged { method, .. } => {
                output::info(&format!("PR was {} merged, safe to force delete", method));
                true
            }
            PrState::Open => {
                output::warn("PR is still OPEN, be careful!");
                false
            }
            PrState::Closed => {
                output::warn("PR was closed without merging");
                false
            }
        },
        None => {
            // No merged PR could be confirmed (no PR, gh unavailable, or lookup
            // failed). Not safe to discard local commits automatically.
            output::warn("No merged PR confirmed; will not force-delete unmerged commits");
            false
        }
    }
}

/// Check for unpushed commits
fn check_unpushed_commits(branch: &str) -> Result<()> {
    if git::has_remote_tracking(branch) {
        let sync_state = SyncState::detect(branch)?;
        if sync_state.has_unpushed() {
            let count = sync_state.unpushed_count();
            output::error(&format!(
                "Branch '{}' has {} unpushed commit(s)!",
                branch, count
            ));
            println!();

            // Show unpushed commits
            if let Ok(commits) =
                git::log_commits(&format!("{}@{{upstream}}", branch), branch, false)
            {
                println!("Unpushed commits:");
                for commit in commits.iter().take(5) {
                    println!("  {commit}");
                }
                println!();
            }

            output::action(&format!("git push origin {}  # Push first", branch));
            output::action(&format!(
                "git branch -D {}    # Or force delete (lose commits)",
                branch
            ));
            return Err(GwError::UnpushedCommits(branch.to_string(), count));
        }
    } else {
        // No remote tracking. Be conservative: only claim the work is safe
        // (remote copy exists) when we can positively confirm it.
        match git::remote_branch_exists(branch) {
            Ok(true) => {
                output::info("Branch has no tracking but remote exists (PR probably merged)")
            }
            Ok(false) => {
                output::warn(&format!("Branch '{}' was never pushed to remote", branch));
                output::warn("Commits on this branch will be lost if deleted");
            }
            Err(e) => {
                output::warn(&format!("Could not verify remote for '{}': {}", branch, e));
                output::warn("Commits on this branch may be lost if deleted");
            }
        }
    }
    Ok(())
}

/// Delete local branch, using force delete if allowed
fn delete_local_branch(
    deletable_branch: crate::state::Branch<crate::state::Deletable>,
    branch_name: &str,
    force_allowed: bool,
    verbose: bool,
) {
    match deletable_branch.delete(verbose) {
        Ok(()) => {
            output::success(&format!(
                "Deleted local branch {}",
                output::bold(branch_name)
            ));
        }
        Err(_) => {
            if force_allowed {
                // PR was merged, safe to force delete
                output::info(
                    "Branch not fully merged locally, but PR was merged. Force deleting...",
                );
                if let Err(e) = git::force_delete_branch(branch_name, verbose) {
                    output::warn(&format!("Force delete failed: {}", e));
                } else {
                    output::success(&format!(
                        "Force deleted local branch {}",
                        output::bold(branch_name)
                    ));
                }
            } else {
                output::warn("Branch not fully merged. Use -D to force delete:");
                output::action(&format!("git branch -D {}", branch_name));
            }
        }
    }
}

/// Whether deleting `branch`'s remote would orphan open child PRs.
///
/// GitHub closes a PR when its base branch is deleted, so if any open PR still
/// targets `branch` as its base we must NOT delete it — warn and return true to
/// skip the deletion. On a query error we conservatively skip too, rather than
/// risk silently closing a child PR.
fn remote_deletion_blocked_by_children(branch: &str) -> bool {
    match github::open_prs_with_base(branch) {
        Ok(children) if !children.is_empty() => {
            output::warn(&format!(
                "Not deleting origin/{branch}: {} open PR(s) still target it as base:",
                children.len()
            ));
            for child in &children {
                output::warn(&format!("  #{} ({})", child.number, child.head_branch));
            }
            output::action(
                "gw sync   # run on each child to restack onto main, then re-run gw cleanup",
            );
            true
        }
        Ok(_) => false,
        Err(e) => {
            output::warn(&format!("Could not check for dependent PRs: {e}"));
            output::warn(&format!(
                "Not deleting origin/{branch} to avoid closing a child PR."
            ));
            output::action(&format!(
                "git push origin --delete {branch}  # if you're sure nothing depends on it"
            ));
            true
        }
    }
}

/// Handle remote branch deletion
fn handle_remote_branch(branch: &str, pr_info: &Option<github::PrInfo>, verbose: bool) {
    let remote_exists = match git::remote_branch_exists(branch) {
        Ok(v) => v,
        Err(e) => {
            // Couldn't reach the remote — don't claim it was "already deleted".
            output::warn(&format!(
                "Could not verify remote branch origin/{branch}: {e}"
            ));
            output::action(&format!(
                "git push origin --delete {branch}  # if it still exists"
            ));
            return;
        }
    };

    if !remote_exists {
        // Remote branch already deleted (GitHub auto-delete after merge)
        if let Some(pr) = pr_info {
            if matches!(pr.state, PrState::Merged { .. }) {
                output::success("Remote branch already deleted by GitHub");
            }
        }
        return;
    }

    // Remote branch still exists
    match pr_info {
        Some(pr) if matches!(pr.state, PrState::Merged { .. }) => {
            // Don't delete a branch that open PRs still use as their base —
            // GitHub would close those child PRs. Skip the remote deletion
            // (local cleanup already happened) and let the user restack first.
            if remote_deletion_blocked_by_children(branch) {
                return;
            }
            // PR merged but remote branch exists - delete it
            output::info("PR merged, deleting remote branch...");
            match github::delete_remote_branch(branch) {
                Ok(()) => {
                    output::success(&format!(
                        "Deleted remote branch origin/{}",
                        output::bold(branch)
                    ));
                }
                Err(e) => {
                    output::warn(&format!("Failed to delete remote branch: {}", e));
                    output::action(&format!("git push origin --delete {}", branch));
                }
            }
        }
        Some(pr) if matches!(pr.state, PrState::Open) => {
            output::warn(&format!(
                "Remote branch exists and PR #{} is still open",
                pr.number
            ));
            output::action(&format!("gh pr view {}", pr.number));
        }
        _ => {
            output::warn(&format!("Remote branch still exists: origin/{}", branch));
            if verbose {
                output::action(&format!("git push origin --delete {}", branch));
            }
        }
    }
}