codeberg_cli/types/
git.rs

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
use std::path::PathBuf;

use anyhow::Context;
use git2::{Remote, Repository};

pub struct OwnerRepo {
    pub owner: String,
    pub repo: String,
}

pub struct Git {
    pub repo: Option<Repository>,
}

impl Default for Git {
    fn default() -> Self {
        Self {
            repo: Repository::open("./.").ok(),
        }
    }
}

impl Git {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn remotes(&self) -> anyhow::Result<Vec<Remote>> {
        let repo = self
            .repo
            .as_ref()
            .context("No repository found in the current path even though one is needed!")?;
        let remotes = repo
            .remotes()?
            .into_iter()
            .filter_map(|remote| {
                let remote = remote?;
                let remote = repo.find_remote(remote).ok()?;
                Some(remote)
            })
            .collect::<Vec<_>>();
        Ok(remotes)
    }

    pub fn owner_repo(&self) -> anyhow::Result<OwnerRepo> {
        let remotes = self
            .remotes()?
            .into_iter()
            .filter_map(|remote| {
                let mut git_url = remote.url().map(PathBuf::from)?;
                // expect urls like
                //
                // - git@codeberg.org:UserName/RepoName.git
                // - https://codeberg.org/UserName/RepoName.git
                let repo = git_url
                    .file_name()?
                    .to_str()?
                    .trim_end_matches(".git")
                    .to_owned();
                git_url.pop();

                let https_owner = git_url
                    .file_name()?
                    .to_str()
                    .filter(|owner| !owner.contains(":"))
                    .map(|owner| owner.to_owned());
                let ssh_owner = git_url
                    .to_str()?
                    .split_once(":")
                    .map(|(_junk, owner)| owner.to_owned());
                let remote_name = remote.name()?.to_owned();
                Some((remote_name, https_owner.or(ssh_owner)?, repo))
            })
            .inspect(|x| tracing::debug!("{x:?}"))
            .collect::<Vec<_>>();

        remotes
            .iter()
            .find_map(|(name, owner, repo)| (*name == "origin").then_some((owner, repo)))
            .or_else(|| remotes.first().map(|(_, owner, repo)| (owner, repo)))
            .map(|(owner, repo)| OwnerRepo {
                owner: owner.clone(),
                repo: repo.clone(),
            })
            .context("Couldn't find owner and repo")
    }
}