1#[cfg(feature = "hosting")]
26pub mod account;
27#[cfg(feature = "hosting")]
28mod assignment_guard;
29pub mod auth;
30#[cfg(feature = "azure-devops")]
31pub mod azure_devops;
32#[cfg(feature = "bitbucket")]
33pub mod bitbucket;
34#[cfg(feature = "hosting")]
35pub mod board;
36pub mod cache_search;
37#[cfg(feature = "hosting")]
38pub mod client;
39pub mod conditional;
40#[cfg(feature = "hosting")]
41pub mod conversation;
42#[cfg(feature = "hosting")]
43pub mod flow_engine;
44#[cfg(feature = "gerrit")]
45pub mod gerrit;
46#[cfg(feature = "gitea")]
47pub mod gitea;
48#[cfg(feature = "github")]
49pub mod github;
50#[cfg(feature = "github")]
51mod github_flow;
52#[cfg(feature = "github")]
53mod github_meta;
54#[cfg(feature = "gitlab")]
55pub mod gitlab;
56#[cfg(feature = "gitlab")]
57mod gitlab_flow;
58#[cfg(feature = "gitlab")]
59mod gitlab_meta;
60pub mod http;
61mod integration;
62#[cfg(feature = "hosting")]
63pub mod issue_flow;
64#[cfg(feature = "jira")]
65pub mod jira;
66#[cfg(feature = "linear")]
67pub mod linear;
68#[cfg(feature = "hosting")]
69pub mod list_cache;
70#[cfg(feature = "local-issues")]
71pub mod local_markdown;
72pub mod markup;
73#[cfg(feature = "hosting")]
74pub mod metadata;
75#[cfg(feature = "hosting")]
76pub mod model;
77#[cfg(feature = "hosting")]
78mod project;
79#[cfg(feature = "hosting")]
80pub mod protection;
81#[cfg(feature = "redmine")]
82pub mod redmine;
83pub mod refs;
84#[cfg(feature = "hosting")]
85pub mod resolve;
86#[cfg(feature = "hosting")]
87pub mod review;
88pub mod scope;
89#[cfg(all(
90 test,
91 any(
92 feature = "github",
93 feature = "gitlab",
94 feature = "gitea",
95 feature = "azure-devops",
96 feature = "bitbucket",
97 feature = "gerrit"
98 )
99))]
100mod scope_fake;
101#[cfg(any(
102 feature = "github",
103 feature = "gitlab",
104 feature = "gitea",
105 feature = "azure-devops",
106 feature = "bitbucket",
107 feature = "gerrit"
108))]
109mod scope_handle;
110#[cfg(feature = "github")]
111mod scoped_transport;
112pub mod spec;
113pub mod ssh_key;
114#[cfg(feature = "trello")]
115pub mod trello;
116pub mod trust;
117pub mod updates;
118mod web_url;
119pub mod xrefs;
120#[cfg(feature = "youtrack")]
121pub mod youtrack;
122
123#[cfg(feature = "hosting")]
124pub use account::{
125 AccountCache, AccountIssue, AccountItems, AccountPr, AccountQuery, CachedAccount, ACCOUNT_TTL,
126 ACCOUNT_TTL_SECS,
127};
128pub use auth::{auth_headers, git_username};
129#[cfg(feature = "hosting")]
130pub use client::{
131 client_for, issue_web_url, pull_request_edit_url, pull_request_head_ref, pull_request_web_url,
132 token_create_url, web_base as integration_web_base, CreatedIssue, CreatedPullRequest,
133 HostingClient, NewIssue, NewPullRequest, UnsupportedClient,
134};
135#[cfg(feature = "network")]
136pub use conditional::shared_network_transport;
137pub use conditional::{shared_rate_note, ConditionalTransport};
138#[cfg(feature = "github")]
139pub use github::GitHubClient;
140#[cfg(feature = "gitlab")]
141pub use gitlab::GitLabClient;
142#[cfg(feature = "network")]
143pub use http::ReqwestTransport;
144pub use http::{HttpRequest, HttpResponse, HttpTransport, Method, RecordedTransport};
145pub use integration::{
146 resolve_local_folder, token_env_var, DefaultTokenSource, Integration, IntegrationKind,
147 StaticToken, TokenSource,
148};
149#[cfg(feature = "hosting")]
150pub use issue_flow::{CreatedBranch, IssueLinks, NewIssueBranch};
151#[cfg(feature = "hosting")]
152pub use metadata::{
153 list_delta, HostedLabel, HostedMilestone, IssueEdit, ItemMeta, MetaKind, PrEdit,
154};
155#[cfg(feature = "hosting")]
156pub use model::{
157 best_pull_request, excess_scopes, is_dangerous_scope, ChecksState, Choice, HostedUser,
158 IssueCreateOptions, IssueFilter, IssueState, IssueSummary, PrFilter, PullRequestState,
159 PullRequestSummary, StateFilter, TokenCheck, TokenFlavor,
160};
161#[cfg(feature = "hosting")]
162pub use project::{HostedProject, HostedSshKey};
163#[cfg(feature = "hosting")]
164pub use resolve::{resolve_for_repo, suggest_for_repo, Resolution, ResolveRemote, Suggestion};
165#[cfg(feature = "hosting")]
166pub use review::{
167 review_base_ref, review_base_refspec, review_compare_ref, review_compare_refspec,
168 review_head_ref, review_head_refspec, review_head_refspec_at, DiffSide, FileStatus, MergeState,
169 PatchSet, PendingComment, PullRequestDetail, ReviewCapabilities, ReviewComment, ReviewEvent,
170 ReviewFile, ReviewOutcome, ReviewState, ReviewSubmission, ReviewThread, ReviewVote,
171 SubmittedReview, VoteLabel, VoteValue,
172};
173pub use scope::{install as install_repo_scopes, RepoScopes};
174#[cfg(feature = "hosting")]
175pub use spec::CheckoutSource;
176pub use spec::{spec_for, FamilySpec, RemoteRef};
177pub use trust::{Account, TrustGate, TrustProblem, TrustSubject};
178pub use web_url::{
179 new_issue_form_url, new_pull_request_form_url, percent_encode_component, PullRequestForm,
180 MAX_URL_LEN, TRUNCATION_NOTE,
181};
182
183pub type Result<T> = std::result::Result<T, Error>;
184
185#[derive(Debug, thiserror::Error)]
186pub enum Error {
187 #[error("unrecognized hosting provider for url: {0}")]
188 UnrecognizedProvider(String),
189
190 #[error("`{0}` is not a usable base url for a hosting instance")]
191 BadUrl(String),
192
193 #[error("no integration configured with id `{0}`")]
194 UnknownIntegration(String),
195
196 #[error(
200 "no token for integration `{id}`: nothing in the credential helper for {host}, \
201 and {env_var} is unset (config points at token_ref `{token_ref}`)"
202 )]
203 NoToken {
204 id: String,
205 token_ref: String,
206 env_var: String,
207 host: String,
208 },
209
210 #[error("{what} failed: the host rejected the token ({detail})")]
211 Unauthorized { what: String, detail: String },
212
213 #[error("{what} failed: the token lacks the required scope ({detail})")]
214 Forbidden { what: String, detail: String },
215
216 #[error("{what} failed with HTTP {status}: {detail}")]
217 Api {
218 what: String,
219 status: u16,
220 detail: String,
221 },
222
223 #[error("{host}: rate limit reached, try again in {}", crate::conditional::wait_text(*retry_in_secs))]
225 RateLimited { host: String, retry_in_secs: u64 },
226
227 #[error("http error: {0}")]
228 Http(String),
229
230 #[error("the host's response could not be decoded: {0}")]
231 Decode(String),
232
233 #[error("{0} is not supported yet: no client exists for it")]
235 NotImplemented(String),
236
237 #[error("`{0}` is not supported by this client")]
239 Unsupported(String),
240
241 #[error("ssh key error: {0}")]
242 Ssh(String),
243
244 #[error("{0}")]
246 Local(String),
247
248 #[error("{0}")]
250 Trust(trust::TrustProblem),
251
252 #[error("the integration trust store is unusable: {0}")]
256 TrustStore(String),
257
258 #[error("{}", scope::ASSIGNMENT_BLOCKED)]
260 AssignmentBlocked,
261
262 #[error("the token belongs to a GitHub App (a bot), not to a person")]
266 BotToken,
267}
268
269pub fn match_integration<'a>(
278 remote_url: &str,
279 integrations: &'a [Integration],
280) -> Option<&'a Integration> {
281 let host = host_of_remote(remote_url)?;
282 integrations.iter().find(|i| {
285 i.host().is_some_and(|h| {
286 let name = h
287 .rsplit_once(':')
288 .filter(|(_, p)| p.bytes().all(|b| b.is_ascii_digit()))
289 .map_or(h.as_str(), |(n, _)| n);
290 name.eq_ignore_ascii_case(&host)
291 })
292 })
293}
294
295fn host_of_remote(remote_url: &str) -> Option<String> {
301 let remote = remote_url.trim();
302 if remote.is_empty() {
303 return None;
304 }
305 let after_scheme = remote.split_once("://").map(|(_, r)| r).unwrap_or(remote);
306 let after_user = after_scheme
308 .rsplit_once('@')
309 .map(|(_, r)| r)
310 .unwrap_or(after_scheme);
311 let end = after_user.find(['/', ':']).unwrap_or(after_user.len());
314 let host = after_user[..end].trim();
315 (!host.is_empty()).then(|| host.to_ascii_lowercase())
316}
317
318pub fn remote_web_base(remote_url: &str) -> Option<(String, String)> {
329 let remote = remote_url.trim();
330 if remote.is_empty() {
331 return None;
332 }
333 let host = host_of_remote(remote)?;
334 let has_scheme = remote.contains("://");
337 let after_scheme = remote.split_once("://").map(|(_, r)| r).unwrap_or(remote);
338 let after_user = after_scheme
339 .rsplit_once('@')
340 .map(|(_, r)| r)
341 .unwrap_or(after_scheme);
342 let end = after_user.find(['/', ':']).unwrap_or(after_user.len());
345 let mut rest = &after_user[end..];
346 let mut port = None;
350 if has_scheme {
351 if let Some(stripped) = rest.strip_prefix(':') {
352 let path_start = stripped.find('/').unwrap_or(stripped.len());
353 port = Some(&stripped[..path_start]);
354 rest = &stripped[path_start..];
355 }
356 }
357 let path = rest.trim_start_matches(['/', ':']).trim_end_matches('/');
358 let path = path.strip_suffix(".git").unwrap_or(path);
359 if path.is_empty() {
360 return None;
361 }
362 let scheme = remote
366 .split_once("://")
367 .map(|(s, _)| s.to_ascii_lowercase())
368 .unwrap_or_default();
369 let base = match (scheme.as_str(), port) {
370 ("http" | "https", Some(port)) if port.bytes().all(|b| b.is_ascii_digit()) => {
371 format!("{scheme}://{host}:{port}")
372 }
373 ("http" | "https", _) => format!("{scheme}://{host}"),
374 _ => format!("https://{host}"),
375 };
376 Some((base, path.to_string()))
377}
378
379pub fn web_base_for(integration: Option<&Integration>, web_base: String) -> String {
384 let Some(integration) = integration else {
385 return web_base;
386 };
387 let Some((scheme, rest)) = integration.url.trim().split_once("://") else {
388 return web_base;
389 };
390 let authority = rest.split('/').next().unwrap_or("");
391 let bare = |x: &str| {
392 let x = x.split_once("://").map_or(x, |(_, r)| r);
393 let x = x.split('/').next().unwrap_or("");
394 x.rsplit_once(':')
395 .filter(|(_, p)| p.bytes().all(|b| b.is_ascii_digit()))
396 .map_or(x, |(h, _)| h)
397 .to_ascii_lowercase()
398 };
399 if authority.is_empty() || bare(authority) != bare(&web_base) {
400 return web_base;
401 }
402 format!("{}://{authority}", scheme.to_ascii_lowercase())
403}
404
405pub fn well_known_kind(web_base: &str) -> Option<IntegrationKind> {
410 let host = web_base
411 .trim_start_matches("https://")
412 .trim_start_matches("http://")
413 .to_ascii_lowercase();
414 [
415 gitpoulpi_config::ApiFamily::Github,
416 gitpoulpi_config::ApiFamily::Gitlab,
417 gitpoulpi_config::ApiFamily::AzureDevops,
418 gitpoulpi_config::ApiFamily::Bitbucket,
419 gitpoulpi_config::ApiFamily::Gitea,
420 ]
421 .into_iter()
422 .find_map(|family| (spec::spec_for(family).well_known)(&host))
423}
424
425fn percent_encode_branch(name: &str) -> String {
430 let mut out = String::with_capacity(name.len());
431 for b in name.bytes() {
432 match b {
433 b'%' => out.push_str("%25"),
434 b'#' => out.push_str("%23"),
435 b'&' => out.push_str("%26"),
436 b' ' => out.push_str("%20"),
437 _ => out.push(b as char),
438 }
439 }
440 out
441}
442
443pub fn new_pull_request_url(
451 kind: IntegrationKind,
452 web_base: &str,
453 project: &str,
454 source: &str,
455 target: Option<&str>,
456) -> String {
457 let spec = spec::spec_for(kind.family());
458 (spec.new_pr_url)(web_base, project, source, target)
460 .or_else(|| {
461 (spec::spec_for(gitpoulpi_config::ApiFamily::Gitlab).new_pr_url)(
462 web_base, project, source, target,
463 )
464 })
465 .unwrap_or_default()
466}
467
468#[cfg(test)]
469mod tests {
470 use super::*;
471
472 fn integrations() -> Vec<Integration> {
473 vec![
474 Integration::new("gh", IntegrationKind::Github, "https://github.com"),
475 Integration::new(
476 "corp",
477 IntegrationKind::Gitlab,
478 "https://gitlab.example.com",
479 ),
480 ]
481 }
482
483 #[test]
487 fn every_remote_spelling_of_one_host_matches_its_integration() {
488 let integrations = integrations();
489 for remote in [
490 "https://gitlab.example.com/group/thing.git",
491 "ssh://git@gitlab.example.com/group/thing.git",
492 "git@gitlab.example.com:group/thing.git",
493 "ssh://git@gitlab.example.com:2222/group/thing.git",
494 "HTTPS://GitLab.Example.COM/group/thing.git",
495 ] {
496 let found = match_integration(remote, &integrations);
497 assert_eq!(found.map(|i| i.id.as_str()), Some("corp"), "{remote}");
498 }
499 }
500
501 #[test]
502 fn an_unconfigured_host_matches_nothing() {
503 assert!(match_integration("https://bitbucket.org/a/b.git", &integrations()).is_none());
504 assert!(match_integration("", &integrations()).is_none());
505 assert!(match_integration(" ", &integrations()).is_none());
506 }
507
508 #[test]
509 fn github_and_gitlab_do_not_match_each_other() {
510 let integrations = integrations();
511 let found = match_integration("git@github.com:me/thing.git", &integrations);
512 assert_eq!(found.map(|i| i.id.as_str()), Some("gh"));
513 }
514
515 #[test]
520 fn web_base_from_every_remote_spelling() {
521 for remote in [
522 "https://gitlab.example.com/group/sub/proj.git",
523 "https://gitlab.example.com/group/sub/proj",
524 "ssh://git@gitlab.example.com/group/sub/proj.git",
525 "ssh://git@gitlab.example.com:2222/group/sub/proj.git",
526 "git@gitlab.example.com:group/sub/proj.git",
527 ] {
528 assert_eq!(
529 remote_web_base(remote),
530 Some((
531 "https://gitlab.example.com".to_string(),
532 "group/sub/proj".to_string()
533 )),
534 "{remote}"
535 );
536 }
537 assert_eq!(
538 remote_web_base("https://github.com/me/thing.git"),
539 Some(("https://github.com".to_string(), "me/thing".to_string()))
540 );
541 assert_eq!(remote_web_base(""), None);
542 assert_eq!(remote_web_base("not a url"), None);
543 }
544
545 #[test]
549 fn web_base_keeps_the_scheme_and_port_of_an_http_remote() {
550 for (remote, base) in [
551 ("http://localhost:3000/o/r.git", "http://localhost:3000"),
552 ("http://gitea:3000/o/r", "http://gitea:3000"),
553 (
554 "http://me:tok@192.168.1.10:8080/o/r.git",
555 "http://192.168.1.10:8080",
556 ),
557 ("https://host.corp:8443/o/r.git", "https://host.corp:8443"),
558 ("HTTP://Nas/o/r.git", "http://nas"),
559 ("ssh://git@nas:2222/o/r.git", "https://nas"),
561 ("git@nas:o/r.git", "https://nas"),
562 ] {
563 assert_eq!(
564 remote_web_base(remote),
565 Some((base.to_string(), "o/r".to_string())),
566 "{remote}"
567 );
568 }
569 }
570
571 #[test]
574 fn a_profile_url_sets_the_web_base_of_its_own_host() {
575 let gitea = Integration::new("g", IntegrationKind::Gitea, "http://nas:3000/");
576 assert_eq!(
577 web_base_for(Some(&gitea), "https://nas".to_string()),
578 "http://nas:3000"
579 );
580 assert_eq!(
581 web_base_for(Some(&gitea), "https://elsewhere".to_string()),
582 "https://elsewhere"
583 );
584 assert_eq!(web_base_for(None, "https://nas".to_string()), "https://nas");
585 }
586
587 #[test]
590 fn an_http_profile_matches_http_and_ssh_remotes() {
591 let ints = vec![Integration::new(
592 "g",
593 IntegrationKind::Gitea,
594 "http://nas:3000",
595 )];
596 for remote in [
597 "http://nas:3000/o/r.git",
598 "ssh://git@nas:2222/o/r.git",
599 "git@nas:o/r.git",
600 ] {
601 assert!(match_integration(remote, &ints).is_some(), "{remote}");
602 }
603 }
604
605 #[test]
606 fn well_known_kind_recognises_github_and_gitlab_but_nothing_else() {
607 assert_eq!(
608 well_known_kind("https://github.com"),
609 Some(IntegrationKind::Github)
610 );
611 assert_eq!(
612 well_known_kind("https://gitlab.com"),
613 Some(IntegrationKind::Gitlab)
614 );
615 assert_eq!(well_known_kind("https://gitlab.example.com"), None);
616 #[cfg(feature = "bitbucket")]
617 assert_eq!(
618 well_known_kind("https://bitbucket.org"),
619 Some(IntegrationKind::Bitbucket)
620 );
621 assert_eq!(well_known_kind("https://bitbucket.example.com"), None);
622 }
623
624 #[test]
629 fn new_pull_request_url_encodes_slashes_and_ampersands() {
630 let gh = new_pull_request_url(
631 IntegrationKind::Github,
632 "https://github.com",
633 "me/thing",
634 "feature & fix #1",
635 Some("main"),
636 );
637 assert_eq!(
638 gh,
639 "https://github.com/me/thing/compare/main...feature%20%26%20fix%20%231?expand=1"
640 );
641 assert_eq!(
642 new_pull_request_url(
643 IntegrationKind::Github,
644 "https://github.com",
645 "me/thing",
646 "feature",
647 None
648 ),
649 "https://github.com/me/thing/compare/feature?expand=1"
650 );
651
652 let gl = new_pull_request_url(
653 IntegrationKind::Gitlab,
654 "https://gitlab.example.com",
655 "group/sub/proj",
656 "feature/login",
657 Some("main"),
658 );
659 assert_eq!(
660 gl,
661 "https://gitlab.example.com/group/sub/proj/-/merge_requests/new?merge_request%5Bsource_branch%5D=feature/login&merge_request%5Btarget_branch%5D=main"
662 );
663 assert_eq!(
664 new_pull_request_url(
665 IntegrationKind::Gitlab,
666 "https://gitlab.example.com",
667 "group/proj",
668 "feature",
669 None
670 ),
671 "https://gitlab.example.com/group/proj/-/merge_requests/new?merge_request%5Bsource_branch%5D=feature"
672 );
673 }
674}