1use gitpoulpi_config::{Integration, IntegrationCategory};
21
22use crate::spec::{spec_for, RemoteRef};
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct ResolveRemote {
27 pub name: String,
28 pub url: String,
29}
30
31impl ResolveRemote {
32 pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
33 Self {
34 name: name.into(),
35 url: url.into(),
36 }
37 }
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Resolution<'a> {
42 pub integration: &'a Integration,
43 pub remote: String,
45 pub project_path: String,
47 pub ambiguous: bool,
49}
50
51fn owned_by(integration: &Integration, url: &str) -> Option<RemoteRef> {
53 let spec = spec_for(integration.kind.family());
54 let remote = (spec.parse_remote)(url)?;
55 (spec.owns_remote)(integration, &remote).then_some(remote)
56}
57
58fn is_hosting(integration: &Integration) -> bool {
59 integration.enabled && integration.kind.category() == IntegrationCategory::Hosting
60}
61
62fn remote_order(remotes: &[ResolveRemote]) -> Vec<&ResolveRemote> {
63 let mut ordered: Vec<&ResolveRemote> = Vec::with_capacity(remotes.len());
64 for special in ["upstream", "origin"] {
65 ordered.extend(remotes.iter().filter(|r| r.name == special));
66 }
67 ordered.extend(
68 remotes
69 .iter()
70 .filter(|r| r.name != "upstream" && r.name != "origin"),
71 );
72 ordered
73}
74
75pub fn resolve_for_repo<'a>(
76 remotes: &[ResolveRemote],
77 integrations: &'a [Integration],
78 override_id: Option<&str>,
79) -> Option<Resolution<'a>> {
80 let ordered = remote_order(remotes);
81
82 if let Some(id) = override_id {
83 if let Some(chosen) = integrations.iter().find(|i| i.id == id && is_hosting(i)) {
86 let spec = spec_for(chosen.kind.family());
87 let pick = ordered
88 .iter()
89 .find_map(|r| owned_by(chosen, &r.url).map(|p| (r, p)))
90 .or_else(|| {
91 ordered
92 .iter()
93 .find_map(|r| (spec.parse_remote)(&r.url).map(|p| (r, p)))
94 })?;
95 return Some(Resolution {
96 integration: chosen,
97 remote: pick.0.name.clone(),
98 project_path: pick.1.project,
99 ambiguous: false,
100 });
101 }
102 }
103
104 for remote in &ordered {
105 let candidates: Vec<(&Integration, RemoteRef)> = integrations
106 .iter()
107 .filter(|i| is_hosting(i))
108 .filter_map(|i| owned_by(i, &remote.url).map(|r| (i, r)))
109 .collect();
110 if candidates.is_empty() {
111 continue;
112 }
113 let namespace = candidates[0].1.project.split('/').next().unwrap_or("");
114 let owner = candidates.iter().find(|(i, _)| {
115 i.user
116 .as_ref()
117 .is_some_and(|u| !u.login.is_empty() && u.login.eq_ignore_ascii_case(namespace))
118 });
119 let (chosen, parsed) = owner.unwrap_or(&candidates[0]);
120 return Some(Resolution {
121 integration: chosen,
122 remote: remote.name.clone(),
123 project_path: parsed.project.clone(),
124 ambiguous: candidates.len() > 1,
125 });
126 }
127 None
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133 use gitpoulpi_config::{ConnectedUser, IntegrationKind};
134
135 fn gl(id: &str, url: &str) -> Integration {
136 Integration::new(id, IntegrationKind::GitlabSelfManaged, url)
137 }
138
139 fn with_user(mut i: Integration, login: &str) -> Integration {
140 i.user = Some(ConnectedUser {
141 login: login.into(),
142 ..Default::default()
143 });
144 i
145 }
146
147 fn origin(url: &str) -> Vec<ResolveRemote> {
148 vec![ResolveRemote::new("origin", url)]
149 }
150
151 #[test]
152 fn two_self_managed_hosts_resolve_by_host() {
153 let ints = vec![
154 gl("a", "https://gitlab.a.example"),
155 gl("b", "https://gitlab.b.example"),
156 ];
157 let r = resolve_for_repo(&origin("git@gitlab.b.example:g/sub/p.git"), &ints, None).unwrap();
158 assert_eq!(r.integration.id, "b");
159 assert_eq!(r.project_path, "g/sub/p");
160 assert_eq!(r.remote, "origin");
161 assert!(!r.ambiguous);
162 }
163
164 #[test]
165 fn every_remote_spelling_reaches_the_same_profile() {
166 let ints = vec![gl("corp", "https://gitlab.example.com")];
167 for url in [
168 "https://gitlab.example.com/g/p.git",
169 "https://gitlab.example.com:8443/g/p.git",
170 "ssh://git@gitlab.example.com:2222/g/p.git",
171 "git@gitlab.example.com:g/p.git",
172 "HTTPS://GitLab.Example.COM/g/p",
173 ] {
174 let r = resolve_for_repo(&origin(url), &ints, None).unwrap();
175 assert_eq!(r.integration.id, "corp", "{url}");
176 assert_eq!(r.project_path, "g/p", "{url}");
177 }
178 }
179
180 #[test]
181 fn a_profile_url_with_a_port_still_matches() {
182 let ints = vec![gl("corp", "https://gitlab.example.com:8443")];
183 assert!(resolve_for_repo(&origin("git@gitlab.example.com:g/p.git"), &ints, None).is_some());
184 }
185
186 #[test]
187 fn two_users_on_one_host_prefer_the_namespace_owner() {
188 let ints = vec![
189 with_user(gl("work", "https://gitlab.example.com"), "corp"),
190 with_user(gl("me", "https://gitlab.example.com"), "sg"),
191 ];
192 let r = resolve_for_repo(
193 &origin("https://gitlab.example.com/sg/thing.git"),
194 &ints,
195 None,
196 )
197 .unwrap();
198 assert_eq!(r.integration.id, "me");
199 assert!(r.ambiguous);
200
201 let r = resolve_for_repo(
202 &origin("https://gitlab.example.com/other/thing.git"),
203 &ints,
204 None,
205 )
206 .unwrap();
207 assert_eq!(
208 r.integration.id, "work",
209 "first configured when nobody owns it"
210 );
211 assert!(r.ambiguous);
212 }
213
214 #[test]
215 fn an_override_beats_the_automatic_choice() {
216 let ints = vec![
217 with_user(gl("work", "https://gitlab.example.com"), "corp"),
218 with_user(gl("me", "https://gitlab.example.com"), "sg"),
219 ];
220 let r = resolve_for_repo(
221 &origin("https://gitlab.example.com/sg/t.git"),
222 &ints,
223 Some("work"),
224 )
225 .unwrap();
226 assert_eq!(r.integration.id, "work");
227 assert!(!r.ambiguous);
228 }
229
230 #[test]
231 fn a_stale_or_disabled_override_falls_back_to_automatic() {
232 let mut off = gl("off", "https://gitlab.example.com");
233 off.enabled = false;
234 let ints = vec![off, gl("on", "https://gitlab.example.com")];
235 for id in ["deleted", "off"] {
236 let r = resolve_for_repo(
237 &origin("https://gitlab.example.com/g/p.git"),
238 &ints,
239 Some(id),
240 )
241 .unwrap();
242 assert_eq!(r.integration.id, "on", "{id}");
243 }
244 }
245
246 #[test]
247 fn upstream_is_tried_before_origin_before_the_rest() {
248 let ints = vec![
249 gl("a", "https://gitlab.a.example"),
250 gl("b", "https://gitlab.b.example"),
251 ];
252 let remotes = vec![
253 ResolveRemote::new("zzz", "https://gitlab.b.example/z/p.git"),
254 ResolveRemote::new("origin", "https://gitlab.a.example/me/p.git"),
255 ResolveRemote::new("upstream", "https://gitlab.b.example/team/p.git"),
256 ];
257 let r = resolve_for_repo(&remotes, &ints, None).unwrap();
258 assert_eq!(
259 (r.integration.id.as_str(), r.remote.as_str()),
260 ("b", "upstream")
261 );
262 assert_eq!(r.project_path, "team/p");
263
264 let ints = vec![gl("b", "https://gitlab.b.example")];
266 let r = resolve_for_repo(&remotes, &ints, None).unwrap();
267 assert_eq!(r.remote, "upstream");
268 }
269
270 #[test]
271 fn unknown_hosts_disabled_profiles_and_issue_trackers_match_nothing() {
272 let mut off = gl("off", "https://gitlab.example.com");
273 off.enabled = false;
274 let jira = Integration::new(
275 "j",
276 IntegrationKind::JiraCloud,
277 "https://gitlab.example.com",
278 );
279 let ints = vec![off, jira];
280 assert!(
281 resolve_for_repo(&origin("https://gitlab.example.com/g/p.git"), &ints, None).is_none()
282 );
283 assert!(
284 resolve_for_repo(&origin("https://elsewhere.example/g/p.git"), &ints, None).is_none()
285 );
286 assert!(resolve_for_repo(&[], &ints, None).is_none());
287 }
288
289 #[test]
290 fn github_dot_com_matches_its_public_profile() {
291 let ints = vec![Integration::new(
292 "gh",
293 IntegrationKind::Github,
294 "https://github.com",
295 )];
296 let r = resolve_for_repo(&origin("git@github.com:me/thing.git"), &ints, None).unwrap();
297 assert_eq!(r.integration.id, "gh");
298 assert_eq!(r.project_path, "me/thing");
299 }
300}
301
302#[derive(Debug, Clone, PartialEq, Eq)]
306pub struct Suggestion {
307 pub integration_id: String,
308 pub remote: String,
309 pub project_path: String,
310}
311
312pub fn suggest_for_repo(
316 remotes: &[ResolveRemote],
317 integrations: &[Integration],
318) -> Vec<Suggestion> {
319 let mut ordered: Vec<&ResolveRemote> = Vec::with_capacity(remotes.len());
320 for special in ["origin", "upstream"] {
321 ordered.extend(remotes.iter().filter(|r| r.name == special));
322 }
323 ordered.extend(
324 remotes
325 .iter()
326 .filter(|r| r.name != "upstream" && r.name != "origin"),
327 );
328 let mut out: Vec<Suggestion> = Vec::new();
329 for remote in ordered {
330 for integration in integrations.iter().filter(|i| is_hosting(i)) {
331 let Some(parsed) = owned_by(integration, &remote.url) else {
332 continue;
333 };
334 let dup = out
335 .iter()
336 .any(|s| s.integration_id == integration.id && s.project_path == parsed.project);
337 if !dup {
338 out.push(Suggestion {
339 integration_id: integration.id.clone(),
340 remote: remote.name.clone(),
341 project_path: parsed.project,
342 });
343 }
344 }
345 }
346 out
347}