|
1
|
//! Working-directory git awareness. |
|
2
|
//! |
|
3
|
//! The point of a `gh`-style CLI is that you rarely have to name the repo — it |
|
4
|
//! reads the one you're standing in. This module answers two questions about |
|
5
|
//! the current directory: which sigit.si repo does it point at, and what branch |
|
6
|
//! is checked out. |
|
7
|
|
|
8
|
use { |
|
9
|
anyhow::{anyhow, Context, Result}, |
|
10
|
git2::Repository as GitRepository, |
|
11
|
std::{fmt, path::Path}, |
|
12
|
}; |
|
13
|
|
|
14
|
/// An `owner/name` pair identifying a repository on sigit.si. |
|
15
|
#[derive(Debug, Clone, PartialEq, Eq)] |
|
16
|
pub struct RepoSlug { |
|
17
|
pub owner: String, |
|
18
|
pub name: String, |
|
19
|
} |
|
20
|
|
|
21
|
impl RepoSlug { |
|
22
|
/// Parse the `owner/name` form users type into `--repo`. |
|
23
|
pub fn parse(input: &str) -> Result<Self> { |
|
24
|
let trimmed = input.trim().trim_matches('/'); |
|
25
|
let mut parts = trimmed.splitn(2, '/'); |
|
26
|
let owner = parts.next().unwrap_or_default().trim(); |
|
27
|
let name = parts.next().unwrap_or_default().trim(); |
|
28
|
|
|
29
|
if owner.is_empty() || name.is_empty() || name.contains('/') { |
|
30
|
return Err(anyhow!( |
|
31
|
"Expected a repository in OWNER/NAME form, got {input:?}." |
|
32
|
)); |
|
33
|
} |
|
34
|
|
|
35
|
Ok(Self { |
|
36
|
owner: owner.to_string(), |
|
37
|
name: name.trim_end_matches(".git").to_string(), |
|
38
|
}) |
|
39
|
} |
|
40
|
} |
|
41
|
|
|
42
|
impl fmt::Display for RepoSlug { |
|
43
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
|
44
|
write!(f, "{}/{}", self.owner, self.name) |
|
45
|
} |
|
46
|
} |
|
47
|
|
|
48
|
/// Find the sigit.si repository the given directory belongs to. |
|
49
|
/// |
|
50
|
/// Remotes are searched in preference order — `origin`, then `sigit`, then |
|
51
|
/// whatever else is configured — and only remotes whose host matches `host` are |
|
52
|
/// considered, so a repo with both a GitHub and a sigit.si remote resolves to |
|
53
|
/// the sigit.si one. |
|
54
|
pub fn current_repo(dir: &Path, host: &str) -> Result<RepoSlug> { |
|
55
|
let repository = GitRepository::discover(dir) |
|
56
|
.context("Not inside a git repository. Pass --repo OWNER/NAME instead.")?; |
|
57
|
|
|
58
|
let remotes = repository |
|
59
|
.remotes() |
|
60
|
.context("Could not read this repository's remotes.")?; |
|
61
|
|
|
62
|
let names: Vec<String> = remotes.iter().flatten().map(str::to_string).collect(); |
|
63
|
|
|
64
|
for candidate in preferred_order(&names) { |
|
65
|
let Ok(remote) = repository.find_remote(&candidate) else { |
|
66
|
continue; |
|
67
|
}; |
|
68
|
let Some(url) = remote.url() else { continue }; |
|
69
|
if let Some(slug) = slug_from_url(url, host) { |
|
70
|
return Ok(slug); |
|
71
|
} |
|
72
|
} |
|
73
|
|
|
74
|
Err(anyhow!( |
|
75
|
"No {host} remote found in this repository. Pass --repo OWNER/NAME instead." |
|
76
|
)) |
|
77
|
} |
|
78
|
|
|
79
|
/// The branch currently checked out, or `None` on a detached HEAD. |
|
80
|
pub fn current_branch(dir: &Path) -> Option<String> { |
|
81
|
let repository = GitRepository::discover(dir).ok()?; |
|
82
|
let head = repository.head().ok()?; |
|
83
|
if !head.is_branch() { |
|
84
|
return None; |
|
85
|
} |
|
86
|
head.shorthand().map(str::to_string) |
|
87
|
} |
|
88
|
|
|
89
|
/// Resolve a ref (or `HEAD`) in the repository around `dir` to a full commit |
|
90
|
/// SHA. A full SHA that this checkout doesn't have is passed through, since |
|
91
|
/// the commit may only exist on the server. |
|
92
|
pub fn resolve_sha(dir: &Path, rev: &str) -> Result<String> { |
|
93
|
let found = GitRepository::discover(dir).ok().and_then(|repository| { |
|
94
|
let object = repository.revparse_single(rev).ok()?; |
|
95
|
Some(object.peel_to_commit().ok()?.id().to_string()) |
|
96
|
}); |
|
97
|
|
|
98
|
match found { |
|
99
|
Some(sha) => Ok(sha), |
|
100
|
None if is_full_sha(rev) => Ok(rev.to_ascii_lowercase()), |
|
101
|
None => Err(anyhow!( |
|
102
|
"Could not resolve {rev:?} to a commit. Run this inside a clone of the repository, \ |
|
103
|
or pass the full commit SHA." |
|
104
|
)), |
|
105
|
} |
|
106
|
} |
|
107
|
|
|
108
|
fn is_full_sha(text: &str) -> bool { |
|
109
|
text.len() == 40 && text.chars().all(|c| c.is_ascii_hexdigit()) |
|
110
|
} |
|
111
|
|
|
112
|
/// `origin` first, then `sigit`, then the rest in their configured order. |
|
113
|
fn preferred_order(names: &[String]) -> Vec<String> { |
|
114
|
let mut ordered = Vec::with_capacity(names.len()); |
|
115
|
for preferred in ["origin", "sigit"] { |
|
116
|
if names.iter().any(|n| n == preferred) { |
|
117
|
ordered.push(preferred.to_string()); |
|
118
|
} |
|
119
|
} |
|
120
|
for name in names { |
|
121
|
if !ordered.contains(name) { |
|
122
|
ordered.push(name.clone()); |
|
123
|
} |
|
124
|
} |
|
125
|
ordered |
|
126
|
} |
|
127
|
|
|
128
|
/// Pull `owner/name` out of a remote URL, but only when it points at `host`. |
|
129
|
/// |
|
130
|
/// Handles the three shapes git remotes come in: `https://host/owner/repo.git`, |
|
131
|
/// `git@host:owner/repo.git`, and `ssh://git@host/owner/repo.git`. |
|
132
|
fn slug_from_url(url: &str, host: &str) -> Option<RepoSlug> { |
|
133
|
let url = url.trim(); |
|
134
|
let (url_host, path) = split_host_and_path(url)?; |
|
135
|
|
|
136
|
if !hosts_match(&url_host, host) { |
|
137
|
return None; |
|
138
|
} |
|
139
|
|
|
140
|
RepoSlug::parse(path.trim_matches('/')).ok() |
|
141
|
} |
|
142
|
|
|
143
|
fn split_host_and_path(url: &str) -> Option<(String, String)> { |
|
144
|
if let Some(rest) = url.split_once("://").map(|(_, rest)| rest) { |
|
145
|
// scheme://[user@]host[:port]/path |
|
146
|
let rest = rest.split_once('@').map_or(rest, |(_, after)| after); |
|
147
|
let (authority, path) = rest.split_once('/')?; |
|
148
|
return Some((authority.to_string(), path.to_string())); |
|
149
|
} |
|
150
|
|
|
151
|
// scp-like: [user@]host:path |
|
152
|
let rest = url.split_once('@').map_or(url, |(_, after)| after); |
|
153
|
let (authority, path) = rest.split_once(':')?; |
|
154
|
Some((authority.to_string(), path.to_string())) |
|
155
|
} |
|
156
|
|
|
157
|
/// Compare hosts ignoring the port and a leading `www.`, so a dev remote on |
|
158
|
/// `localhost:3000` matches a `localhost` base URL and vice versa. |
|
159
|
pub fn hosts_match(a: &str, b: &str) -> bool { |
|
160
|
fn normalize(host: &str) -> String { |
|
161
|
let host = host.trim().to_ascii_lowercase(); |
|
162
|
let host = host |
|
163
|
.rsplit_once("://") |
|
164
|
.map_or(host.as_str(), |(_, rest)| rest); |
|
165
|
let host = host.split('/').next().unwrap_or(host); |
|
166
|
let host = host.split(':').next().unwrap_or(host); |
|
167
|
host.trim_start_matches("www.").to_string() |
|
168
|
} |
|
169
|
|
|
170
|
normalize(a) == normalize(b) |
|
171
|
} |
|
172
|
|
|
173
|
#[cfg(test)] |
|
174
|
mod tests { |
|
175
|
use super::*; |
|
176
|
|
|
177
|
#[test] |
|
178
|
fn slugs_parse_from_the_owner_name_form() { |
|
179
|
let slug = RepoSlug::parse("seto/sigit-si").unwrap(); |
|
180
|
assert_eq!(slug.owner, "seto"); |
|
181
|
assert_eq!(slug.name, "sigit-si"); |
|
182
|
assert_eq!(slug.to_string(), "seto/sigit-si"); |
|
183
|
} |
|
184
|
|
|
185
|
#[test] |
|
186
|
fn a_trailing_git_suffix_is_dropped() { |
|
187
|
assert_eq!( |
|
188
|
RepoSlug::parse("seto/sigit-si.git").unwrap().name, |
|
189
|
"sigit-si" |
|
190
|
); |
|
191
|
} |
|
192
|
|
|
193
|
#[test] |
|
194
|
fn dotted_repo_names_survive() { |
|
195
|
// The server allows names like "Qwen2.5-3B-Instruct-GGUF". |
|
196
|
let slug = RepoSlug::parse("seto/Qwen2.5-3B-Instruct-GGUF").unwrap(); |
|
197
|
assert_eq!(slug.name, "Qwen2.5-3B-Instruct-GGUF"); |
|
198
|
} |
|
199
|
|
|
200
|
#[test] |
|
201
|
fn incomplete_slugs_are_rejected() { |
|
202
|
assert!(RepoSlug::parse("sigit-si").is_err()); |
|
203
|
assert!(RepoSlug::parse("seto/").is_err()); |
|
204
|
assert!(RepoSlug::parse("/sigit-si").is_err()); |
|
205
|
assert!(RepoSlug::parse("a/b/c").is_err()); |
|
206
|
} |
|
207
|
|
|
208
|
#[test] |
|
209
|
fn https_remotes_resolve() { |
|
210
|
let slug = slug_from_url("https://sigit.si/seto/sigit-si.git", "https://sigit.si").unwrap(); |
|
211
|
assert_eq!(slug.to_string(), "seto/sigit-si"); |
|
212
|
} |
|
213
|
|
|
214
|
#[test] |
|
215
|
fn scp_style_ssh_remotes_resolve() { |
|
216
|
let slug = slug_from_url("git@sigit.si:seto/sigit-si.git", "sigit.si").unwrap(); |
|
217
|
assert_eq!(slug.to_string(), "seto/sigit-si"); |
|
218
|
} |
|
219
|
|
|
220
|
#[test] |
|
221
|
fn ssh_url_remotes_resolve() { |
|
222
|
let slug = slug_from_url("ssh://git@sigit.si/seto/sigit-si.git", "sigit.si").unwrap(); |
|
223
|
assert_eq!(slug.to_string(), "seto/sigit-si"); |
|
224
|
} |
|
225
|
|
|
226
|
#[test] |
|
227
|
fn remotes_on_another_host_are_ignored() { |
|
228
|
// The whole point: a repo mirrored from GitHub must not resolve to its |
|
229
|
// GitHub remote when we asked for the sigit.si one. |
|
230
|
assert!(slug_from_url("git@github.com:seto/sigit-si.git", "sigit.si").is_none()); |
|
231
|
assert!( |
|
232
|
slug_from_url("https://github.com/seto/sigit-si.git", "https://sigit.si").is_none() |
|
233
|
); |
|
234
|
} |
|
235
|
|
|
236
|
#[test] |
|
237
|
fn dev_remotes_match_regardless_of_port() { |
|
238
|
let slug = slug_from_url( |
|
239
|
"http://localhost:3000/seto/demo.git", |
|
240
|
"http://localhost:3000", |
|
241
|
) |
|
242
|
.unwrap(); |
|
243
|
assert_eq!(slug.to_string(), "seto/demo"); |
|
244
|
} |
|
245
|
|
|
246
|
#[test] |
|
247
|
fn a_ref_resolves_to_its_commit() { |
|
248
|
let dir = tempfile::tempdir().unwrap(); |
|
249
|
let repository = GitRepository::init(dir.path()).unwrap(); |
|
250
|
let signature = git2::Signature::now("t", "t@example.com").unwrap(); |
|
251
|
let tree = repository |
|
252
|
.find_tree(repository.treebuilder(None).unwrap().write().unwrap()) |
|
253
|
.unwrap(); |
|
254
|
let id = repository |
|
255
|
.commit(Some("HEAD"), &signature, &signature, "init", &tree, &[]) |
|
256
|
.unwrap(); |
|
257
|
|
|
258
|
assert_eq!(resolve_sha(dir.path(), "HEAD").unwrap(), id.to_string()); |
|
259
|
} |
|
260
|
|
|
261
|
#[test] |
|
262
|
fn an_unknown_full_sha_is_passed_through() { |
|
263
|
let dir = tempfile::tempdir().unwrap(); |
|
264
|
let sha = "A".repeat(40); |
|
265
|
assert_eq!(resolve_sha(dir.path(), &sha).unwrap(), "a".repeat(40)); |
|
266
|
} |
|
267
|
|
|
268
|
#[test] |
|
269
|
fn an_unknown_ref_is_an_error() { |
|
270
|
let dir = tempfile::tempdir().unwrap(); |
|
271
|
assert!(resolve_sha(dir.path(), "main").is_err()); |
|
272
|
} |
|
273
|
|
|
274
|
#[test] |
|
275
|
fn origin_is_tried_before_other_remotes() { |
|
276
|
let names = vec!["upstream".to_string(), "origin".to_string()]; |
|
277
|
assert_eq!(preferred_order(&names).first().unwrap(), "origin"); |
|
278
|
} |
|
279
|
|
|
280
|
#[test] |
|
281
|
fn every_remote_is_still_considered() { |
|
282
|
let names = vec!["upstream".to_string(), "origin".to_string()]; |
|
283
|
assert_eq!(preferred_order(&names).len(), 2); |
|
284
|
} |
|
285
|
} |