Skip to main content

git_cli/
open.rs

1use nils_common::git::strip_userinfo;
2use nils_common::process;
3use std::io::{self, Write};
4use std::process::Output;
5
6pub fn dispatch(cmd: &str, args: &[String]) -> Option<i32> {
7    match cmd {
8        "repo" => Some(open_repo(args)),
9        "branch" => Some(open_branch(args)),
10        "default" | "default-branch" => Some(open_default_branch(args)),
11        "commit" => Some(open_commit(args)),
12        "compare" => Some(open_compare(args)),
13        "pr" | "pull-request" | "mr" | "merge-request" => Some(open_pr(args)),
14        "pulls" | "prs" | "merge-requests" | "mrs" => Some(open_pulls(args)),
15        "issue" | "issues" => Some(open_issues(args)),
16        "action" | "actions" => Some(open_actions(args)),
17        "release" | "releases" => Some(open_releases(args)),
18        "tag" | "tags" => Some(open_tags(args)),
19        "commits" | "history" => Some(open_commits(args)),
20        "file" | "blob" => Some(open_file(args)),
21        "blame" => Some(open_blame(args)),
22        _ => None,
23    }
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27enum Provider {
28    Github,
29    Gitlab,
30    Generic,
31}
32
33impl Provider {
34    fn from_base_url(base_url: &str) -> Self {
35        let host = host_from_url(base_url);
36        match host.as_str() {
37            "github.com" => Self::Github,
38            "gitlab.com" => Self::Gitlab,
39            _ => {
40                if host.contains("gitlab") {
41                    Self::Gitlab
42                } else if host.contains("github") {
43                    Self::Github
44                } else {
45                    Self::Generic
46                }
47            }
48        }
49    }
50}
51
52#[derive(Debug, Clone)]
53struct OpenContext {
54    base_url: String,
55    remote: String,
56    remote_branch: String,
57    provider: Provider,
58}
59
60#[derive(Debug, Clone)]
61struct CollabContext {
62    base_url: String,
63    remote: String,
64    provider: Provider,
65}
66
67fn open_repo(args: &[String]) -> i32 {
68    if args.len() > 1 {
69        eprintln!("โŒ git-cli open repo takes at most one remote name");
70        print_usage();
71        return 2;
72    }
73
74    if args.first().is_some_and(|arg| is_help_token(arg)) {
75        print_usage();
76        return 0;
77    }
78
79    let base_url = if let Some(remote) = args.first() {
80        match normalize_remote_url(remote) {
81            Ok(url) => url,
82            Err(code) => return code,
83        }
84    } else {
85        match resolve_context() {
86            Ok(ctx) => ctx.base_url,
87            Err(code) => return code,
88        }
89    };
90
91    open_url(&base_url, "๐ŸŒ Opened")
92}
93
94fn open_branch(args: &[String]) -> i32 {
95    if args.len() > 1 {
96        eprintln!("โŒ git-cli open branch takes at most one ref");
97        print_usage();
98        return 2;
99    }
100
101    if args.first().is_some_and(|arg| is_help_token(arg)) {
102        print_usage();
103        return 0;
104    }
105
106    let ctx = match resolve_context() {
107        Ok(ctx) => ctx,
108        Err(code) => return code,
109    };
110
111    let reference = args
112        .first()
113        .map(ToOwned::to_owned)
114        .unwrap_or_else(|| ctx.remote_branch.clone());
115    let url = tree_url(ctx.provider, &ctx.base_url, &reference);
116    open_url(&url, "๐ŸŒฟ Opened")
117}
118
119fn open_default_branch(args: &[String]) -> i32 {
120    if args.len() > 1 {
121        eprintln!("โŒ git-cli open default-branch takes at most one remote name");
122        print_usage();
123        return 2;
124    }
125
126    if args.first().is_some_and(|arg| is_help_token(arg)) {
127        print_usage();
128        return 0;
129    }
130
131    let (base_url, remote, provider) = if let Some(remote) = args.first() {
132        let base_url = match normalize_remote_url(remote) {
133            Ok(url) => url,
134            Err(code) => return code,
135        };
136        let provider = Provider::from_base_url(&base_url);
137        (base_url, remote.to_string(), provider)
138    } else {
139        let ctx = match resolve_context() {
140            Ok(ctx) => ctx,
141            Err(code) => return code,
142        };
143        (ctx.base_url, ctx.remote, ctx.provider)
144    };
145
146    let default_branch = match default_branch_name(&remote) {
147        Ok(branch) => branch,
148        Err(code) => return code,
149    };
150    let url = tree_url(provider, &base_url, &default_branch);
151    open_url(&url, "๐ŸŒฟ Opened")
152}
153
154fn open_commit(args: &[String]) -> i32 {
155    if args.len() > 1 {
156        eprintln!("โŒ git-cli open commit takes at most one ref");
157        print_usage();
158        return 2;
159    }
160
161    if args.first().is_some_and(|arg| is_help_token(arg)) {
162        print_usage();
163        return 0;
164    }
165
166    let reference = args.first().map(String::as_str).unwrap_or("HEAD");
167    let ctx = match resolve_context() {
168        Ok(ctx) => ctx,
169        Err(code) => return code,
170    };
171
172    let commit_ref = format!("{reference}^{{commit}}");
173    let commit = match git_stdout_trimmed(&["rev-parse", &commit_ref]) {
174        Ok(value) => value,
175        Err(_) => {
176            eprintln!("โŒ Invalid commit/tag/branch: {reference}");
177            return 1;
178        }
179    };
180
181    let url = commit_url(ctx.provider, &ctx.base_url, &commit);
182    open_url(&url, "๐Ÿ”— Opened")
183}
184
185fn open_compare(args: &[String]) -> i32 {
186    if args.first().is_some_and(|arg| is_help_token(arg)) {
187        print_usage();
188        return 0;
189    }
190
191    if args.len() > 2 {
192        eprintln!("โŒ git-cli open compare takes at most two refs");
193        print_usage();
194        return 2;
195    }
196
197    let ctx = match resolve_context() {
198        Ok(ctx) => ctx,
199        Err(code) => return code,
200    };
201
202    let (base, head) = match args.len() {
203        0 => {
204            let base = match default_branch_name(&ctx.remote) {
205                Ok(value) => value,
206                Err(code) => return code,
207            };
208            (base, ctx.remote_branch)
209        }
210        1 => (args[0].to_string(), ctx.remote_branch),
211        _ => (args[0].to_string(), args[1].to_string()),
212    };
213
214    let url = compare_url(ctx.provider, &ctx.base_url, &base, &head);
215    open_url(&url, "๐Ÿ”€ Opened")
216}
217
218fn open_pr(args: &[String]) -> i32 {
219    if args.len() > 1 {
220        eprintln!("โŒ git-cli open pr takes at most one number");
221        print_usage();
222        return 2;
223    }
224
225    if args.first().is_some_and(|arg| is_help_token(arg)) {
226        print_usage();
227        return 0;
228    }
229
230    let ctx = match resolve_context() {
231        Ok(ctx) => ctx,
232        Err(code) => return code,
233    };
234    let collab = match resolve_collab_context(&ctx) {
235        Ok(value) => value,
236        Err(code) => return code,
237    };
238
239    if let Some(raw_number) = args.first() {
240        let pr_number = match parse_positive_number(raw_number, "PR") {
241            Ok(value) => value,
242            Err(code) => return code,
243        };
244
245        let url = match collab.provider {
246            Provider::Github => format!("{}/pull/{pr_number}", collab.base_url),
247            Provider::Gitlab => format!("{}/-/merge_requests/{pr_number}", collab.base_url),
248            Provider::Generic => {
249                eprintln!("โ— pr <number> is only supported for GitHub/GitLab remotes.");
250                return 1;
251            }
252        };
253        return open_url(&url, "๐Ÿงท Opened");
254    }
255
256    if collab.provider == Provider::Github
257        && process::cmd_exists("gh")
258        && try_open_pr_with_gh(&ctx, &collab)
259    {
260        return 0;
261    }
262
263    match collab.provider {
264        Provider::Github => {
265            let base = match default_branch_name(&collab.remote) {
266                Ok(value) => value,
267                Err(code) => return code,
268            };
269
270            let mut head_ref = ctx.remote_branch.clone();
271            if collab.base_url != ctx.base_url
272                && let Some(slug) = github_repo_slug(&ctx.base_url)
273                && let Some((owner, _)) = slug.split_once('/')
274            {
275                head_ref = format!("{owner}:{}", ctx.remote_branch);
276            }
277
278            let url = format!(
279                "{}/compare/{}...{}?expand=1",
280                collab.base_url, base, head_ref
281            );
282            open_url(&url, "๐Ÿงท Opened")
283        }
284        Provider::Gitlab => {
285            let base = match default_branch_name(&collab.remote) {
286                Ok(value) => value,
287                Err(code) => return code,
288            };
289            let source_enc = percent_encode(&ctx.remote_branch, false);
290            let target_enc = percent_encode(&base, false);
291            let url = format!(
292                "{}/-/merge_requests/new?merge_request[source_branch]={source_enc}&merge_request[target_branch]={target_enc}",
293                collab.base_url
294            );
295            open_url(&url, "๐Ÿงท Opened")
296        }
297        Provider::Generic => {
298            let base = match default_branch_name(&collab.remote) {
299                Ok(value) => value,
300                Err(code) => return code,
301            };
302            let url = format!(
303                "{}/compare/{}...{}",
304                collab.base_url, base, ctx.remote_branch
305            );
306            open_url(&url, "๐Ÿงท Opened")
307        }
308    }
309}
310
311fn open_pulls(args: &[String]) -> i32 {
312    if args.len() > 1 {
313        eprintln!("โŒ git-cli open pulls takes at most one number");
314        print_usage();
315        return 2;
316    }
317
318    if let Some(value) = args.first() {
319        return open_pr(&[value.to_string()]);
320    }
321
322    let ctx = match resolve_context() {
323        Ok(ctx) => ctx,
324        Err(code) => return code,
325    };
326    let collab = match resolve_collab_context(&ctx) {
327        Ok(value) => value,
328        Err(code) => return code,
329    };
330
331    let url = match collab.provider {
332        Provider::Gitlab => format!("{}/-/merge_requests", collab.base_url),
333        _ => format!("{}/pulls", collab.base_url),
334    };
335    open_url(&url, "๐Ÿ“Œ Opened")
336}
337
338fn open_issues(args: &[String]) -> i32 {
339    if args.len() > 1 {
340        eprintln!("โŒ git-cli open issues takes at most one number");
341        print_usage();
342        return 2;
343    }
344
345    let ctx = match resolve_context() {
346        Ok(ctx) => ctx,
347        Err(code) => return code,
348    };
349    let collab = match resolve_collab_context(&ctx) {
350        Ok(value) => value,
351        Err(code) => return code,
352    };
353
354    let url = if let Some(raw_number) = args.first() {
355        let issue_number = match parse_positive_number(raw_number, "issue") {
356            Ok(value) => value,
357            Err(code) => return code,
358        };
359        match collab.provider {
360            Provider::Gitlab => format!("{}/-/issues/{issue_number}", collab.base_url),
361            _ => format!("{}/issues/{issue_number}", collab.base_url),
362        }
363    } else {
364        match collab.provider {
365            Provider::Gitlab => format!("{}/-/issues", collab.base_url),
366            _ => format!("{}/issues", collab.base_url),
367        }
368    };
369    open_url(&url, "๐Ÿ“Œ Opened")
370}
371
372fn open_actions(args: &[String]) -> i32 {
373    if args.len() > 1 {
374        eprintln!("โŒ git-cli open actions takes at most one workflow");
375        print_usage();
376        return 2;
377    }
378
379    if args.first().is_some_and(|arg| is_help_token(arg)) {
380        print_usage();
381        return 0;
382    }
383
384    let ctx = match resolve_context() {
385        Ok(ctx) => ctx,
386        Err(code) => return code,
387    };
388    let collab = match resolve_collab_context(&ctx) {
389        Ok(value) => value,
390        Err(code) => return code,
391    };
392
393    if collab.provider != Provider::Github {
394        eprintln!("โ— actions is only supported for GitHub remotes.");
395        return 1;
396    }
397
398    let url = if let Some(workflow) = args.first() {
399        if is_yaml_workflow(workflow) {
400            let encoded = percent_encode(workflow, false);
401            format!("{}/actions/workflows/{encoded}", collab.base_url)
402        } else {
403            let q = format!("workflow:{workflow}");
404            let encoded = percent_encode(&q, false);
405            format!("{}/actions?query={encoded}", collab.base_url)
406        }
407    } else {
408        format!("{}/actions", collab.base_url)
409    };
410
411    open_url(&url, "๐Ÿ“Œ Opened")
412}
413
414fn open_releases(args: &[String]) -> i32 {
415    if args.len() > 1 {
416        eprintln!("โŒ git-cli open releases takes at most one tag");
417        print_usage();
418        return 2;
419    }
420
421    if args.first().is_some_and(|arg| is_help_token(arg)) {
422        print_usage();
423        return 0;
424    }
425
426    let ctx = match resolve_context() {
427        Ok(ctx) => ctx,
428        Err(code) => return code,
429    };
430    let collab = match resolve_collab_context(&ctx) {
431        Ok(value) => value,
432        Err(code) => return code,
433    };
434
435    let url = if let Some(tag) = args.first() {
436        release_tag_url(collab.provider, &collab.base_url, tag)
437    } else {
438        match collab.provider {
439            Provider::Gitlab => format!("{}/-/releases", collab.base_url),
440            _ => format!("{}/releases", collab.base_url),
441        }
442    };
443    open_url(&url, "๐Ÿ“Œ Opened")
444}
445
446fn open_tags(args: &[String]) -> i32 {
447    if args.len() > 1 {
448        eprintln!("โŒ git-cli open tags takes at most one tag");
449        print_usage();
450        return 2;
451    }
452
453    if args.first().is_some_and(|arg| is_help_token(arg)) {
454        print_usage();
455        return 0;
456    }
457
458    let ctx = match resolve_context() {
459        Ok(ctx) => ctx,
460        Err(code) => return code,
461    };
462    let collab = match resolve_collab_context(&ctx) {
463        Ok(value) => value,
464        Err(code) => return code,
465    };
466
467    let url = if let Some(tag) = args.first() {
468        release_tag_url(collab.provider, &collab.base_url, tag)
469    } else {
470        match collab.provider {
471            Provider::Gitlab => format!("{}/-/tags", collab.base_url),
472            _ => format!("{}/tags", collab.base_url),
473        }
474    };
475    open_url(&url, "๐Ÿ“Œ Opened")
476}
477
478fn open_commits(args: &[String]) -> i32 {
479    if args.len() > 1 {
480        eprintln!("โŒ git-cli open commits takes at most one ref");
481        print_usage();
482        return 2;
483    }
484
485    if args.first().is_some_and(|arg| is_help_token(arg)) {
486        print_usage();
487        return 0;
488    }
489
490    let ctx = match resolve_context() {
491        Ok(ctx) => ctx,
492        Err(code) => return code,
493    };
494    let reference = args
495        .first()
496        .map(ToOwned::to_owned)
497        .unwrap_or_else(|| ctx.remote_branch.clone());
498    let url = commits_url(ctx.provider, &ctx.base_url, &reference);
499    open_url(&url, "๐Ÿ“œ Opened")
500}
501
502fn open_file(args: &[String]) -> i32 {
503    if args.first().is_some_and(|arg| is_help_token(arg)) {
504        print_usage();
505        return 0;
506    }
507
508    if args.is_empty() || args.len() > 2 {
509        eprintln!("โŒ Usage: git-cli open file <path> [ref]");
510        return 2;
511    }
512
513    let ctx = match resolve_context() {
514        Ok(ctx) => ctx,
515        Err(code) => return code,
516    };
517
518    let path = normalize_repo_path(&args[0]);
519    let reference = args
520        .get(1)
521        .map(ToOwned::to_owned)
522        .unwrap_or_else(|| ctx.remote_branch.clone());
523
524    let url = blob_url(ctx.provider, &ctx.base_url, &reference, &path);
525    open_url(&url, "๐Ÿ“„ Opened")
526}
527
528fn open_blame(args: &[String]) -> i32 {
529    if args.first().is_some_and(|arg| is_help_token(arg)) {
530        print_usage();
531        return 0;
532    }
533
534    if args.is_empty() || args.len() > 2 {
535        eprintln!("โŒ Usage: git-cli open blame <path> [ref]");
536        return 2;
537    }
538
539    let ctx = match resolve_context() {
540        Ok(ctx) => ctx,
541        Err(code) => return code,
542    };
543
544    let path = normalize_repo_path(&args[0]);
545    let reference = args
546        .get(1)
547        .map(ToOwned::to_owned)
548        .unwrap_or_else(|| ctx.remote_branch.clone());
549
550    let url = blame_url(ctx.provider, &ctx.base_url, &reference, &path);
551    open_url(&url, "๐Ÿ•ต๏ธ Opened")
552}
553
554fn try_open_pr_with_gh(ctx: &OpenContext, collab: &CollabContext) -> bool {
555    let mut candidates: Vec<Option<String>> = Vec::new();
556
557    if let Some(slug) = github_repo_slug(&collab.base_url) {
558        candidates.push(Some(slug));
559    }
560    if let Some(slug) = github_repo_slug(&ctx.base_url)
561        && !candidates
562            .iter()
563            .any(|value| value.as_deref() == Some(&slug))
564    {
565        candidates.push(Some(slug));
566    }
567    candidates.push(None);
568
569    for repo in candidates {
570        if run_gh_pr_view(repo.as_deref(), Some(&ctx.remote_branch)) {
571            return true;
572        }
573    }
574
575    false
576}
577
578fn run_gh_pr_view(repo: Option<&str>, selector: Option<&str>) -> bool {
579    let mut owned_args: Vec<String> = vec!["pr".into(), "view".into(), "--web".into()];
580    if let Some(repo) = repo {
581        owned_args.push("--repo".into());
582        owned_args.push(repo.to_string());
583    }
584    if let Some(selector) = selector {
585        owned_args.push(selector.to_string());
586    }
587    let args: Vec<&str> = owned_args.iter().map(String::as_str).collect();
588
589    let output = match run_output("gh", &args) {
590        Ok(output) => output,
591        Err(_) => return false,
592    };
593
594    if output.status.success() {
595        println!("๐Ÿงท Opened PR via gh");
596        true
597    } else {
598        false
599    }
600}
601
602fn resolve_context() -> Result<OpenContext, i32> {
603    let (remote, remote_branch) = resolve_upstream()?;
604    let base_url = normalize_remote_url(&remote)?;
605    let provider = Provider::from_base_url(&base_url);
606    Ok(OpenContext {
607        base_url,
608        remote,
609        remote_branch,
610        provider,
611    })
612}
613
614fn resolve_collab_context(ctx: &OpenContext) -> Result<CollabContext, i32> {
615    let env_remote = std::env::var("GIT_OPEN_COLLAB_REMOTE")
616        .ok()
617        .map(|value| value.trim().to_string())
618        .filter(|value| !value.is_empty());
619
620    if let Some(remote) = env_remote
621        && let Ok(base_url) = normalize_remote_url(&remote)
622    {
623        let provider = Provider::from_base_url(&base_url);
624        return Ok(CollabContext {
625            base_url,
626            remote,
627            provider,
628        });
629    }
630
631    Ok(CollabContext {
632        base_url: ctx.base_url.clone(),
633        remote: ctx.remote.clone(),
634        provider: ctx.provider,
635    })
636}
637
638fn resolve_upstream() -> Result<(String, String), i32> {
639    if !git_status_success(&["rev-parse", "--is-inside-work-tree"]) {
640        eprintln!("โŒ Not in a git repository");
641        return Err(1);
642    }
643
644    let branch = match git_stdout_trimmed(&["rev-parse", "--abbrev-ref", "HEAD"]) {
645        Ok(value) => value,
646        Err(_) => {
647            eprintln!("โŒ Unable to resolve current branch");
648            return Err(1);
649        }
650    };
651
652    let upstream =
653        git_stdout_trimmed_optional(&["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
654            .unwrap_or_default();
655
656    let mut remote = String::new();
657    let mut remote_branch = String::new();
658
659    if !upstream.is_empty()
660        && upstream != branch
661        && let Some((upstream_remote, upstream_branch)) = upstream.split_once('/')
662    {
663        remote = upstream_remote.to_string();
664        remote_branch = upstream_branch.to_string();
665    }
666
667    if remote.is_empty() {
668        remote = "origin".to_string();
669    }
670
671    if remote_branch.is_empty() || remote_branch == "HEAD" {
672        remote_branch = branch;
673    }
674
675    Ok((remote, remote_branch))
676}
677
678fn normalize_remote_url(remote: &str) -> Result<String, i32> {
679    if remote.trim().is_empty() {
680        eprintln!("โŒ Missing remote name");
681        return Err(1);
682    }
683
684    let raw = match git_stdout_trimmed(&["remote", "get-url", remote]) {
685        Ok(value) => value,
686        Err(_) => {
687            eprintln!("โŒ Failed to resolve remote URL for {remote}");
688            return Err(1);
689        }
690    };
691
692    match normalize_remote_url_from_raw(&raw) {
693        Some(value) => Ok(value),
694        None => {
695            eprintln!("โŒ Unable to normalize remote URL for {remote}");
696            Err(1)
697        }
698    }
699}
700
701fn normalize_remote_url_from_raw(raw: &str) -> Option<String> {
702    let input = raw.trim();
703    if input.is_empty() {
704        return None;
705    }
706
707    let normalized = if let Some((scheme, rest)) = input.split_once("://") {
708        let (host_with_auth, path) = match rest.split_once('/') {
709            Some((host, path)) => (host, path),
710            None => (rest, ""),
711        };
712        let host = strip_userinfo(host_with_auth);
713        if host.is_empty() {
714            return None;
715        }
716
717        match scheme {
718            "ssh" | "git" => {
719                if path.is_empty() {
720                    format!("https://{host}")
721                } else {
722                    format!("https://{host}/{path}")
723                }
724            }
725            "http" | "https" => {
726                if path.is_empty() {
727                    format!("{scheme}://{host}")
728                } else {
729                    format!("{scheme}://{host}/{path}")
730                }
731            }
732            _ => {
733                if path.is_empty() {
734                    format!("{scheme}://{host}")
735                } else {
736                    format!("{scheme}://{host}/{path}")
737                }
738            }
739        }
740    } else if input.contains(':') {
741        if let Some((host_part, path_part)) = input.rsplit_once(':') {
742            let host = strip_userinfo(host_part);
743            if !host.is_empty()
744                && !path_part.is_empty()
745                && !host.contains('/')
746                && !path_part.starts_with('/')
747            {
748                format!("https://{host}/{path_part}")
749            } else {
750                input.to_string()
751            }
752        } else {
753            input.to_string()
754        }
755    } else if let Some((host_part, path_part)) = input.split_once('/') {
756        if host_part.contains('@') {
757            let host = strip_userinfo(host_part);
758            if host.is_empty() {
759                return None;
760            }
761            format!("https://{host}/{path_part}")
762        } else {
763            input.to_string()
764        }
765    } else {
766        input.to_string()
767    };
768
769    if !normalized.starts_with("http://") && !normalized.starts_with("https://") {
770        return None;
771    }
772
773    let trimmed = normalized.trim_end_matches('/').trim_end_matches(".git");
774    if trimmed.is_empty() {
775        None
776    } else {
777        Some(trimmed.to_string())
778    }
779}
780
781fn default_branch_name(remote: &str) -> Result<String, i32> {
782    let symbolic = format!("refs/remotes/{remote}/HEAD");
783    if let Some(value) =
784        git_stdout_trimmed_optional(&["symbolic-ref", "--quiet", "--short", &symbolic])
785        && let Some((_, branch)) = value.split_once('/')
786        && !branch.trim().is_empty()
787    {
788        return Ok(branch.to_string());
789    }
790
791    let output = match run_git_output(&["remote", "show", remote]) {
792        Some(output) => output,
793        None => return Err(1),
794    };
795    if !output.status.success() {
796        emit_output(&output);
797        return Err(exit_code(&output));
798    }
799    let text = String::from_utf8_lossy(&output.stdout);
800    for line in text.lines() {
801        if line.contains("HEAD branch") {
802            let value = line
803                .split_once(':')
804                .map(|(_, tail)| tail.trim())
805                .unwrap_or("");
806            if !value.is_empty() && value != "(unknown)" {
807                return Ok(value.to_string());
808            }
809        }
810    }
811
812    eprintln!("โŒ Failed to resolve default branch for {remote}");
813    Err(1)
814}
815
816fn parse_positive_number(raw: &str, kind: &str) -> Result<String, i32> {
817    let cleaned = raw.trim_start_matches('#');
818    if cleaned.chars().all(|ch| ch.is_ascii_digit()) && !cleaned.is_empty() {
819        Ok(cleaned.to_string())
820    } else {
821        eprintln!("โŒ Invalid {kind} number: {raw}");
822        Err(2)
823    }
824}
825
826fn normalize_repo_path(path: &str) -> String {
827    path.trim_start_matches("./")
828        .trim_start_matches('/')
829        .to_string()
830}
831
832fn is_yaml_workflow(value: &str) -> bool {
833    value.ends_with(".yml") || value.ends_with(".yaml")
834}
835
836fn tree_url(provider: Provider, base_url: &str, reference: &str) -> String {
837    match provider {
838        Provider::Gitlab => format!("{base_url}/-/tree/{reference}"),
839        _ => format!("{base_url}/tree/{reference}"),
840    }
841}
842
843fn commit_url(provider: Provider, base_url: &str, commit: &str) -> String {
844    match provider {
845        Provider::Gitlab => format!("{base_url}/-/commit/{commit}"),
846        _ => format!("{base_url}/commit/{commit}"),
847    }
848}
849
850fn compare_url(provider: Provider, base_url: &str, base: &str, head: &str) -> String {
851    match provider {
852        Provider::Gitlab => format!("{base_url}/-/compare/{base}...{head}"),
853        _ => format!("{base_url}/compare/{base}...{head}"),
854    }
855}
856
857fn blob_url(provider: Provider, base_url: &str, reference: &str, path: &str) -> String {
858    let encoded_path = percent_encode(path, true);
859    match provider {
860        Provider::Gitlab => format!("{base_url}/-/blob/{reference}/{encoded_path}"),
861        _ => format!("{base_url}/blob/{reference}/{encoded_path}"),
862    }
863}
864
865fn blame_url(provider: Provider, base_url: &str, reference: &str, path: &str) -> String {
866    let encoded_path = percent_encode(path, true);
867    match provider {
868        Provider::Gitlab => format!("{base_url}/-/blame/{reference}/{encoded_path}"),
869        _ => format!("{base_url}/blame/{reference}/{encoded_path}"),
870    }
871}
872
873fn commits_url(provider: Provider, base_url: &str, reference: &str) -> String {
874    match provider {
875        Provider::Gitlab => format!("{base_url}/-/commits/{reference}"),
876        _ => format!("{base_url}/commits/{reference}"),
877    }
878}
879
880fn release_tag_url(provider: Provider, base_url: &str, tag: &str) -> String {
881    let encoded = percent_encode(tag, false);
882    match provider {
883        Provider::Gitlab => format!("{base_url}/-/releases/{encoded}"),
884        _ => format!("{base_url}/releases/tag/{encoded}"),
885    }
886}
887
888fn github_repo_slug(base_url: &str) -> Option<String> {
889    let without_scheme = base_url
890        .split_once("://")
891        .map(|(_, rest)| rest)
892        .unwrap_or(base_url);
893    let (_, path) = without_scheme.split_once('/')?;
894    let mut parts = path.split('/').filter(|part| !part.is_empty());
895    let owner = parts.next()?;
896    let repo = parts.next()?;
897    Some(format!("{owner}/{repo}"))
898}
899
900fn host_from_url(url: &str) -> String {
901    let without_scheme = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);
902    without_scheme
903        .split('/')
904        .next()
905        .unwrap_or("")
906        .to_ascii_lowercase()
907}
908
909fn percent_encode(value: &str, keep_slash: bool) -> String {
910    let mut out = String::new();
911    for byte in value.as_bytes() {
912        let is_unreserved =
913            matches!(byte, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~');
914        if is_unreserved || (keep_slash && *byte == b'/') {
915            out.push(*byte as char);
916        } else {
917            out.push_str(&format!("%{byte:02X}"));
918        }
919    }
920    out
921}
922
923fn open_url(url: &str, label: &str) -> i32 {
924    if url.is_empty() {
925        eprintln!("โŒ Missing URL");
926        return 1;
927    }
928
929    let Some(opener) = process::browser_open_command() else {
930        eprintln!("โŒ Cannot open URL (no open/xdg-open)");
931        return 1;
932    };
933
934    let output = match run_output(opener, &[url]) {
935        Ok(output) => output,
936        Err(err) => {
937            eprintln!("{err}");
938            return 1;
939        }
940    };
941    if !output.status.success() {
942        if process::is_headless_browser_launch_failure(&output.stdout, &output.stderr) {
943            println!("๐Ÿ”— URL: {url}");
944            eprintln!("โš ๏ธ  Could not launch a browser in this environment; open the URL manually.");
945            return 0;
946        }
947        emit_output(&output);
948        return exit_code(&output);
949    }
950
951    println!("{label}: {url}");
952    0
953}
954
955fn is_help_token(raw: &str) -> bool {
956    matches!(raw, "-h" | "--help" | "help")
957}
958
959fn print_usage() {
960    println!("Usage:");
961    println!("  git-cli open");
962    println!("  git-cli open repo [remote]");
963    println!("  git-cli open branch [ref]");
964    println!("  git-cli open default-branch [remote]");
965    println!("  git-cli open commit [ref]");
966    println!("  git-cli open compare [base] [head]");
967    println!("  git-cli open pr [number]");
968    println!("  git-cli open pulls [number]");
969    println!("  git-cli open issues [number]");
970    println!("  git-cli open actions [workflow]");
971    println!("  git-cli open releases [tag]");
972    println!("  git-cli open tags [tag]");
973    println!("  git-cli open commits [ref]");
974    println!("  git-cli open file <path> [ref]");
975    println!("  git-cli open blame <path> [ref]");
976    println!();
977    println!("Notes:");
978    println!("  - Uses the upstream remote when available; falls back to origin.");
979    println!("  - Collaboration pages prefer GIT_OPEN_COLLAB_REMOTE when set.");
980    println!("  - `pr` prefers gh when available on GitHub remotes.");
981}
982
983fn run_git_output(args: &[&str]) -> Option<Output> {
984    match run_output("git", args) {
985        Ok(output) => Some(output),
986        Err(err) => {
987            eprintln!("{err}");
988            None
989        }
990    }
991}
992
993fn run_output(cmd: &str, args: &[&str]) -> Result<Output, String> {
994    process::run_output(cmd, args)
995        .map(|output| output.into_std_output())
996        .map_err(|err| format!("spawn {cmd}: {err}"))
997}
998
999fn git_stdout_trimmed(args: &[&str]) -> Result<String, i32> {
1000    let output = run_git_output(args).ok_or(1)?;
1001    if !output.status.success() {
1002        emit_output(&output);
1003        return Err(exit_code(&output));
1004    }
1005    Ok(trim_trailing_newlines(&String::from_utf8_lossy(&output.stdout)).to_string())
1006}
1007
1008fn git_stdout_trimmed_optional(args: &[&str]) -> Option<String> {
1009    let output = run_git_output(args)?;
1010    if !output.status.success() {
1011        return None;
1012    }
1013    let value = trim_trailing_newlines(&String::from_utf8_lossy(&output.stdout)).to_string();
1014    if value.is_empty() { None } else { Some(value) }
1015}
1016
1017fn git_status_success(args: &[&str]) -> bool {
1018    run_git_output(args)
1019        .map(|output| output.status.success())
1020        .unwrap_or(false)
1021}
1022
1023fn trim_trailing_newlines(input: &str) -> &str {
1024    input.trim_end_matches(['\n', '\r'])
1025}
1026
1027fn exit_code(output: &Output) -> i32 {
1028    output.status.code().unwrap_or(1)
1029}
1030
1031fn emit_output(output: &Output) {
1032    let _ = io::stdout().write_all(&output.stdout);
1033    let _ = io::stderr().write_all(&output.stderr);
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038    use super::*;
1039    use pretty_assertions::assert_eq;
1040
1041    fn args(values: &[&str]) -> Vec<String> {
1042        values.iter().map(|value| (*value).to_string()).collect()
1043    }
1044
1045    #[test]
1046    fn normalize_remote_url_supports_common_git_forms() {
1047        assert_eq!(
1048            normalize_remote_url_from_raw("git@github.com:acme/repo.git"),
1049            Some("https://github.com/acme/repo".to_string())
1050        );
1051        assert_eq!(
1052            normalize_remote_url_from_raw("ssh://git@gitlab.com/group/repo.git"),
1053            Some("https://gitlab.com/group/repo".to_string())
1054        );
1055        assert_eq!(
1056            normalize_remote_url_from_raw("https://github.com/acme/repo.git/"),
1057            Some("https://github.com/acme/repo".to_string())
1058        );
1059    }
1060
1061    #[test]
1062    fn normalize_remote_url_rejects_non_http_like_sources() {
1063        assert_eq!(normalize_remote_url_from_raw("../relative/path"), None);
1064        assert_eq!(normalize_remote_url_from_raw("/tmp/repo.git"), None);
1065        assert_eq!(normalize_remote_url_from_raw(""), None);
1066    }
1067
1068    #[test]
1069    fn provider_detection_matches_hosts() {
1070        assert_eq!(
1071            Provider::from_base_url("https://github.com/acme/repo"),
1072            Provider::Github
1073        );
1074        assert_eq!(
1075            Provider::from_base_url("https://gitlab.com/acme/repo"),
1076            Provider::Gitlab
1077        );
1078        assert_eq!(
1079            Provider::from_base_url("https://gitlab.internal/acme/repo"),
1080            Provider::Gitlab
1081        );
1082        assert_eq!(
1083            Provider::from_base_url("https://code.example.com/acme/repo"),
1084            Provider::Generic
1085        );
1086    }
1087
1088    #[test]
1089    fn github_slug_parses_owner_repo() {
1090        assert_eq!(
1091            github_repo_slug("https://github.com/acme/repo"),
1092            Some("acme/repo".to_string())
1093        );
1094        assert_eq!(
1095            github_repo_slug("https://github.com/acme/repo/sub/path"),
1096            Some("acme/repo".to_string())
1097        );
1098        assert_eq!(github_repo_slug("https://github.com/acme"), None);
1099    }
1100
1101    #[test]
1102    fn percent_encode_supports_paths_and_queries() {
1103        assert_eq!(
1104            percent_encode("docs/read me.md", true),
1105            "docs/read%20me.md".to_string()
1106        );
1107        assert_eq!(
1108            percent_encode("workflow:CI Build", false),
1109            "workflow%3ACI%20Build".to_string()
1110        );
1111    }
1112
1113    #[test]
1114    fn url_builders_follow_provider_conventions() {
1115        assert_eq!(
1116            tree_url(Provider::Github, "https://github.com/acme/repo", "main"),
1117            "https://github.com/acme/repo/tree/main"
1118        );
1119        assert_eq!(
1120            tree_url(Provider::Gitlab, "https://gitlab.com/acme/repo", "main"),
1121            "https://gitlab.com/acme/repo/-/tree/main"
1122        );
1123        assert_eq!(
1124            release_tag_url(Provider::Github, "https://github.com/acme/repo", "v1.2.3"),
1125            "https://github.com/acme/repo/releases/tag/v1.2.3"
1126        );
1127        assert_eq!(
1128            release_tag_url(Provider::Gitlab, "https://gitlab.com/acme/repo", "v1.2.3"),
1129            "https://gitlab.com/acme/repo/-/releases/v1.2.3"
1130        );
1131    }
1132
1133    #[test]
1134    fn parse_positive_number_accepts_hash_prefix() {
1135        assert_eq!(parse_positive_number("#123", "PR"), Ok("123".to_string()));
1136        assert_eq!(parse_positive_number("42", "issue"), Ok("42".to_string()));
1137        assert_eq!(parse_positive_number("abc", "PR"), Err(2));
1138    }
1139
1140    #[test]
1141    fn open_commands_reject_too_many_args_before_git_lookups() {
1142        assert_eq!(open_repo(&args(&["origin", "extra"])), 2);
1143        assert_eq!(open_branch(&args(&["main", "extra"])), 2);
1144        assert_eq!(open_default_branch(&args(&["origin", "extra"])), 2);
1145        assert_eq!(open_commit(&args(&["HEAD", "extra"])), 2);
1146        assert_eq!(open_compare(&args(&["base", "head", "extra"])), 2);
1147        assert_eq!(open_pr(&args(&["1", "extra"])), 2);
1148        assert_eq!(open_pulls(&args(&["1", "extra"])), 2);
1149        assert_eq!(open_issues(&args(&["1", "extra"])), 2);
1150        assert_eq!(open_actions(&args(&["ci.yml", "extra"])), 2);
1151        assert_eq!(open_releases(&args(&["v1.0.0", "extra"])), 2);
1152        assert_eq!(open_tags(&args(&["v1.0.0", "extra"])), 2);
1153        assert_eq!(open_commits(&args(&["main", "extra"])), 2);
1154        assert_eq!(open_file(&args(&["src/lib.rs", "main", "extra"])), 2);
1155        assert_eq!(open_blame(&args(&["src/lib.rs", "main", "extra"])), 2);
1156    }
1157
1158    #[test]
1159    fn open_commands_help_paths_return_zero_without_repo() {
1160        assert_eq!(open_repo(&args(&["--help"])), 0);
1161        assert_eq!(open_branch(&args(&["-h"])), 0);
1162        assert_eq!(open_default_branch(&args(&["help"])), 0);
1163        assert_eq!(open_commit(&args(&["--help"])), 0);
1164        assert_eq!(open_pr(&args(&["help"])), 0);
1165        assert_eq!(open_actions(&args(&["--help"])), 0);
1166        assert_eq!(open_releases(&args(&["--help"])), 0);
1167        assert_eq!(open_tags(&args(&["--help"])), 0);
1168        assert_eq!(open_commits(&args(&["--help"])), 0);
1169    }
1170
1171    #[test]
1172    fn open_file_and_blame_require_path_argument() {
1173        assert_eq!(open_file(&args(&[])), 2);
1174        assert_eq!(open_blame(&args(&[])), 2);
1175    }
1176
1177    #[test]
1178    fn normalize_remote_url_handles_additional_variants() {
1179        assert_eq!(
1180            normalize_remote_url_from_raw("https://token@github.com/acme/repo.git"),
1181            Some("https://github.com/acme/repo".to_string())
1182        );
1183        assert_eq!(
1184            normalize_remote_url_from_raw("ssh://git@gitlab.com"),
1185            Some("https://gitlab.com".to_string())
1186        );
1187        assert_eq!(
1188            normalize_remote_url_from_raw("git://gitlab.com/group/repo.git"),
1189            Some("https://gitlab.com/group/repo".to_string())
1190        );
1191        assert_eq!(
1192            normalize_remote_url_from_raw("git@github.com:acme/repo"),
1193            Some("https://github.com/acme/repo".to_string())
1194        );
1195        assert_eq!(
1196            normalize_remote_url_from_raw("user@gitlab.com/acme/repo.git"),
1197            Some("https://gitlab.com/acme/repo".to_string())
1198        );
1199        assert_eq!(normalize_remote_url_from_raw("ssh://git@/acme/repo"), None);
1200        assert_eq!(normalize_remote_url_from_raw("file:///tmp/repo.git"), None);
1201    }
1202
1203    #[test]
1204    fn helper_functions_cover_url_and_path_variants() {
1205        assert_eq!(normalize_repo_path("./docs/read me.md"), "docs/read me.md");
1206        assert_eq!(normalize_repo_path("/src/lib.rs"), "src/lib.rs");
1207        assert!(is_yaml_workflow("ci.yml"));
1208        assert!(is_yaml_workflow("ci.yaml"));
1209        assert!(!is_yaml_workflow("ci.json"));
1210        assert_eq!(strip_userinfo("git@github.com"), "github.com");
1211        assert_eq!(
1212            host_from_url("HTTPS://User@Example.COM/repo"),
1213            "user@example.com"
1214        );
1215        assert_eq!(trim_trailing_newlines("line\r\n"), "line");
1216        assert!(is_help_token("help"));
1217        assert!(!is_help_token("--version"));
1218        assert_eq!(
1219            github_repo_slug("github.com/acme/repo"),
1220            Some("acme/repo".to_string())
1221        );
1222        assert_eq!(github_repo_slug("https://github.com"), None);
1223    }
1224
1225    #[test]
1226    fn remaining_url_builders_cover_gitlab_and_generic_paths() {
1227        assert_eq!(
1228            commit_url(
1229                Provider::Generic,
1230                "https://code.example.com/acme/repo",
1231                "abc123"
1232            ),
1233            "https://code.example.com/acme/repo/commit/abc123"
1234        );
1235        assert_eq!(
1236            compare_url(
1237                Provider::Gitlab,
1238                "https://gitlab.com/acme/repo",
1239                "main",
1240                "feature"
1241            ),
1242            "https://gitlab.com/acme/repo/-/compare/main...feature"
1243        );
1244        assert_eq!(
1245            blob_url(
1246                Provider::Gitlab,
1247                "https://gitlab.com/acme/repo",
1248                "main",
1249                "dir/file name.rs"
1250            ),
1251            "https://gitlab.com/acme/repo/-/blob/main/dir/file%20name.rs"
1252        );
1253        assert_eq!(
1254            blame_url(
1255                Provider::Generic,
1256                "https://code.example.com/acme/repo",
1257                "main",
1258                "dir/file name.rs"
1259            ),
1260            "https://code.example.com/acme/repo/blame/main/dir/file%20name.rs"
1261        );
1262        assert_eq!(
1263            commits_url(Provider::Gitlab, "https://gitlab.com/acme/repo", "main"),
1264            "https://gitlab.com/acme/repo/-/commits/main"
1265        );
1266    }
1267}