Skip to main content

gitpoulpi_hosting/
lib.rs

1//! Hosting and issue-tracker API clients: GitHub, GitLab, Gitea/Forgejo, Azure
2//! DevOps, Bitbucket, Gerrit, Jira, Trello, Linear, YouTrack, Redmine and local
3//! Markdown issues, including self-managed instances.
4//!
5//! Two jobs:
6//!
7//! 1. **List the projects a token can see, and clone straight from that
8//!    list.** [`HostingClient::list_projects`] returns a normalized
9//!    [`HostedProject`] whichever host produced it, and
10//!    [`HostedProject::clone_url`] hands the chosen row's URL to
11//!    `GitBackend::clone`.
12//! 2. **Generate an SSH key and upload it.** [`ssh_key`] makes the pair
13//!    in process (no `ssh-keygen` dependency, no prompt), and
14//!    [`HostingClient::upload_ssh_key`] registers the public half.
15//!
16//! Every network call goes through [`http::HttpTransport`], so the crate
17//! is testable with no network ([`http::RecordedTransport`]); only
18//! `ReqwestTransport`, behind the default `network` feature, opens a socket.
19//!
20//! An integration is a base URL plus a token reference, and the API root
21//! is *derived* from the base URL (see [`Integration::api_base`]) rather
22//! than configured separately, because two keys that must agree can
23//! disagree.
24
25#[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::{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    /// Deliberately verbose: every way of supplying the token is named,
201    /// because "no token" with no further detail is the error people
202    /// file issues about.
203    #[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    /// The host said to slow down (or we already know it is out of calls).
228    #[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    /// The kind is configurable but no client exists for it yet.
238    #[error("{0} is not supported yet: no client exists for it")]
239    NotImplemented(String),
240
241    /// The client exists but does not offer this operation.
242    #[error("`{0}` is not supported by this client")]
243    Unsupported(String),
244
245    #[error("ssh key error: {0}")]
246    Ssh(String),
247
248    /// The local Markdown issue source: a folder or note problem.
249    #[error("{0}")]
250    Local(String),
251
252    /// The integration trust check refused: nothing was sent.
253    #[error("{0}")]
254    Trust(trust::TrustProblem),
255
256    /// `trust.toml` could not be read or written. Refused rather than
257    /// treated as empty: an empty store would re-trust whatever the config
258    /// says now.
259    #[error("the integration trust store is unusable: {0}")]
260    TrustStore(String),
261
262    /// The repository blocks assignment: nothing was sent.
263    #[error("{}", scope::ASSIGNMENT_BLOCKED)]
264    AssignmentBlocked,
265
266    /// The token is a GitHub App installation token: it has no user behind
267    /// it, so `GET /user` (who am I) does not apply. Not a failure: the
268    /// actor is the App.
269    #[error("the token belongs to a GitHub App (a bot), not to a person")]
270    BotToken,
271}
272
273/// Which configured instance a remote URL belongs to, so a repository's
274/// `origin` can be linked back to the integration that can answer
275/// questions about it.
276///
277/// Compares hosts, not whole URLs: `git@gitlab.example.com:g/p.git` and
278/// `https://gitlab.example.com/g/p.git` are the same instance, and an
279/// integration configured as `https://gitlab.example.com` has to match
280/// both.
281pub 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    // A profile's host carries its port (`nas:3000`); the remote's does not
287    // (ssh and http differ in them), so compare the names only.
288    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
299/// The host part of any remote spelling git accepts.
300///
301/// Three shapes in the wild: `https://host/path`, `ssh://git@host/path`
302/// and the scp-like `git@host:path`, which is not a URL at all and is
303/// the one a naive `Url::parse` drops on the floor.
304fn 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    // Strip any `user@` / `user:password@` prefix.
311    let after_user = after_scheme
312        .rsplit_once('@')
313        .map(|(_, r)| r)
314        .unwrap_or(after_scheme);
315    // Whichever of `/` (url) or `:` (scp-like, and also a port) comes
316    // first ends the host.
317    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
322/// Splits a git remote URL into the host's *web* base (`https://host`,
323/// never the API root) and the project path (`group/sub/proj`), for
324/// building a pull/merge-request URL by hand.
325///
326/// Handles every spelling `host_of_remote` does - scp-like
327/// (`git@host:group/proj.git`), `ssh://` (a port, if any, is dropped and
328/// the scheme is `https`: the ssh daemon says nothing about the web UI)
329/// and `http(s)://` (scheme and port are the web UI's own, so a plain-http
330/// server in a container stays `http://host:3000`) - and always strips a
331/// trailing `.git`.
332pub 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    // Repeats `host_of_remote`'s scheme/user/host split so that everything
339    // after the host can be taken as the path; keep the two in step.
340    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    // The host ends at the first `/` or `:` (a port, or the scp-like
347    // separator); whichever it is, the path starts just after it.
348    let end = after_user.find(['/', ':']).unwrap_or(after_user.len());
349    let mut rest = &after_user[end..];
350    // A `:port` before the path (`ssh://` with an explicit port -- the
351    // colon there is a port, not the scp-like separator, which is only
352    // scheme-less `user@host:path`): drop it, keep the `/path`.
353    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    // An http(s) remote is the web UI's own address, scheme and port
367    // included (a self-hosted server is often plain http on a port);
368    // ssh and scp-like remotes say nothing about it, so https it is.
369    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
383/// `web_base` (from [`remote_web_base`]), moved to the address the
384/// matched profile says the server lives at when it is the same host:
385/// an ssh remote of a server configured as `http://host:3000` opens its
386/// web pages there, not on `https://host`.
387pub 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
409/// The two hosts recognized with no configuration at all: `github.com` /
410/// `gitlab.com` (or a `*.github.com` / `*.gitlab.com` subdomain), so a
411/// remote with no matching `[[integrations]]` entry still gets a usable
412/// compare/new-request URL.
413pub 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
429/// Percent-encodes the characters that would break a branch name out of a
430/// query-string value or URL path segment: `#`, `%`, `&` and space.
431/// Deliberately narrow: a legal git branch name cannot contain most other
432/// URL-unsafe characters.
433fn 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
447/// Builds the "open a compare/new pull-request page" URL by hand: the
448/// no-token fallback, and what a token-holding flow opens on success too
449/// (see [`client::HostingClient::create_pull_request`]).
450///
451/// `web_base` and `project` are `remote_web_base`'s output; `source` is the
452/// branch to merge from, `target` the branch to merge into (the host's
453/// default when `None`).
454pub 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    // A family with no URL of its own keeps the GitLab shape it always had.
463    (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    /// Every remote spelling of one instance must find the same
488    /// integration - especially the scp-like form, which is what an
489    /// SSH clone leaves in `.git/config`.
490    #[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    /// Every spelling a git remote can be typed in must yield the same
520    /// `https://host` web base and project path - this is what the
521    /// no-token compare/merge-request URL is built from, so getting it
522    /// wrong silently sends the user to the wrong page.
523    #[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    /// A self-hosted server is often plain http on a port (a Docker
550    /// container): an http(s) remote's own scheme and port are the web
551    /// UI's, so the compare / merge-request URL must not become https.
552    #[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 stays https on the default port: the daemon's port is not the web UI's.
564            ("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    /// An ssh remote of a profile configured as `http://host:port` still
576    /// opens the web UI where the profile says it is.
577    #[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    /// The profile matches an http remote with a port, and an ssh remote
592    /// of the same machine.
593    #[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    /// `#`, `%`, `&` and space in a branch name must not break out of
629    /// the query string or the URL path segment, and `/` in the project
630    /// path must survive untouched - it is a path separator, not part
631    /// of a branch name.
632    #[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}