git_github/
open.rs

1use crate::git;
2use std::env;
3
4pub enum OpenTarget {
5    Remote,
6    Commit(String),
7    Branch(String),
8}
9
10fn get_remote(remote_name: &str) -> Result<crate::url::Remote, String> {
11    let path = env::current_dir().map_err(|_| "Failed to get current directory")?;
12    let repo = git::Repo::new(&path);
13    repo.remote(remote_name)
14        .map_err(|_| format!("Error: Remote '{}' not found", remote_name))
15}
16
17pub fn open(remote_name: &str, target: OpenTarget) {
18    let path = env::current_dir().unwrap_or_else(|_| {
19        eprintln!("Failed to get current directory");
20        Default::default()
21    });
22    let repo = git::Repo::new(&path);
23
24    if let OpenTarget::Branch(branch_name) = &target {
25        if !repo.exist(remote_name, branch_name) {
26            eprintln!(
27                "Error: Branch '{}' not found in remote '{}'",
28                branch_name, remote_name
29            );
30            return;
31        }
32    }
33
34    let mut target = target;
35    if let Ok(current_branch) = repo.current_branch() {
36        target = OpenTarget::Branch(current_branch);
37    }
38
39    match get_remote(remote_name) {
40        Ok(remote) => {
41            let url = match target {
42                OpenTarget::Remote => remote.get_repo_url(),
43                OpenTarget::Commit(commit_id) => remote.get_commit_url(&commit_id),
44                OpenTarget::Branch(branch_name) => remote.get_branch_url(&branch_name),
45            };
46            open::that(url).unwrap_or_else(|_| eprintln!("Failed to open URL"))
47        }
48        Err(e) => eprintln!("{}", e),
49    }
50}