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 request_actions;
86#[cfg(feature = "hosting")]
87pub mod resolve;
88#[cfg(feature = "hosting")]
89pub mod review;
90pub mod scope;
91#[cfg(all(
92 test,
93 any(
94 feature = "github",
95 feature = "gitlab",
96 feature = "gitea",
97 feature = "azure-devops",
98 feature = "bitbucket",
99 feature = "gerrit"
100 )
101))]
102mod scope_fake;
103#[cfg(any(
104 feature = "github",
105 feature = "gitlab",
106 feature = "gitea",
107 feature = "azure-devops",
108 feature = "bitbucket",
109 feature = "gerrit"
110))]
111mod scope_handle;
112#[cfg(feature = "github")]
113mod scoped_transport;
114pub mod spec;
115pub mod ssh_key;
116#[cfg(feature = "trello")]
117pub mod trello;
118pub mod trust;
119pub mod updates;
120mod web_url;
121pub mod xrefs;
122#[cfg(feature = "youtrack")]
123pub mod youtrack;
124
125#[cfg(feature = "hosting")]
126pub use account::{
127 AccountCache, AccountIssue, AccountItems, AccountPr, AccountQuery, CachedAccount, ACCOUNT_TTL,
128 ACCOUNT_TTL_SECS,
129};
130pub use auth::{auth_headers, git_username};
131#[cfg(feature = "hosting")]
132pub use client::{
133 client_for, issue_web_url, pull_request_edit_url, pull_request_head_ref, pull_request_web_url,
134 token_create_url, web_base as integration_web_base, CreatedIssue, CreatedPullRequest,
135 HostingClient, NewIssue, NewPullRequest, UnsupportedClient,
136};
137#[cfg(feature = "network")]
138pub use conditional::shared_network_transport;
139pub use conditional::{shared_rate_note, ConditionalTransport};
140#[cfg(feature = "github")]
141pub use github::GitHubClient;
142#[cfg(feature = "gitlab")]
143pub use gitlab::GitLabClient;
144#[cfg(feature = "network")]
145pub use http::ReqwestTransport;
146pub use http::{HttpBytes, HttpRequest, HttpResponse, HttpTransport, Method, RecordedTransport};
147pub use integration::{
148 resolve_local_folder, token_env_var, DefaultTokenSource, Integration, IntegrationKind,
149 StaticToken, TokenSource,
150};
151#[cfg(feature = "hosting")]
152pub use issue_flow::{CreatedBranch, IssueLinks, NewIssueBranch};
153#[cfg(feature = "hosting")]
154pub use metadata::{
155 list_delta, HostedLabel, HostedMilestone, IssueEdit, ItemMeta, MetaKind, PrEdit,
156};
157#[cfg(feature = "hosting")]
158pub use model::{
159 best_pull_request, excess_scopes, is_dangerous_scope, ChecksState, Choice, HostedUser,
160 IssueCreateOptions, IssueFilter, IssueState, IssueSummary, PrFilter, PullRequestState,
161 PullRequestSummary, StateFilter, TokenCheck, TokenFlavor,
162};
163#[cfg(feature = "hosting")]
164pub use project::{HostedProject, HostedSshKey};
165#[cfg(feature = "hosting")]
166pub use request_actions::{request_actions, strip_draft_prefix, MergeMethod, RequestActions};
167#[cfg(feature = "hosting")]
168pub use resolve::{resolve_for_repo, suggest_for_repo, Resolution, ResolveRemote, Suggestion};
169#[cfg(feature = "hosting")]
170pub use review::{
171 review_base_ref, review_base_refspec, review_compare_ref, review_compare_refspec,
172 review_head_ref, review_head_refspec, review_head_refspec_at, DiffSide, FileStatus, MergeState,
173 PatchSet, PendingComment, PullRequestDetail, ReviewCapabilities, ReviewComment, ReviewEvent,
174 ReviewFile, ReviewOutcome, ReviewState, ReviewSubmission, ReviewThread, ReviewVote,
175 SubmittedReview, VoteLabel, VoteValue,
176};
177pub use scope::{install as install_repo_scopes, RepoScopes};
178#[cfg(feature = "hosting")]
179pub use spec::CheckoutSource;
180pub use spec::{spec_for, FamilySpec, RemoteRef};
181pub use trust::{Account, TrustGate, TrustProblem, TrustSubject};
182pub use web_url::{
183 new_issue_form_url, new_pull_request_form_url, percent_encode_component, PullRequestForm,
184 MAX_URL_LEN, TRUNCATION_NOTE,
185};
186
187pub type Result<T> = std::result::Result<T, Error>;
188
189#[derive(Debug, thiserror::Error)]
190pub enum Error {
191 #[error("unrecognized hosting provider for url: {0}")]
192 UnrecognizedProvider(String),
193
194 #[error("`{0}` is not a usable base url for a hosting instance")]
195 BadUrl(String),
196
197 #[error("no integration configured with id `{0}`")]
198 UnknownIntegration(String),
199
200 #[error(
204 "no token for integration `{id}`: nothing in the credential helper for {host}, \
205 and {env_var} is unset (config points at token_ref `{token_ref}`)"
206 )]
207 NoToken {
208 id: String,
209 token_ref: String,
210 env_var: String,
211 host: String,
212 },
213
214 #[error("{what} failed: the host rejected the token ({detail})")]
215 Unauthorized { what: String, detail: String },
216
217 #[error("{what} failed: the token lacks the required scope ({detail})")]
218 Forbidden { what: String, detail: String },
219
220 #[error("{what} failed with HTTP {status}: {detail}")]
221 Api {
222 what: String,
223 status: u16,
224 detail: String,
225 },
226
227 #[error("{host}: rate limit reached, try again in {}", crate::conditional::wait_text(*retry_in_secs))]
229 RateLimited { host: String, retry_in_secs: u64 },
230
231 #[error("http error: {0}")]
232 Http(String),
233
234 #[error("the host's response could not be decoded: {0}")]
235 Decode(String),
236
237 #[error("{0} is not supported yet: no client exists for it")]
239 NotImplemented(String),
240
241 #[error("`{0}` is not supported by this client")]
243 Unsupported(String),
244
245 #[error("ssh key error: {0}")]
246 Ssh(String),
247
248 #[error("{0}")]
250 Local(String),
251
252 #[error("{0}")]
254 Trust(trust::TrustProblem),
255
256 #[error("the integration trust store is unusable: {0}")]
260 TrustStore(String),
261
262 #[error("{}", scope::ASSIGNMENT_BLOCKED)]
264 AssignmentBlocked,
265
266 #[error("the token belongs to a GitHub App (a bot), not to a person")]
270 BotToken,
271}
272
273pub fn match_integration<'a>(
282 remote_url: &str,
283 integrations: &'a [Integration],
284) -> Option<&'a Integration> {
285 let host = host_of_remote(remote_url)?;
286 integrations.iter().find(|i| {
289 i.host().is_some_and(|h| {
290 let name = h
291 .rsplit_once(':')
292 .filter(|(_, p)| p.bytes().all(|b| b.is_ascii_digit()))
293 .map_or(h.as_str(), |(n, _)| n);
294 name.eq_ignore_ascii_case(&host)
295 })
296 })
297}
298
299fn host_of_remote(remote_url: &str) -> Option<String> {
305 let remote = remote_url.trim();
306 if remote.is_empty() {
307 return None;
308 }
309 let after_scheme = remote.split_once("://").map(|(_, r)| r).unwrap_or(remote);
310 let after_user = after_scheme
312 .rsplit_once('@')
313 .map(|(_, r)| r)
314 .unwrap_or(after_scheme);
315 let end = after_user.find(['/', ':']).unwrap_or(after_user.len());
318 let host = after_user[..end].trim();
319 (!host.is_empty()).then(|| host.to_ascii_lowercase())
320}
321
322pub fn remote_web_base(remote_url: &str) -> Option<(String, String)> {
333 let remote = remote_url.trim();
334 if remote.is_empty() {
335 return None;
336 }
337 let host = host_of_remote(remote)?;
338 let has_scheme = remote.contains("://");
341 let after_scheme = remote.split_once("://").map(|(_, r)| r).unwrap_or(remote);
342 let after_user = after_scheme
343 .rsplit_once('@')
344 .map(|(_, r)| r)
345 .unwrap_or(after_scheme);
346 let end = after_user.find(['/', ':']).unwrap_or(after_user.len());
349 let mut rest = &after_user[end..];
350 let mut port = None;
354 if has_scheme {
355 if let Some(stripped) = rest.strip_prefix(':') {
356 let path_start = stripped.find('/').unwrap_or(stripped.len());
357 port = Some(&stripped[..path_start]);
358 rest = &stripped[path_start..];
359 }
360 }
361 let path = rest.trim_start_matches(['/', ':']).trim_end_matches('/');
362 let path = path.strip_suffix(".git").unwrap_or(path);
363 if path.is_empty() {
364 return None;
365 }
366 let scheme = remote
370 .split_once("://")
371 .map(|(s, _)| s.to_ascii_lowercase())
372 .unwrap_or_default();
373 let base = match (scheme.as_str(), port) {
374 ("http" | "https", Some(port)) if port.bytes().all(|b| b.is_ascii_digit()) => {
375 format!("{scheme}://{host}:{port}")
376 }
377 ("http" | "https", _) => format!("{scheme}://{host}"),
378 _ => format!("https://{host}"),
379 };
380 Some((base, path.to_string()))
381}
382
383pub fn web_base_for(integration: Option<&Integration>, web_base: String) -> String {
388 let Some(integration) = integration else {
389 return web_base;
390 };
391 let Some((scheme, rest)) = integration.url.trim().split_once("://") else {
392 return web_base;
393 };
394 let authority = rest.split('/').next().unwrap_or("");
395 let bare = |x: &str| {
396 let x = x.split_once("://").map_or(x, |(_, r)| r);
397 let x = x.split('/').next().unwrap_or("");
398 x.rsplit_once(':')
399 .filter(|(_, p)| p.bytes().all(|b| b.is_ascii_digit()))
400 .map_or(x, |(h, _)| h)
401 .to_ascii_lowercase()
402 };
403 if authority.is_empty() || bare(authority) != bare(&web_base) {
404 return web_base;
405 }
406 format!("{}://{authority}", scheme.to_ascii_lowercase())
407}
408
409pub fn well_known_kind(web_base: &str) -> Option<IntegrationKind> {
414 let host = web_base
415 .trim_start_matches("https://")
416 .trim_start_matches("http://")
417 .to_ascii_lowercase();
418 [
419 gitpoulpi_config::ApiFamily::Github,
420 gitpoulpi_config::ApiFamily::Gitlab,
421 gitpoulpi_config::ApiFamily::AzureDevops,
422 gitpoulpi_config::ApiFamily::Bitbucket,
423 gitpoulpi_config::ApiFamily::Gitea,
424 ]
425 .into_iter()
426 .find_map(|family| (spec::spec_for(family).well_known)(&host))
427}
428
429fn percent_encode_branch(name: &str) -> String {
434 let mut out = String::with_capacity(name.len());
435 for b in name.bytes() {
436 match b {
437 b'%' => out.push_str("%25"),
438 b'#' => out.push_str("%23"),
439 b'&' => out.push_str("%26"),
440 b' ' => out.push_str("%20"),
441 _ => out.push(b as char),
442 }
443 }
444 out
445}
446
447pub fn new_pull_request_url(
455 kind: IntegrationKind,
456 web_base: &str,
457 project: &str,
458 source: &str,
459 target: Option<&str>,
460) -> String {
461 let spec = spec::spec_for(kind.family());
462 (spec.new_pr_url)(web_base, project, source, target)
464 .or_else(|| {
465 (spec::spec_for(gitpoulpi_config::ApiFamily::Gitlab).new_pr_url)(
466 web_base, project, source, target,
467 )
468 })
469 .unwrap_or_default()
470}
471
472#[cfg(test)]
473mod tests {
474 use super::*;
475
476 fn integrations() -> Vec<Integration> {
477 vec![
478 Integration::new("gh", IntegrationKind::Github, "https://github.com"),
479 Integration::new(
480 "corp",
481 IntegrationKind::Gitlab,
482 "https://gitlab.example.com",
483 ),
484 ]
485 }
486
487 #[test]
491 fn every_remote_spelling_of_one_host_matches_its_integration() {
492 let integrations = integrations();
493 for remote in [
494 "https://gitlab.example.com/group/thing.git",
495 "ssh://git@gitlab.example.com/group/thing.git",
496 "git@gitlab.example.com:group/thing.git",
497 "ssh://git@gitlab.example.com:2222/group/thing.git",
498 "HTTPS://GitLab.Example.COM/group/thing.git",
499 ] {
500 let found = match_integration(remote, &integrations);
501 assert_eq!(found.map(|i| i.id.as_str()), Some("corp"), "{remote}");
502 }
503 }
504
505 #[test]
506 fn an_unconfigured_host_matches_nothing() {
507 assert!(match_integration("https://bitbucket.org/a/b.git", &integrations()).is_none());
508 assert!(match_integration("", &integrations()).is_none());
509 assert!(match_integration(" ", &integrations()).is_none());
510 }
511
512 #[test]
513 fn github_and_gitlab_do_not_match_each_other() {
514 let integrations = integrations();
515 let found = match_integration("git@github.com:me/thing.git", &integrations);
516 assert_eq!(found.map(|i| i.id.as_str()), Some("gh"));
517 }
518
519 #[test]
524 fn web_base_from_every_remote_spelling() {
525 for remote in [
526 "https://gitlab.example.com/group/sub/proj.git",
527 "https://gitlab.example.com/group/sub/proj",
528 "ssh://git@gitlab.example.com/group/sub/proj.git",
529 "ssh://git@gitlab.example.com:2222/group/sub/proj.git",
530 "git@gitlab.example.com:group/sub/proj.git",
531 ] {
532 assert_eq!(
533 remote_web_base(remote),
534 Some((
535 "https://gitlab.example.com".to_string(),
536 "group/sub/proj".to_string()
537 )),
538 "{remote}"
539 );
540 }
541 assert_eq!(
542 remote_web_base("https://github.com/me/thing.git"),
543 Some(("https://github.com".to_string(), "me/thing".to_string()))
544 );
545 assert_eq!(remote_web_base(""), None);
546 assert_eq!(remote_web_base("not a url"), None);
547 }
548
549 #[test]
553 fn web_base_keeps_the_scheme_and_port_of_an_http_remote() {
554 for (remote, base) in [
555 ("http://localhost:3000/o/r.git", "http://localhost:3000"),
556 ("http://gitea:3000/o/r", "http://gitea:3000"),
557 (
558 "http://me:tok@192.168.1.10:8080/o/r.git",
559 "http://192.168.1.10:8080",
560 ),
561 ("https://host.corp:8443/o/r.git", "https://host.corp:8443"),
562 ("HTTP://Nas/o/r.git", "http://nas"),
563 ("ssh://git@nas:2222/o/r.git", "https://nas"),
565 ("git@nas:o/r.git", "https://nas"),
566 ] {
567 assert_eq!(
568 remote_web_base(remote),
569 Some((base.to_string(), "o/r".to_string())),
570 "{remote}"
571 );
572 }
573 }
574
575 #[test]
578 fn a_profile_url_sets_the_web_base_of_its_own_host() {
579 let gitea = Integration::new("g", IntegrationKind::Gitea, "http://nas:3000/");
580 assert_eq!(
581 web_base_for(Some(&gitea), "https://nas".to_string()),
582 "http://nas:3000"
583 );
584 assert_eq!(
585 web_base_for(Some(&gitea), "https://elsewhere".to_string()),
586 "https://elsewhere"
587 );
588 assert_eq!(web_base_for(None, "https://nas".to_string()), "https://nas");
589 }
590
591 #[test]
594 fn an_http_profile_matches_http_and_ssh_remotes() {
595 let ints = vec![Integration::new(
596 "g",
597 IntegrationKind::Gitea,
598 "http://nas:3000",
599 )];
600 for remote in [
601 "http://nas:3000/o/r.git",
602 "ssh://git@nas:2222/o/r.git",
603 "git@nas:o/r.git",
604 ] {
605 assert!(match_integration(remote, &ints).is_some(), "{remote}");
606 }
607 }
608
609 #[test]
610 fn well_known_kind_recognises_github_and_gitlab_but_nothing_else() {
611 assert_eq!(
612 well_known_kind("https://github.com"),
613 Some(IntegrationKind::Github)
614 );
615 assert_eq!(
616 well_known_kind("https://gitlab.com"),
617 Some(IntegrationKind::Gitlab)
618 );
619 assert_eq!(well_known_kind("https://gitlab.example.com"), None);
620 #[cfg(feature = "bitbucket")]
621 assert_eq!(
622 well_known_kind("https://bitbucket.org"),
623 Some(IntegrationKind::Bitbucket)
624 );
625 assert_eq!(well_known_kind("https://bitbucket.example.com"), None);
626 }
627
628 #[test]
633 fn new_pull_request_url_encodes_slashes_and_ampersands() {
634 let gh = new_pull_request_url(
635 IntegrationKind::Github,
636 "https://github.com",
637 "me/thing",
638 "feature & fix #1",
639 Some("main"),
640 );
641 assert_eq!(
642 gh,
643 "https://github.com/me/thing/compare/main...feature%20%26%20fix%20%231?expand=1"
644 );
645 assert_eq!(
646 new_pull_request_url(
647 IntegrationKind::Github,
648 "https://github.com",
649 "me/thing",
650 "feature",
651 None
652 ),
653 "https://github.com/me/thing/compare/feature?expand=1"
654 );
655
656 let gl = new_pull_request_url(
657 IntegrationKind::Gitlab,
658 "https://gitlab.example.com",
659 "group/sub/proj",
660 "feature/login",
661 Some("main"),
662 );
663 assert_eq!(
664 gl,
665 "https://gitlab.example.com/group/sub/proj/-/merge_requests/new?merge_request%5Bsource_branch%5D=feature/login&merge_request%5Btarget_branch%5D=main"
666 );
667 assert_eq!(
668 new_pull_request_url(
669 IntegrationKind::Gitlab,
670 "https://gitlab.example.com",
671 "group/proj",
672 "feature",
673 None
674 ),
675 "https://gitlab.example.com/group/proj/-/merge_requests/new?merge_request%5Bsource_branch%5D=feature"
676 );
677 }
678}