gitflow-core 1.3.0

gf 核心库:Platform trait 抽象、跨平台适配器与 toon 输出。Core library: platform abstraction, adapters & toon output.
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
//! PR cleanup domain types and service.
//!
//! Provides argument and result types for the `gf pr cleanup` command,
//! plus the [`CleanupService`] that coordinates branch and worktree cleanup.

use serde::{Deserialize, Serialize};

use crate::{pr::PrData, types::State};

/// Arguments for the `gf pr cleanup` command.
///
/// Supports cleanup by PR numbers, by status (`--merged`/`--closed`),
/// or a combination. The `numbers` field is mutually exclusive with
/// `merged`/`closed` flags.
#[derive(Debug, Clone)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "Configuration type with boolean flags"
)]
pub struct CleanupArgs {
    /// PR numbers to clean up (mutually exclusive with `merged`/`closed`).
    pub numbers: Vec<u64>,
    /// Clean up all merged PRs.
    pub merged: bool,
    /// Clean up all closed PRs.
    pub closed: bool,
    /// Remove the specified worktree path after cleanup.
    pub worktree: Option<String>,
    /// Delete remote branches.
    pub remote: bool,
    /// Delete local branches.
    pub local: bool,
    /// Force cleanup of unmerged branches.
    pub force: bool,
    /// Show what would be done without actually doing it.
    pub dry_run: bool,
    /// Skip interactive confirmation.
    pub yes: bool,
}

/// Result of cleaning up a single PR.
///
/// Tracks which operations succeeded and any errors encountered.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(
    clippy::struct_excessive_bools,
    reason = "Result type tracking multiple operation outcomes"
)]
pub struct CleanupResult {
    /// PR number.
    pub pr_number: u64,
    /// PR title.
    pub pr_title: String,
    /// Branch name that was cleaned up.
    pub branch: String,
    /// Whether the remote branch was deleted.
    pub remote_deleted: bool,
    /// Whether the local branch was deleted.
    pub local_deleted: bool,
    /// Whether the worktree was exited.
    pub worktree_exited: bool,
    /// Whether the worktree directory was removed.
    pub worktree_removed: bool,
    /// Whether this was a dry-run (no actual deletions).
    pub dry_run: bool,
    /// Error message if cleanup failed for this PR.
    pub error: Option<String>,
}

/// Check if a branch name matches common protected branch patterns.
///
/// Protected branches include: `main`, `master`, `develop`, and `release/*`.
///
/// This is a local check — Phase 2 may add remote branch protection queries.
#[must_use]
pub fn is_protected_branch(branch: &str) -> bool {
    matches!(branch, "main" | "master" | "develop") || branch.starts_with("release/")
}

/// Perform safety checks before cleaning up a PR.
///
/// Checks:
/// 1. PR status (must be merged or closed, unless `force` is true)
/// 2. Branch protection (hard reject — cannot be overridden)
/// 3. Current branch (cannot delete currently checked-out branch)
///
/// # Errors
///
/// Returns an error if any safety check fails.
pub fn check_safety(pr: &PrData, current_branch: &str, force: bool) -> crate::Result<()> {
    // 1. Check PR status
    if !force && pr.state != State::Closed {
        return Err(crate::CoreError::App(format!(
            "PR #{} 尚未合并或关闭。使用 --force 强制清理。",
            pr.number
        )));
    }

    // 2. Check protected branch (hard reject)
    if is_protected_branch(&pr.head_branch) {
        return Err(crate::CoreError::App(format!(
            "分支 '{}' 受保护,拒绝删除",
            pr.head_branch
        )));
    }

    // 3. Check current branch (hard reject)
    if pr.head_branch == current_branch {
        return Err(crate::CoreError::App(format!(
            "无法删除当前检出的分支 '{}'",
            pr.head_branch
        )));
    }

    Ok(())
}

/// Service for coordinating PR cleanup operations.
///
/// Orchestrates safety checks, git operations, and worktree handling.
#[derive(Debug)]
pub struct CleanupService;

impl CleanupService {
    /// Clean up a single PR's branches and optionally its worktree.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Safety checks fail
    /// - Git operations fail
    /// - Worktree operations fail
    pub async fn cleanup_single_pr(
        provider: &dyn crate::pr::PrProvider,
        pr_number: u64,
        args: &CleanupArgs,
    ) -> crate::Result<CleanupResult> {
        // 1. Fetch PR data
        let pr = provider.view(pr_number).await?;

        // 2. Get current branch
        let current_branch = get_current_branch().await?;

        // 3. Safety checks
        check_safety(&pr, &current_branch, args.force)?;

        // 4. Delete remote branch (if requested and not dry-run)
        let mut remote_deleted = false;
        if args.remote && !args.dry_run {
            if let Err(e) = crate::git_ops::delete_remote_branch(&pr.head_branch).await {
                // Log error but continue (branch might not exist)
                tracing::warn!("Failed to delete remote branch: {}", e);
            } else {
                remote_deleted = true;
            }
        }

        // 5. Delete local branch (if requested and not dry-run)
        let mut local_deleted = false;
        if args.local && !args.dry_run {
            crate::git_ops::delete_local_branch(&pr.head_branch, args.force).await?;
            local_deleted = true;
        }

        // 6. Handle worktree
        let mut worktree_exited = false;
        let mut worktree_removed = false;

        if crate::git_ops::is_in_worktree().await? && !args.dry_run {
            crate::git_ops::exit_worktree().await?;
            worktree_exited = true;

            if let Some(ref worktree_path) = args.worktree {
                crate::git_ops::remove_worktree(worktree_path).await?;
                worktree_removed = true;
            }
        }

        Ok(CleanupResult {
            pr_number: pr.number,
            pr_title: pr.title,
            branch: pr.head_branch,
            remote_deleted,
            local_deleted,
            worktree_exited,
            worktree_removed,
            dry_run: args.dry_run,
            error: None,
        })
    }

    /// Clean up multiple PRs by number.
    ///
    /// Continues on individual failures and collects all results.
    ///
    /// # Errors
    ///
    /// Returns an error only if the provider call itself fails.
    /// Individual PR cleanup failures are captured in the results.
    pub async fn cleanup(
        provider: &dyn crate::pr::PrProvider,
        args: &CleanupArgs,
    ) -> crate::Result<Vec<CleanupResult>> {
        let mut results = Vec::new();

        for &pr_number in &args.numbers {
            match Self::cleanup_single_pr(provider, pr_number, args).await {
                Ok(result) => results.push(result),
                Err(e) => {
                    // Capture error in result instead of failing the whole batch
                    results.push(CleanupResult {
                        pr_number,
                        pr_title: String::new(),
                        branch: String::new(),
                        remote_deleted: false,
                        local_deleted: false,
                        worktree_exited: false,
                        worktree_removed: false,
                        dry_run: args.dry_run,
                        error: Some(e.to_string()),
                    });
                }
            }
        }

        Ok(results)
    }

    /// Clean up all merged PRs.
    ///
    /// # Errors
    ///
    /// Returns an error if listing PRs fails.
    pub async fn cleanup_merged(
        provider: &dyn crate::pr::PrProvider,
        args: &CleanupArgs,
    ) -> crate::Result<Vec<CleanupResult>> {
        let prs = provider
            .list(crate::pr::ListPrArgs {
                state: Some(State::Closed),
                limit: None,
            })
            .await?;

        // Filter to only merged PRs (state == Closed includes merged)
        let merged_prs: Vec<_> = prs
            .into_iter()
            .filter(|pr| pr.state == State::Closed)
            .collect();

        let mut results = Vec::new();
        for pr in merged_prs {
            let mut pr_args = args.clone();
            pr_args.numbers = vec![pr.number];

            match Self::cleanup_single_pr(provider, pr.number, &pr_args).await {
                Ok(result) => results.push(result),
                Err(e) => {
                    results.push(CleanupResult {
                        pr_number: pr.number,
                        pr_title: pr.title,
                        branch: pr.head_branch,
                        remote_deleted: false,
                        local_deleted: false,
                        worktree_exited: false,
                        worktree_removed: false,
                        dry_run: args.dry_run,
                        error: Some(e.to_string()),
                    });
                }
            }
        }

        Ok(results)
    }

    /// Clean up all closed PRs.
    ///
    /// # Errors
    ///
    /// Returns an error if listing PRs fails.
    pub async fn cleanup_closed(
        provider: &dyn crate::pr::PrProvider,
        args: &CleanupArgs,
    ) -> crate::Result<Vec<CleanupResult>> {
        // Same as cleanup_merged for now (both use state == Closed)
        Self::cleanup_merged(provider, args).await
    }
}

/// Get the current git branch name.
///
/// # Errors
///
/// Returns an error if the git command fails or HEAD is detached.
async fn get_current_branch() -> crate::Result<String> {
    let output = tokio::process::Command::new("git")
        .args(["branch", "--show-current"])
        .output()
        .await
        .map_err(|e| crate::CoreError::App(format!("Failed to get current branch: {e}")))?;

    if !output.status.success() {
        return Err(crate::CoreError::App(
            "Failed to get current branch".to_string(),
        ));
    }

    let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if branch.is_empty() {
        return Err(crate::CoreError::App("HEAD is detached".to_string()));
    }

    Ok(branch)
}

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

    #[test]
    fn test_should_create_cleanup_args_with_defaults() {
        let args = CleanupArgs {
            numbers: vec![172],
            merged: false,
            closed: false,
            worktree: None,
            remote: true,
            local: true,
            force: false,
            dry_run: false,
            yes: false,
        };
        assert_eq!(args.numbers, vec![172]);
        assert!(args.remote);
        assert!(args.local);
        assert!(!args.force);
    }

    #[test]
    fn test_should_create_cleanup_args_for_batch() {
        let args = CleanupArgs {
            numbers: vec![172, 173, 174],
            merged: false,
            closed: false,
            worktree: None,
            remote: true,
            local: true,
            force: false,
            dry_run: false,
            yes: false,
        };
        assert_eq!(args.numbers.len(), 3);
    }

    #[test]
    fn test_should_create_cleanup_args_for_merged() {
        let args = CleanupArgs {
            numbers: vec![],
            merged: true,
            closed: false,
            worktree: None,
            remote: true,
            local: true,
            force: false,
            dry_run: false,
            yes: false,
        };
        assert!(args.merged);
        assert!(!args.closed);
    }

    #[test]
    fn test_should_serialize_cleanup_result() {
        let result = CleanupResult {
            pr_number: 172,
            pr_title: "Add feature".to_string(),
            branch: "feature/x".to_string(),
            remote_deleted: true,
            local_deleted: true,
            worktree_exited: false,
            worktree_removed: false,
            dry_run: false,
            error: None,
        };
        let json = serde_json::to_string(&result).expect("serialize");
        assert!(json.contains("\"prNumber\":172"));
        assert!(json.contains("\"remoteDeleted\":true"));
    }

    #[test]
    fn test_should_serialize_cleanup_result_with_error() {
        let result = CleanupResult {
            pr_number: 175,
            pr_title: "Protected branch".to_string(),
            branch: "main".to_string(),
            remote_deleted: false,
            local_deleted: false,
            worktree_exited: false,
            worktree_removed: false,
            dry_run: false,
            error: Some("Branch 'main' is protected".to_string()),
        };
        let json = serde_json::to_string(&result).expect("serialize");
        assert!(json.contains("\"error\":"));
        assert!(json.contains("protected"));
    }

    #[test]
    fn test_should_identify_main_as_protected() {
        assert!(is_protected_branch("main"));
    }

    #[test]
    fn test_should_identify_master_as_protected() {
        assert!(is_protected_branch("master"));
    }

    #[test]
    fn test_should_identify_develop_as_protected() {
        assert!(is_protected_branch("develop"));
    }

    #[test]
    fn test_should_identify_release_branches_as_protected() {
        assert!(is_protected_branch("release/1.0"));
        assert!(is_protected_branch("release/v2.0.0"));
    }

    #[test]
    fn test_should_not_identify_feature_branch_as_protected() {
        assert!(!is_protected_branch("feature/x"));
        assert!(!is_protected_branch("bugfix/123"));
    }

    #[test]
    fn test_should_allow_cleanup_of_merged_pr() {
        let pr = PrData {
            number: 172,
            title: "Add feature".to_string(),
            body: None,
            state: State::Closed,
            draft: false,
            author: crate::types::UserSummary {
                login: "alice".to_string(),
                id: "1".to_string(),
            },
            base_branch: "main".to_string(),
            head_branch: "feature/x".to_string(),
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            url: "https://github.com/test/repo/pull/172".to_string(),
        };
        let result = check_safety(&pr, "main", false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_should_refuse_to_delete_protected_branch() {
        let pr = PrData {
            number: 172,
            title: "Update main".to_string(),
            body: None,
            state: State::Closed,
            draft: false,
            author: crate::types::UserSummary {
                login: "alice".to_string(),
                id: "1".to_string(),
            },
            base_branch: "main".to_string(),
            head_branch: "main".to_string(),
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            url: "https://github.com/test/repo/pull/172".to_string(),
        };
        let result = check_safety(&pr, "develop", false);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("受保护"));
    }

    #[test]
    fn test_should_refuse_to_delete_current_branch() {
        let pr = PrData {
            number: 172,
            title: "Add feature".to_string(),
            body: None,
            state: State::Closed,
            draft: false,
            author: crate::types::UserSummary {
                login: "alice".to_string(),
                id: "1".to_string(),
            },
            base_branch: "main".to_string(),
            head_branch: "feature/x".to_string(),
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            url: "https://github.com/test/repo/pull/172".to_string(),
        };
        let result = check_safety(&pr, "feature/x", false);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("当前检出"));
    }

    #[test]
    fn test_should_require_merged_or_closed_state() {
        let pr = PrData {
            number: 172,
            title: "Add feature".to_string(),
            body: None,
            state: State::Open,
            draft: false,
            author: crate::types::UserSummary {
                login: "alice".to_string(),
                id: "1".to_string(),
            },
            base_branch: "main".to_string(),
            head_branch: "feature/x".to_string(),
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            url: "https://github.com/test/repo/pull/172".to_string(),
        };
        let result = check_safety(&pr, "main", false);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("尚未合并或关闭"));
    }

    #[test]
    fn test_should_allow_unmerged_pr_with_force() {
        let pr = PrData {
            number: 172,
            title: "Add feature".to_string(),
            body: None,
            state: State::Open,
            draft: false,
            author: crate::types::UserSummary {
                login: "alice".to_string(),
                id: "1".to_string(),
            },
            base_branch: "main".to_string(),
            head_branch: "feature/x".to_string(),
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            url: "https://github.com/test/repo/pull/172".to_string(),
        };
        let result = check_safety(&pr, "main", true);
        assert!(result.is_ok());
    }
}