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        return Default::default();
21    });
22    let mut repo = git::Repo::new(&path);
23
24    if let OpenTarget::Branch(branch_name) = &target {
25        if !repo.exist(remote_name, branch_name) {
26            eprintln!("Error: Branch '{}' not found in remote '{}'", branch_name, remote_name);
27            return;
28        }
29    }
30
31    let mut target = target;
32    if let Ok(current_branch) = repo.current_branch() {
33        target = OpenTarget::Branch(current_branch);
34    }
35
36    match get_remote(remote_name) {
37        Ok(remote) => {
38            let url = match target {
39                OpenTarget::Remote => remote.get_repo_url(),
40                OpenTarget::Commit(commit_id) => remote.get_commit_url(&commit_id),
41                OpenTarget::Branch(branch_name) => remote.get_branch_url(&branch_name),
42            };
43            open::that(url).unwrap_or_else(|_| eprintln!("Failed to open URL"))
44        }
45        Err(e) => eprintln!("{}", e),
46    }
47}