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 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    /// Deliberately verbose: every way of supplying the token is named,
197    /// because "no token" with no further detail is the error people
198    /// file issues about.
199    #[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    /// The host said to slow down (or we already know it is out of calls).
224    #[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    /// The kind is configurable but no client exists for it yet.
234    #[error("{0} is not supported yet: no client exists for it")]
235    NotImplemented(String),
236
237    /// The client exists but does not offer this operation.
238    #[error("`{0}` is not supported by this client")]
239    Unsupported(String),
240
241    #[error("ssh key error: {0}")]
242    Ssh(String),
243
244    /// The local Markdown issue source: a folder or note problem.
245    #[error("{0}")]
246    Local(String),
247
248    /// The integration trust check refused: nothing was sent.
249    #[error("{0}")]
250    Trust(trust::TrustProblem),
251
252    /// `trust.toml` could not be read or written. Refused rather than
253    /// treated as empty: an empty store would re-trust whatever the config
254    /// says now.
255    #[error("the integration trust store is unusable: {0}")]
256    TrustStore(String),
257
258    /// The repository blocks assignment: nothing was sent.
259    #[error("{}", scope::ASSIGNMENT_BLOCKED)]
260    AssignmentBlocked,
261
262    /// The token is a GitHub App installation token: it has no user behind
263    /// it, so `GET /user` (who am I) does not apply. Not a failure: the
264    /// actor is the App.
265    #[error("the token belongs to a GitHub App (a bot), not to a person")]
266    BotToken,
267}
268
269/// Which configured instance a remote URL belongs to, so a repository's
270/// `origin` can be linked back to the integration that can answer
271/// questions about it.
272///
273/// Compares hosts, not whole URLs: `git@gitlab.example.com:g/p.git` and
274/// `https://gitlab.example.com/g/p.git` are the same instance, and an
275/// integration configured as `https://gitlab.example.com` has to match
276/// both.
277pub 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    // A profile's host carries its port (`nas:3000`); the remote's does not
283    // (ssh and http differ in them), so compare the names only.
284    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
295/// The host part of any remote spelling git accepts.
296///
297/// Three shapes in the wild: `https://host/path`, `ssh://git@host/path`
298/// and the scp-like `git@host:path`, which is not a URL at all and is
299/// the one a naive `Url::parse` drops on the floor.
300fn 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    // Strip any `user@` / `user:password@` prefix.
307    let after_user = after_scheme
308        .rsplit_once('@')
309        .map(|(_, r)| r)
310        .unwrap_or(after_scheme);
311    // Whichever of `/` (url) or `:` (scp-like, and also a port) comes
312    // first ends the host.
313    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
318/// Splits a git remote URL into the host's *web* base (`https://host`,
319/// never the API root) and the project path (`group/sub/proj`), for
320/// building a pull/merge-request URL by hand.
321///
322/// Handles every spelling `host_of_remote` does - scp-like
323/// (`git@host:group/proj.git`), `ssh://` (a port, if any, is dropped and
324/// the scheme is `https`: the ssh daemon says nothing about the web UI)
325/// and `http(s)://` (scheme and port are the web UI's own, so a plain-http
326/// server in a container stays `http://host:3000`) - and always strips a
327/// trailing `.git`.
328pub 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    // Repeats `host_of_remote`'s scheme/user/host split so that everything
335    // after the host can be taken as the path; keep the two in step.
336    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    // The host ends at the first `/` or `:` (a port, or the scp-like
343    // separator); whichever it is, the path starts just after it.
344    let end = after_user.find(['/', ':']).unwrap_or(after_user.len());
345    let mut rest = &after_user[end..];
346    // A `:port` before the path (`ssh://` with an explicit port -- the
347    // colon there is a port, not the scp-like separator, which is only
348    // scheme-less `user@host:path`): drop it, keep the `/path`.
349    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    // An http(s) remote is the web UI's own address, scheme and port
363    // included (a self-hosted server is often plain http on a port);
364    // ssh and scp-like remotes say nothing about it, so https it is.
365    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
379/// `web_base` (from [`remote_web_base`]), moved to the address the
380/// matched profile says the server lives at when it is the same host:
381/// an ssh remote of a server configured as `http://host:3000` opens its
382/// web pages there, not on `https://host`.
383pub 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
405/// The two hosts recognized with no configuration at all: `github.com` /
406/// `gitlab.com` (or a `*.github.com` / `*.gitlab.com` subdomain), so a
407/// remote with no matching `[[integrations]]` entry still gets a usable
408/// compare/new-request URL.
409pub 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
425/// Percent-encodes the characters that would break a branch name out of a
426/// query-string value or URL path segment: `#`, `%`, `&` and space.
427/// Deliberately narrow: a legal git branch name cannot contain most other
428/// URL-unsafe characters.
429fn 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
443/// Builds the "open a compare/new pull-request page" URL by hand: the
444/// no-token fallback, and what a token-holding flow opens on success too
445/// (see [`client::HostingClient::create_pull_request`]).
446///
447/// `web_base` and `project` are `remote_web_base`'s output; `source` is the
448/// branch to merge from, `target` the branch to merge into (the host's
449/// default when `None`).
450pub 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    // A family with no URL of its own keeps the GitLab shape it always had.
459    (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    /// Every remote spelling of one instance must find the same
484    /// integration - especially the scp-like form, which is what an
485    /// SSH clone leaves in `.git/config`.
486    #[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    /// Every spelling a git remote can be typed in must yield the same
516    /// `https://host` web base and project path - this is what the
517    /// no-token compare/merge-request URL is built from, so getting it
518    /// wrong silently sends the user to the wrong page.
519    #[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    /// A self-hosted server is often plain http on a port (a Docker
546    /// container): an http(s) remote's own scheme and port are the web
547    /// UI's, so the compare / merge-request URL must not become https.
548    #[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 stays https on the default port: the daemon's port is not the web UI's.
560            ("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    /// An ssh remote of a profile configured as `http://host:port` still
572    /// opens the web UI where the profile says it is.
573    #[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    /// The profile matches an http remote with a port, and an ssh remote
588    /// of the same machine.
589    #[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    /// `#`, `%`, `&` and space in a branch name must not break out of
625    /// the query string or the URL path segment, and `/` in the project
626    /// path must survive untouched - it is a path separator, not part
627    /// of a branch name.
628    #[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}