summaryrefslogtreecommitdiffstats
path: root/repo_url/src/repo.rs
blob: a03a7ebb929ab445894845ab680c41b186e37728 (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use std::borrow::Cow;
use std::convert::TryFrom;
use url;
use url::Url;

pub type GResult<T> = Result<T, GitError>;

#[derive(Debug, Clone)]
pub struct Repo {
    // as set by the create author
    pub url: Url,
    pub host: RepoHost,
}

#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum RepoHost {
    GitHub(SimpleRepo),
    GitLab(SimpleRepo),
    BitBucket(SimpleRepo),
    Other,
}

#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct SimpleRepo {
    pub owner: Box<str>,
    pub repo: Box<str>,
}

impl SimpleRepo {
    pub fn new(owner: impl Into<Box<str>>, repo: impl Into<Box<str>>) -> Self {
        Self {
            owner: owner.into(),
            repo: repo.into(),
        }
    }
}

#[derive(Debug, Clone)]
pub enum GitError {
    IncompleteUrl,
    InvalidUrl(url::ParseError),
}

impl std::error::Error for GitError {
    fn description(&self) -> &str {"git"}
}

impl std::fmt::Display for GitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            GitError::IncompleteUrl => f.write_str("Incomplete URL"),
            GitError::InvalidUrl(e) => e.fmt(f),
        }
    }
}

impl Repo {
    /// Parse the given URL
    pub fn new(url: &str) -> GResult<Self> {
        let url = Url::parse(url).map_err(|e| GitError::InvalidUrl(e))?;
        Ok(Repo {
            host: match (&url.host_str(), url.path_segments()) {
                (Some("www.github.com"), Some(path)) |
                (Some("github.com"), Some(path)) => {
                    RepoHost::GitHub(Self::repo_from_path(path)?)
                },
                (Some("www.gitlab.com"), Some(path)) |
                (Some("gitlab.com"), Some(path)) => {
                    RepoHost::GitLab(Self::repo_from_path(path)?)
                },
                (Some("bitbucket.org"), Some(path)) => {
                    RepoHost::BitBucket(Self::repo_from_path(path)?)
                },
                _ => RepoHost::Other,
            },
            url,
        })
    }

    fn repo_from_path<'a>(mut path: impl Iterator<Item = &'a str>) -> GResult<SimpleRepo> {
        Ok(SimpleRepo {
            owner: path.next().ok_or(GitError::IncompleteUrl)?.to_ascii_lowercase().into_boxed_str(),
            repo: path.next().ok_or(GitError::IncompleteUrl)?.trim_end_matches(".git").to_ascii_lowercase().into_boxed_str(),
        })
    }

    /// True if the URL may be a well-known git repository URL
    pub fn looks_like_repo_url(url: &str) -> bool {
        Url::parse(url).ok().map_or(false, |url| match url.host_str() {
            Some("github.com") | Some("www.github.com") => true,
            Some("gitlab.com") | Some("www.gitlab.com") => true,
            Some("bitbucket.org") => true,
            _ => false,
        })
    }

    pub fn raw_url(&self) -> &str {
        self.url.as_str()
    }

    /// Enum with details of git hosting service
    pub fn host(&self) -> &RepoHost {
        &self.host
    }

    /// URL to view who contributed to the repository
    pub fn contributors_http_url(&self) -> Cow<'_, str> {
        match self.host {
            RepoHost::GitHub(SimpleRepo {ref owner, ref repo}) => {
                format!("https://github.com/{}/{}/graphs/contributors", owner, repo).into()
            },
            RepoHost::GitLab(SimpleRepo {ref owner, ref repo}) => {
                format!("https://gitlab.com/{}/{}/graphs/master", owner, repo).into()
            },
            RepoHost::BitBucket(SimpleRepo {ref owner, ref repo}) => {
                // not really…
                format!("https://bitbucket.org/{}/{}/commits/all", owner, repo).into()
            },
            RepoHost::Other => self.url.as_str().into(),
        }
    }

    /// Name of the hosting service
    pub fn site_link_label(&self) -> &'static str {
        match self.host {
            RepoHost::GitHub(..) => "GitHub",
            RepoHost::GitLab(..) => "GitLab",
            RepoHost::BitBucket(..) => "BitBucket",
            RepoHost::Other => "Source Code",
        }
    }

    /// URL for links in readmes hosted on the git website
    ///
    /// Base dir is without leading or trailing `/`, i.e. `""` for root, `"foo/bar"`, etc.
    pub fn readme_base_url(&self, base_dir_in_repo: &str) -> String {
        assert!(!base_dir_in_repo.starts_with('/'));
        let slash = if base_dir_in_repo != "" && !base_dir_in_repo.ends_with('/') { "/" } else { "" };
        match self.host {
            RepoHost::GitHub(SimpleRepo {ref owner, ref repo}) => {
                format!("https://github.com/{}/{}/blob/master/{}{}", owner, repo, base_dir_in_repo, slash)
            },
            RepoHost::GitLab(SimpleRepo {ref owner, ref repo}) => {
                format!("https://gitlab.com/{}/{}/blob/master/{}{}", owner, repo, base_dir_in_repo, slash)
            },
            RepoHost::BitBucket(_) |  // FIXME: needs commit hash!
            RepoHost::Other => self.url.to_string() // FIXME: how to add base dir?
        }
    }

    /// URL for image embeds in readmes hosted on the git website
    ///
    /// Base dir is without leading or trailing `/`, i.e. `""` for root, `"foo/bar"`, etc.
    pub fn readme_base_image_url(&self, base_dir_in_repo: &str) -> String {
        assert!(!base_dir_in_repo.starts_with('/'));
        let slash = if base_dir_in_repo != "" && !base_dir_in_repo.ends_with('/') { "/" } else { "" };
        match self.host {
            RepoHost::GitHub(SimpleRepo {ref owner, ref repo}) => {
                format!("https://raw.githubusercontent.com/{}/{}/master/{}{}", owner, repo, base_dir_in_repo, slash)
            },
            RepoHost::GitLab(SimpleRepo {ref owner, ref repo}) => {
                format!("https://gitlab.com/{}/{}/raw/master/{}{}", owner, repo, base_dir_in_repo, slash)
            },
            RepoHost::BitBucket(_) |  // FIXME: needs commit hash!
            RepoHost::Other => self.url.to_string() // FIXME: how to add base dir?
        }
    }

    /// URL for browsing the repository via web browser
    pub fn canonical_http_url(&self, base_dir_in_repo: &str) -> Cow<'_, str> {
        self.host.canonical_http_url(base_dir_in_repo)
            .unwrap_or_else(|| self.url.as_str().into()) // FIXME: how to add base dir?
    }

    pub fn canonical_git_url(&self) -> Cow<'_, str> {
        match self.host.canonical_git_url() {
            Some(s) => s.into(),
            None => self.url.as_str().into(),
        }
    }

    pub fn owner_name(&self) -> Option<&str> {
        self.host.owner_name()
    }

    pub fn repo_name(&self) -> Option<&str> {
        self.host.repo_name()
    }
}

impl RepoHost {
    /// URL for cloning the repository via git
    pub fn canonical_git_url(&self) -> Option<String> {
        match self {
            RepoHost::GitHub(SimpleRepo {ref owner, ref repo}) => {
                Some(format!("https://github.com/{}/{}.git", owner, repo))
            },
            RepoHost::GitLab(SimpleRepo {ref owner, ref repo}) => {
                Some(format!("https://gitlab.com/{}/{}.git", owner, repo))
            },
            RepoHost::BitBucket(SimpleRepo {ref owner, ref repo}) => {
                Some(format!("https://bitbucket.org/{}/{}", owner, repo))
            },
            RepoHost::Other => None,
        }
    }

    /// URL for browsing the repository via web browser
    pub fn canonical_http_url(&self, base_dir_in_repo: &str) -> Option<Cow<'_, str>> {
        assert!(!base_dir_in_repo.starts_with('/'));
        let slash = if base_dir_in_repo != "" { "/tree/master/" } else { "" };
        match self {
            RepoHost::GitHub(