Skip to main content

workon/
pr.rs

1//! Pull request support for creating worktrees from PR references.
2//!
3//! This module enables creating worktrees directly from pull request references,
4//! making it easy to review PRs in isolated worktrees.
5//!
6//! ## PR Reference Parsing
7//!
8//! Supports multiple PR reference formats:
9//! - `#123` - GitHub shorthand (most common)
10//! - `pr#123` or `pr-123` - Explicit PR references
11//! - `https://github.com/owner/repo/pull/123` - Full GitHub PR URL
12//! - `origin/pull/123/head` - Direct remote ref (less common)
13//!
14//! Parsing is lenient - if it looks like a PR reference, we'll try to extract the number.
15//!
16//! ## Smart Routing
17//!
18//! The CLI's smart routing (in main.rs) automatically detects PR references:
19//! ```bash
20//! git workon #123        # Routes to `new` command with PR reference
21//! git workon pr#123      # Same - creates PR worktree
22//! git workon feature     # Routes to `find` command (not a PR)
23//! ```
24//!
25//! ## Remote Detection Algorithm
26//!
27//! To fetch PRs, we need to determine which remote to use. The detection strategy:
28//! 1. Check for `upstream` remote (common in fork workflows)
29//! 2. Fall back to `origin` remote (most common)
30//! 3. Use first available remote (rare, but handles edge cases)
31//!
32//! This handles both direct repository workflows and fork-based workflows.
33//!
34//! ## Auto-Fetch Strategy
35//!
36//! PR branches are fetched automatically using gh CLI metadata:
37//! ```text
38//! git fetch <remote> +refs/heads/{branch}:refs/remotes/<remote>/{branch}
39//! ```
40//!
41//! Where `{branch}` is the actual branch name from the PR (obtained via gh CLI).
42//! The `+` forces the fetch even if not fast-forward, ensuring we always get the latest PR state.
43//!
44//! For fork PRs, a fork remote is automatically added and the branch is fetched from it.
45//! For non-fork PRs, the branch is fetched from the detected remote (origin/upstream).
46//!
47//! ## Worktree Naming
48//!
49//! Worktree names are generated from `workon.prFormat` config (default: `pr-{number}`):
50//! - `pr-123` (default format)
51//! - `#123` (if configured with `#{number}`)
52//! - `pull-123` (if configured with `pull-{number}`)
53//!
54//! The format must contain `{number}` placeholder.
55//!
56//! ## Example Usage
57//!
58//! ```bash
59//! # Create worktree for PR #123 (auto-detects remote, auto-fetches)
60//! git workon #123
61//!
62//! # Explicit PR reference
63//! git workon new pr#456
64//!
65//! # From GitHub URL
66//! git workon new https://github.com/user/repo/pull/789
67//!
68//! # Configure custom naming
69//! git config workon.prFormat "review-{number}"
70//! git workon #123  # Creates worktree named "review-123"
71//! ```
72//!
73//! ## gh CLI Integration
74//!
75//! PR support integrates with gh CLI for rich metadata:
76//! - **Format placeholders**: {number}, {title}, {author}, {branch}
77//! - **Fork support**: Auto-adds fork remotes and fetches fork branches
78//! - **Metadata**: Fetches PR title, author, branch names, and state
79//! - **Validation**: Checks PR exists before creating worktree
80
81use git2::{FetchOptions, Repository};
82use log::debug;
83
84use crate::{
85    error::{PrError, Result},
86    get_remote_callbacks,
87};
88
89/// A parsed pull request reference from user input.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct PullRequest {
92    /// The PR number extracted from the reference string.
93    pub number: u32,
94    /// Optional remote name if the reference included one (e.g. `origin/pull/123/head`).
95    pub remote: Option<String>,
96}
97
98/// PR metadata fetched from the `gh` CLI.
99#[derive(Debug, Clone)]
100pub struct PrMetadata {
101    /// PR number.
102    pub number: u32,
103    /// PR title.
104    pub title: String,
105    /// GitHub login of the PR author.
106    pub author: String,
107    /// Name of the branch that the PR was created from.
108    pub head_ref: String,
109    /// Name of the branch the PR targets.
110    pub base_ref: String,
111    /// True if the PR comes from a forked repository.
112    pub is_fork: bool,
113    /// GitHub login of the fork owner, if this is a fork PR.
114    pub fork_owner: Option<String>,
115    /// Clone URL of the fork repository, if this is a fork PR.
116    pub fork_url: Option<String>,
117}
118
119/// Parse a PR reference from user input
120///
121/// Supported formats:
122/// - `#123` - GitHub shorthand
123/// - `pr#123` or `pr-123` - Explicit PR references
124/// - `https://github.com/owner/repo/pull/123` - GitHub PR URL
125/// - `origin/pull/123/head` - Direct remote ref
126///
127/// Returns `Ok(None)` if the input is not a PR reference.
128/// Returns `Ok(Some(PullRequest))` if successfully parsed.
129/// Returns `Err` if the input looks like a PR reference but is malformed.
130pub fn parse_pr_reference(input: &str) -> Result<Option<PullRequest>> {
131    // Try #123 format
132    if let Some(num_str) = input.strip_prefix('#') {
133        return parse_number(num_str, input).map(|num| {
134            Some(PullRequest {
135                number: num,
136                remote: None,
137            })
138        });
139    }
140
141    // Try pr#123 format
142    if let Some(num_str) = input.strip_prefix("pr#") {
143        return parse_number(num_str, input).map(|num| {
144            Some(PullRequest {
145                number: num,
146                remote: None,
147            })
148        });
149    }
150
151    // Try pr-123 format
152    if let Some(num_str) = input.strip_prefix("pr-") {
153        return parse_number(num_str, input).map(|num| {
154            Some(PullRequest {
155                number: num,
156                remote: None,
157            })
158        });
159    }
160
161    // Try GitHub URL: https://github.com/owner/repo/pull/123
162    if input.contains("github.com") && input.contains("/pull/") {
163        return parse_github_url(input);
164    }
165
166    // Try remote ref format: origin/pull/123/head
167    if input.contains("/pull/") && input.ends_with("/head") {
168        return parse_remote_ref(input);
169    }
170
171    // Not a PR reference
172    Ok(None)
173}
174
175/// Helper to parse a number string
176fn parse_number(num_str: &str, original_input: &str) -> Result<u32> {
177    num_str.parse::<u32>().map_err(|_| {
178        PrError::InvalidReference {
179            input: original_input.to_string(),
180        }
181        .into()
182    })
183}
184
185/// Parse GitHub PR URL
186fn parse_github_url(url: &str) -> Result<Option<PullRequest>> {
187    // Extract the PR number from URL like: https://github.com/owner/repo/pull/123
188    let parts: Vec<&str> = url.split('/').collect();
189
190    // Find "pull" in the path and get the number after it
191    for (i, &part) in parts.iter().enumerate() {
192        if part == "pull" && i + 1 < parts.len() {
193            let num_str = parts[i + 1];
194            let number = parse_number(num_str, url)?;
195            return Ok(Some(PullRequest {
196                number,
197                remote: None,
198            }));
199        }
200    }
201
202    Err(PrError::InvalidReference {
203        input: url.to_string(),
204    }
205    .into())
206}
207
208/// Parse remote ref format: origin/pull/123/head
209fn parse_remote_ref(ref_str: &str) -> Result<Option<PullRequest>> {
210    // Format: remote/pull/number/head
211    let parts: Vec<&str> = ref_str.split('/').collect();
212
213    if parts.len() >= 4 && parts[parts.len() - 3] == "pull" && parts[parts.len() - 1] == "head" {
214        let num_str = parts[parts.len() - 2];
215        let number = parse_number(num_str, ref_str)?;
216        return Ok(Some(PullRequest {
217            number,
218            remote: None,
219        }));
220    }
221
222    Err(PrError::InvalidReference {
223        input: ref_str.to_string(),
224    }
225    .into())
226}
227
228/// Return `Ok(())` if the `gh` CLI is installed and reachable in `PATH`.
229///
230/// Returns [`PrError::GhNotInstalled`] if `gh` cannot be executed.
231pub fn check_gh_available() -> Result<()> {
232    std::process::Command::new("gh")
233        .arg("--version")
234        .output()
235        .map_err(|_| PrError::GhNotInstalled)?;
236    Ok(())
237}
238
239/// Fetch PR metadata for `pr_number` using the `gh` CLI.
240///
241/// Runs `gh pr view <pr_number> --json ...` and parses the JSON output.
242/// Requires `gh` to be authenticated (`gh auth login`).
243pub fn fetch_pr_metadata(pr_number: u32) -> Result<PrMetadata> {
244    // Ensure gh is available
245    check_gh_available()?;
246
247    // Fetch PR metadata with single gh command
248    let output = std::process::Command::new("gh")
249        .args([
250            "pr",
251            "view",
252            &pr_number.to_string(),
253            "--json",
254            "number,title,author,headRefName,baseRefName,isCrossRepository,headRepository",
255        ])
256        .output()
257        .map_err(|e| PrError::GhFetchFailed {
258            message: e.to_string(),
259        })?;
260
261    if !output.status.success() {
262        let stderr = String::from_utf8_lossy(&output.stderr);
263        return Err(PrError::GhFetchFailed {
264            message: stderr.to_string(),
265        }
266        .into());
267    }
268
269    // Parse JSON response
270    let json_str = String::from_utf8_lossy(&output.stdout);
271    let json: serde_json::Value =
272        serde_json::from_str(&json_str).map_err(|e| PrError::GhJsonParseFailed {
273            message: e.to_string(),
274        })?;
275
276    // Extract fields
277    let number = json["number"]
278        .as_u64()
279        .ok_or_else(|| PrError::GhJsonParseFailed {
280            message: "Missing 'number' field".to_string(),
281        })? as u32;
282
283    let title = json["title"]
284        .as_str()
285        .ok_or_else(|| PrError::GhJsonParseFailed {
286            message: "Missing 'title' field".to_string(),
287        })?
288        .to_string();
289
290    let author = json["author"]["login"]
291        .as_str()
292        .ok_or_else(|| PrError::GhJsonParseFailed {
293            message: "Missing 'author.login' field".to_string(),
294        })?
295        .to_string();
296
297    let head_ref = json["headRefName"]
298        .as_str()
299        .ok_or_else(|| PrError::GhJsonParseFailed {
300            message: "Missing 'headRefName' field".to_string(),
301        })?
302        .to_string();
303
304    let base_ref = json["baseRefName"]
305        .as_str()
306        .ok_or_else(|| PrError::GhJsonParseFailed {
307            message: "Missing 'baseRefName' field".to_string(),
308        })?
309        .to_string();
310
311    let is_fork = json["isCrossRepository"].as_bool().unwrap_or(false);
312
313    let (fork_owner, fork_url) = if is_fork {
314        let owner = json["headRepository"]["owner"]["login"]
315            .as_str()
316            .ok_or(PrError::MissingForkOwner)?
317            .to_string();
318        let url = json["headRepository"]["url"]
319            .as_str()
320            .map(|s| s.to_string());
321        (Some(owner), url)
322    } else {
323        (None, None)
324    };
325
326    Ok(PrMetadata {
327        number,
328        title,
329        author,
330        head_ref,
331        base_ref,
332        is_fork,
333        fork_owner,
334        fork_url,
335    })
336}
337
338/// Look up the merged PR for `branch`, if any, using the `gh` CLI.
339///
340/// Runs `gh pr list --head <branch> --state merged --json number,mergedAt --limit 1`.
341/// Matching is by branch name only, so a same-named branch from a fork is a
342/// false match; callers that care about this should already have ruled out
343/// forks another way.
344///
345/// Returns `Ok(None)` if the branch never had a PR merged under that name.
346/// Does not call [`check_gh_available`] itself — callers that intend to
347/// silently degrade when `gh` is unavailable should check once up front
348/// rather than pay for it on every branch.
349pub fn find_merged_pr(branch: &str) -> Result<Option<u32>> {
350    let output = std::process::Command::new("gh")
351        .args([
352            "pr",
353            "list",
354            "--head",
355            branch,
356            "--state",
357            "merged",
358            "--json",
359            "number,mergedAt",
360            "--limit",
361            "1",
362        ])
363        .output()
364        .map_err(|e| PrError::GhFetchFailed {
365            message: e.to_string(),
366        })?;
367
368    if !output.status.success() {
369        let stderr = String::from_utf8_lossy(&output.stderr);
370        return Err(PrError::GhFetchFailed {
371            message: stderr.to_string(),
372        }
373        .into());
374    }
375
376    let json_str = String::from_utf8_lossy(&output.stdout);
377    Ok(parse_merged_pr(&json_str))
378}
379
380/// Extract a merged PR number from `gh pr list --json number,mergedAt`'s output.
381///
382/// Treats any shape mismatch as "no merged PR" rather than an error: an empty array
383/// (never had a PR), missing/non-numeric `number`, a non-array payload, or malformed
384/// JSON. [`find_merged_pr`] already treats a `None` here as a degrade-quietly case, so
385/// there is no separate error path to preserve for these.
386fn parse_merged_pr(json: &str) -> Option<u32> {
387    let json: serde_json::Value = serde_json::from_str(json).ok()?;
388    json.as_array()?
389        .first()?
390        .get("number")?
391        .as_u64()
392        .map(|n| n as u32)
393}
394
395/// Sanitize a string for use in branch/worktree names
396fn sanitize_for_branch_name(s: &str) -> String {
397    let sanitized = s
398        .chars()
399        .map(|c| match c {
400            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => c,
401            ' ' | '/' => '-',
402            _ => '-',
403        })
404        .collect::<String>()
405        .to_lowercase();
406
407    // Collapse multiple dashes into single dash
408    let mut result = String::new();
409    let mut last_was_dash = false;
410    for c in sanitized.chars() {
411        if c == '-' {
412            if !last_was_dash {
413                result.push(c);
414            }
415            last_was_dash = true;
416        } else {
417            result.push(c);
418            last_was_dash = false;
419        }
420    }
421
422    result.trim_matches(|c| c == '-' || c == '_').to_string()
423}
424
425/// Expand all placeholders in `format` using `metadata`.
426///
427/// Supported placeholders: `{number}`, `{title}`, `{author}`, `{branch}`.
428/// Title, author, and branch values are sanitized for use in branch/directory names.
429pub fn format_pr_name_with_metadata(format: &str, metadata: &PrMetadata) -> String {
430    format
431        .replace("{number}", &metadata.number.to_string())
432        .replace("{title}", &sanitize_for_branch_name(&metadata.title))
433        .replace("{author}", &sanitize_for_branch_name(&metadata.author))
434        .replace("{branch}", &sanitize_for_branch_name(&metadata.head_ref))
435}
436
437/// Check if a string looks like a PR reference
438///
439/// This is a quick check used for routing decisions.
440pub fn is_pr_reference(input: &str) -> bool {
441    parse_pr_reference(input).ok().flatten().is_some()
442}
443
444/// Priority tier for the shared `upstream → origin → others` remote precedence.
445///
446/// The single encoding of the precedence ADR-024 prescribes for every remote
447/// decision: [`preferred_remote_order`] sorts by it, and
448/// `resolve_remote_tracking` (worktree.rs) uses equal tiers to detect
449/// ambiguity. Lower is more preferred; all non-special remotes share a tier.
450pub fn remote_priority(remote: &str) -> usize {
451    match remote {
452        "upstream" => 0,
453        "origin" => 1,
454        _ => 2,
455    }
456}
457
458/// Returns remotes in preferred order: upstream first, then origin, then all
459/// others in configuration order (the sort is stable).
460pub fn preferred_remote_order(repo: &Repository) -> Vec<String> {
461    let Ok(remotes) = repo.remotes() else {
462        return vec![];
463    };
464    let mut all: Vec<String> = remotes
465        .iter()
466        .flatten()
467        .flatten()
468        .map(str::to_string)
469        .collect();
470    all.sort_by_key(|r| remote_priority(r));
471    all
472}
473
474/// True if any of the repository's remotes point at `github.com`.
475///
476/// `gh` can only resolve a PR against a GitHub remote, so callers use this to skip a
477/// lookup that is guaranteed to fail (e.g. prune's PR-merged signal). Handles both URL
478/// forms (`https://github.com/...` and `git@github.com:...`); a remote whose URL fails
479/// to parse is treated as non-GitHub rather than an error.
480pub fn has_github_remote(repo: &Repository) -> bool {
481    let Ok(remotes) = repo.remotes() else {
482        return false;
483    };
484    remotes.iter().flatten().flatten().any(|name| {
485        repo.find_remote(name)
486            .ok()
487            .and_then(|r| r.url().ok().map(str::to_string))
488            .and_then(|url| crate::ssh_config::extract_host_from_url(&url))
489            .is_some_and(|host| host.eq_ignore_ascii_case("github.com"))
490    })
491}
492
493/// Select which remote to use for fetching PR refs.
494///
495/// Priority: `upstream` → `origin` → first available remote.
496/// Returns [`PrError::NoRemoteConfigured`] if the repository has no remotes.
497pub fn detect_pr_remote(repo: &Repository) -> Result<String> {
498    preferred_remote_order(repo)
499        .into_iter()
500        .next()
501        .ok_or_else(|| PrError::NoRemoteConfigured.into())
502}
503
504/// Ensure a remote for a fork PR exists, then return its name.
505///
506/// For non-fork PRs this is equivalent to [`detect_pr_remote`].
507/// For fork PRs, a remote named `pr-{number}-fork` is added if it doesn't
508/// already exist, pointing at the fork's clone URL.
509pub fn setup_fork_remote(repo: &Repository, metadata: &PrMetadata) -> Result<String> {
510    if !metadata.is_fork {
511        // Not a fork - use regular remote
512        return detect_pr_remote(repo);
513    }
514
515    // Fork PR - need to add fork remote
516    let _fork_owner = metadata
517        .fork_owner
518        .as_ref()
519        .ok_or(PrError::MissingForkOwner)?;
520
521    let fork_url = metadata
522        .fork_url
523        .as_ref()
524        .ok_or(PrError::MissingForkOwner)?;
525
526    // Check if fork remote already exists
527    let fork_remote_name = format!("pr-{}-fork", metadata.number);
528
529    if repo.find_remote(&fork_remote_name).is_ok() {
530        debug!("Fork remote {} already exists", fork_remote_name);
531        return Ok(fork_remote_name);
532    }
533
534    // Add fork as remote
535    debug!("Adding fork remote: {} -> {}", fork_remote_name, fork_url);
536    repo.remote(&fork_remote_name, fork_url)
537        .map_err(|e| PrError::FetchFailed {
538            remote: fork_remote_name.clone(),
539            message: format!("Failed to add fork remote: {}", e),
540        })?;
541
542    Ok(fork_remote_name)
543}
544
545/// Fetch `branch` from `remote_name`, making it available as
546/// `refs/remotes/{remote_name}/{branch}`.
547///
548/// This is used for both fork and non-fork PRs to fetch the PR's head branch
549/// identified via `gh` CLI metadata. If the ref already exists locally the
550/// fetch is skipped.
551pub fn fetch_branch(repo: &Repository, remote_name: &str, branch: &str) -> Result<()> {
552    // Check if branch already exists locally
553    let branch_ref = format!("refs/remotes/{}/{}", remote_name, branch);
554    if repo.find_reference(&branch_ref).is_ok() {
555        debug!("Branch ref {} already exists", branch_ref);
556        return Ok(());
557    }
558
559    debug!("Fetching branch {} from remote {}", branch, remote_name);
560
561    let refspec = format!(
562        "+refs/heads/{}:refs/remotes/{}/{}",
563        branch, remote_name, branch
564    );
565
566    let remote_url = repo
567        .find_remote(remote_name)
568        .ok()
569        .and_then(|r| r.url().ok().map(str::to_string));
570    let auth = get_remote_callbacks(repo, remote_url.as_deref())?;
571    let mut fetch_options = FetchOptions::new();
572    fetch_options.remote_callbacks(auth.callbacks());
573
574    repo.find_remote(remote_name)?
575        .fetch(
576            &[refspec.as_str()],
577            Some(&mut fetch_options),
578            Some("Fetching PR branch"),
579        )
580        .map_err(|e| PrError::FetchFailed {
581            remote: remote_name.to_string(),
582            message: e.message().to_string(),
583        })?;
584
585    debug!("Successfully fetched branch {}", branch);
586    Ok(())
587}
588
589/// Format a PR worktree name using the format string
590///
591/// Replaces `{number}` placeholder with the PR number.
592pub fn format_pr_name(format: &str, pr_number: u32) -> String {
593    format.replace("{number}", &pr_number.to_string())
594}
595
596/// Prepare everything needed to create a worktree for PR `pr_number`.
597///
598/// Orchestrates the complete PR workflow:
599/// 1. Checks that `gh` CLI is available
600/// 2. Fetches PR metadata via `gh`
601/// 3. Sets up a fork remote if the PR is cross-repository
602/// 4. Fetches the PR's head branch
603/// 5. Formats the worktree name using `pr_format`
604///
605/// Returns `(worktree_name, remote_ref, base_branch)` ready for `add_worktree`.
606pub fn prepare_pr_worktree(
607    repo: &Repository,
608    pr_number: u32,
609    pr_format: &str,
610) -> Result<(String, String, String)> {
611    debug!("Preparing PR worktree for PR #{}", pr_number);
612
613    // Fetch PR metadata from gh CLI
614    let metadata = fetch_pr_metadata(pr_number)?;
615    debug!(
616        "Fetched metadata: title='{}', author='{}', is_fork={}",
617        metadata.title, metadata.author, metadata.is_fork
618    );
619
620    // Setup remote and fetch branch
621    // For fork PRs: setup fork remote and fetch from it
622    // For non-fork PRs: use existing remote (origin/upstream)
623    let remote_name = if metadata.is_fork {
624        setup_fork_remote(repo, &metadata)?
625    } else {
626        detect_pr_remote(repo)?
627    };
628
629    // Fetch the actual branch from gh CLI metadata (works for both fork and non-fork)
630    fetch_branch(repo, &remote_name, &metadata.head_ref)?;
631
632    // Format worktree name using metadata
633    let worktree_name = format_pr_name_with_metadata(pr_format, &metadata);
634    debug!("Worktree name: {}", worktree_name);
635
636    // Build remote ref using the actual branch from metadata
637    let remote_ref = format!("{}/{}", remote_name, metadata.head_ref);
638    debug!("Remote ref: {}", remote_ref);
639
640    Ok((worktree_name, remote_ref, metadata.base_ref))
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    #[test]
648    fn test_parse_hash_number() {
649        let pr = parse_pr_reference("#123").unwrap().unwrap();
650        assert_eq!(pr.number, 123);
651        assert_eq!(pr.remote, None);
652    }
653
654    #[test]
655    fn test_parse_pr_hash_number() {
656        let pr = parse_pr_reference("pr#456").unwrap().unwrap();
657        assert_eq!(pr.number, 456);
658        assert_eq!(pr.remote, None);
659    }
660
661    #[test]
662    fn test_parse_pr_dash_number() {
663        let pr = parse_pr_reference("pr-789").unwrap().unwrap();
664        assert_eq!(pr.number, 789);
665        assert_eq!(pr.remote, None);
666    }
667
668    #[test]
669    fn test_parse_github_url() {
670        let pr = parse_pr_reference("https://github.com/owner/repo/pull/999")
671            .unwrap()
672            .unwrap();
673        assert_eq!(pr.number, 999);
674        assert_eq!(pr.remote, None);
675    }
676
677    #[test]
678    fn test_parse_remote_ref() {
679        let pr = parse_pr_reference("origin/pull/111/head").unwrap().unwrap();
680        assert_eq!(pr.number, 111);
681        assert_eq!(pr.remote, None);
682    }
683
684    #[test]
685    fn test_parse_regular_branch_name() {
686        let result = parse_pr_reference("my-feature-branch").unwrap();
687        assert!(result.is_none());
688    }
689
690    #[test]
691    fn test_parse_invalid_number() {
692        let result = parse_pr_reference("#abc");
693        assert!(result.is_err());
694    }
695
696    #[test]
697    fn test_is_pr_reference_true() {
698        assert!(is_pr_reference("#123"));
699        assert!(is_pr_reference("pr#456"));
700        assert!(is_pr_reference("pr-789"));
701        assert!(is_pr_reference("https://github.com/owner/repo/pull/999"));
702    }
703
704    #[test]
705    fn test_is_pr_reference_false() {
706        assert!(!is_pr_reference("my-branch"));
707        assert!(!is_pr_reference("feature"));
708    }
709
710    #[test]
711    fn test_format_pr_name() {
712        assert_eq!(format_pr_name("pr-{number}", 123), "pr-123");
713        assert_eq!(format_pr_name("review-{number}", 456), "review-456");
714        assert_eq!(format_pr_name("{number}-test", 789), "789-test");
715    }
716
717    #[test]
718    fn test_sanitize_branch_name() {
719        assert_eq!(sanitize_for_branch_name("Fix Bug #123"), "fix-bug-123");
720        assert_eq!(
721            sanitize_for_branch_name("Add Feature (v2)"),
722            "add-feature-v2"
723        );
724        assert_eq!(sanitize_for_branch_name("john-smith"), "john-smith");
725        assert_eq!(
726            sanitize_for_branch_name("Fix: Authentication Issue"),
727            "fix-authentication-issue"
728        );
729        assert_eq!(sanitize_for_branch_name("Test@#$%"), "test");
730    }
731
732    #[test]
733    fn test_format_with_metadata() {
734        let metadata = PrMetadata {
735            number: 123,
736            title: "Fix Authentication Bug".to_string(),
737            author: "john-smith".to_string(),
738            head_ref: "feature/fix-auth".to_string(),
739            base_ref: "main".to_string(),
740            is_fork: false,
741            fork_owner: None,
742            fork_url: None,
743        };
744
745        assert_eq!(
746            format_pr_name_with_metadata("pr-{number}", &metadata),
747            "pr-123"
748        );
749        assert_eq!(
750            format_pr_name_with_metadata("{number}-{title}", &metadata),
751            "123-fix-authentication-bug"
752        );
753        assert_eq!(
754            format_pr_name_with_metadata("{author}/pr-{number}", &metadata),
755            "john-smith/pr-123"
756        );
757        assert_eq!(
758            format_pr_name_with_metadata("{branch}-{number}", &metadata),
759            "feature-fix-auth-123"
760        );
761    }
762
763    #[test]
764    fn test_parse_merged_pr_empty_array() {
765        assert_eq!(parse_merged_pr("[]"), None);
766    }
767
768    #[test]
769    fn test_parse_merged_pr_populated_array() {
770        let json = r#"[{"number":66,"mergedAt":"2024-01-01T00:00:00Z"}]"#;
771        assert_eq!(parse_merged_pr(json), Some(66));
772    }
773
774    #[test]
775    fn test_parse_merged_pr_number_missing() {
776        let json = r#"[{"mergedAt":"2024-01-01T00:00:00Z"}]"#;
777        assert_eq!(parse_merged_pr(json), None);
778    }
779
780    #[test]
781    fn test_parse_merged_pr_number_non_numeric() {
782        let json = r#"[{"number":"not-a-number","mergedAt":"2024-01-01T00:00:00Z"}]"#;
783        assert_eq!(parse_merged_pr(json), None);
784    }
785
786    #[test]
787    fn test_parse_merged_pr_non_array_payload() {
788        assert_eq!(parse_merged_pr(r#"{"number":66}"#), None);
789    }
790
791    #[test]
792    fn test_parse_merged_pr_malformed_json() {
793        assert_eq!(parse_merged_pr("not json"), None);
794    }
795
796    // Integration tests requiring gh CLI (marked with #[ignore])
797    #[test]
798    #[ignore]
799    fn test_gh_cli_available() {
800        check_gh_available().expect("gh CLI should be installed");
801    }
802
803    #[test]
804    #[ignore]
805    fn test_fetch_real_pr_metadata() {
806        // Requires gh CLI and auth
807        // This test uses a real PR from a public repo (git-workon itself if available)
808        // Replace with actual PR number from your repository for testing
809        let metadata = fetch_pr_metadata(1).expect("Failed to fetch PR metadata");
810        assert_eq!(metadata.number, 1);
811        assert!(!metadata.title.is_empty());
812        assert!(!metadata.author.is_empty());
813    }
814}