rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! Pull requests from where the repository is hosted: GitHub, GitLab, Gitea (and Forgejo)
//! and Bitbucket, in the cloud or self-hosted.
//!
//! Requests are made with curl, which Windows ships. They are tried without signing in first.
//! If the host refuses, the credentials git already has for that same host are used; they go
//! to curl on its standard input, so they never show up in a process list, and only over https.
//! The address of the API is always derived from the remote's own host, never taken from the
//! repository's settings, so a repository cannot point those credentials somewhere else.

use std::io::Write;
use std::path::Path;
use std::process::Stdio;

use serde_json::Value;

use super::git;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    GitHub,
    GitLab,
    Gitea,
    BitbucketCloud,
    BitbucketServer,
}

impl Kind {
    pub fn label(self) -> &'static str {
        match self {
            Kind::GitHub => "GitHub",
            Kind::GitLab => "GitLab",
            Kind::Gitea => "Gitea",
            Kind::BitbucketCloud => "Bitbucket",
            Kind::BitbucketServer => "Bitbucket Server",
        }
    }

    fn from_setting(s: &str) -> Option<Kind> {
        Some(match s.trim().to_ascii_lowercase().as_str() {
            "github" => Kind::GitHub,
            "gitlab" => Kind::GitLab,
            "gitea" | "forgejo" => Kind::Gitea,
            "bitbucket" => Kind::BitbucketCloud,
            "bitbucket-server" => Kind::BitbucketServer,
            _ => return None,
        })
    }

    /// The ref a host keeps a pull request's head under, if it keeps one.
    pub fn head_ref(self, number: u64) -> Option<String> {
        match self {
            Kind::GitHub | Kind::Gitea => Some(format!("refs/pull/{number}/head")),
            Kind::GitLab => Some(format!("refs/merge-requests/{number}/head")),
            Kind::BitbucketServer => Some(format!("refs/pull-requests/{number}/from")),
            Kind::BitbucketCloud => None,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Location {
    /// Whether the API can be asked over https (and so be sent credentials).
    pub secure: bool,
    /// Host, with the port when the remote is an https address that names one.
    pub host: String,
    /// `owner/repo`; on GitLab it can be deeper (`group/sub/repo`).
    pub path: String,
}

/// Understands `https://host/owner/repo.git`, `ssh://git@host:22/owner/repo` and
/// `git@host:owner/repo.git`. Local paths are not hosts.
pub fn parse_remote(url: &str) -> Option<Location> {
    let url = url.trim();
    let (secure, rest, ssh) = if let Some(r) = url.strip_prefix("https://") {
        (true, r, false)
    } else if let Some(r) = url.strip_prefix("http://") {
        (false, r, false)
    } else if let Some(r) = url.strip_prefix("ssh://").or_else(|| url.strip_prefix("git+ssh://")) {
        (true, r, true)
    } else if url.contains("://") {
        return None;
    } else {
        // `[user@]host:path`. A one-letter "host" is a Windows drive.
        let (host, path) = url.split_once(':')?;
        let host = host.rsplit('@').next()?;
        if host.len() < 2 || host.contains(['/', '\\']) {
            return None;
        }
        return location(true, host, path);
    };
    let (authority, path) = rest.split_once('/')?;
    let host = authority.rsplit('@').next()?;
    // The port of an ssh address says nothing about where the API is.
    let host = if ssh { host.split(':').next()? } else { host };
    location(secure, host, path)
}

fn location(secure: bool, host: &str, path: &str) -> Option<Location> {
    let path = path.trim_matches('/');
    let path = path.strip_suffix(".git").unwrap_or(path);
    let plain = |s: &str| !s.is_empty() && !s.chars().any(|c| c.is_whitespace() || c.is_control() || "\"'\\?#".contains(c));
    (plain(host) && plain(path) && path.contains('/')).then(|| Location { secure, host: host.to_ascii_lowercase(), path: path.to_string() })
}

/// What kind of host this probably is, from its name.
pub fn guess(host: &str) -> Vec<Kind> {
    let name = host.split(':').next().unwrap_or(host);
    match name {
        "github.com" => vec![Kind::GitHub],
        "bitbucket.org" => vec![Kind::BitbucketCloud],
        "codeberg.org" => vec![Kind::Gitea],
        _ if name.contains("gitlab") => vec![Kind::GitLab],
        _ if name.contains("gitea") || name.contains("forgejo") => vec![Kind::Gitea],
        _ if name.contains("bitbucket") || name.contains("stash") => vec![Kind::BitbucketServer],
        _ if name.contains("github") => vec![Kind::GitHub],
        // An unrecognised name: ask each in turn.
        _ => vec![Kind::Gitea, Kind::GitLab, Kind::GitHub, Kind::BitbucketServer],
    }
}

#[derive(Clone, Debug, Default)]
pub struct PullRequest {
    pub number: u64,
    pub title: String,
    pub author: String,
    pub base: String,
    pub head_branch: String,
    pub head_sha: String,
    pub body: String,
    pub url: String,
    pub draft: bool,
    /// The host's word for where it stands: `open`, `MERGED`, ...; empty if it gave none.
    pub state: String,
    /// Bitbucket Server only merges the version it is told about.
    pub version: u64,
}

impl PullRequest {
    /// Not merged, declined or closed, as far as the host said.
    pub fn is_open(&self) -> bool {
        self.state.is_empty() || ["open", "opened"].iter().any(|s| self.state.eq_ignore_ascii_case(s))
    }
}

fn encode(s: &str) -> String {
    s.bytes()
        .map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") })
        .collect()
}

/// The API address of the open pull requests, or of one of them.
pub fn api_url(kind: Kind, at: &Location, number: Option<u64>) -> Option<String> {
    let scheme = if at.secure { "https" } else { "http" };
    let host = &at.host;
    let (owner, repo) = at.path.rsplit_once('/')?;
    let id = number.map(|n| format!("/{n}")).unwrap_or_default();
    Some(match kind {
        Kind::GitHub => {
            let base = if host == "github.com" { "https://api.github.com".to_string() } else { format!("{scheme}://{host}/api/v3") };
            let query = if number.is_none() { "?state=open&per_page=50" } else { "" };
            format!("{base}/repos/{}/pulls{id}{query}", at.path)
        }
        Kind::Gitea => {
            let query = if number.is_none() { "?state=open&limit=50" } else { "" };
            format!("{scheme}://{host}/api/v1/repos/{}/pulls{id}{query}", at.path)
        }
        Kind::GitLab => {
            let query = if number.is_none() { "?state=opened&per_page=50" } else { "" };
            format!("{scheme}://{host}/api/v4/projects/{}/merge_requests{id}{query}", encode(&at.path))
        }
        Kind::BitbucketCloud => {
            let query = if number.is_none() { "?state=OPEN&pagelen=50" } else { "" };
            format!("https://api.bitbucket.org/2.0/repositories/{}/pullrequests{id}{query}", at.path)
        }
        Kind::BitbucketServer => {
            // Clone addresses look like `/scm/KEY/repo` over http and `/KEY/repo` over ssh.
            let owner = owner.strip_prefix("scm/").unwrap_or(owner);
            let query = if number.is_none() { "?state=OPEN&limit=50" } else { "" };
            format!("{scheme}://{host}/rest/api/1.0/projects/{owner}/repos/{repo}/pull-requests{id}{query}")
        }
    })
}

fn text_at(v: &Value, path: &str) -> String {
    v.pointer(path).and_then(Value::as_str).unwrap_or_default().to_string()
}

fn parse_one(kind: Kind, v: &Value) -> Option<PullRequest> {
    let (number, author, base, head_branch, head_sha, body, url) = match kind {
        Kind::GitHub | Kind::Gitea => ("/number", "/user/login", "/base/ref", "/head/ref", "/head/sha", "/body", "/html_url"),
        Kind::GitLab => ("/iid", "/author/username", "/target_branch", "/source_branch", "/sha", "/description", "/web_url"),
        Kind::BitbucketCloud => (
            "/id",
            "/author/display_name",
            "/destination/branch/name",
            "/source/branch/name",
            "/source/commit/hash",
            "/description",
            "/links/html/href",
        ),
        Kind::BitbucketServer => (
            "/id",
            "/author/user/displayName",
            "/toRef/displayId",
            "/fromRef/displayId",
            "/fromRef/latestCommit",
            "/description",
            "/links/self/0/href",
        ),
    };
    let title = v.get("title")?.as_str()?.to_string();
    Some(PullRequest {
        number: v.pointer(number)?.as_u64()?,
        title,
        author: text_at(v, author),
        base: text_at(v, base),
        head_branch: text_at(v, head_branch),
        head_sha: text_at(v, head_sha),
        body: text_at(v, body),
        url: text_at(v, url),
        draft: v.get("draft").and_then(Value::as_bool).unwrap_or(false),
        state: text_at(v, "/state"),
        version: v.get("version").and_then(Value::as_u64).unwrap_or(0),
    })
}

/// A list answer, or `None` if it is not shaped like one from this kind of host.
pub fn parse_list(kind: Kind, v: &Value) -> Option<Vec<PullRequest>> {
    let items = match kind {
        Kind::BitbucketCloud | Kind::BitbucketServer => v.get("values")?.as_array()?,
        _ => v.as_array()?,
    };
    let parsed: Vec<PullRequest> = items.iter().filter_map(|i| parse_one(kind, i)).collect();
    (parsed.len() == items.len()).then_some(parsed)
}

struct Credential {
    user: String,
    secret: String,
}

/// A token from the environment, only for the public host it is meant for.
fn env_token(host: &str) -> Option<String> {
    let names: &[&str] = match host {
        "github.com" => &["GH_TOKEN", "GITHUB_TOKEN"],
        "gitlab.com" => &["GITLAB_TOKEN"],
        _ => &[],
    };
    names.iter().find_map(|n| std::env::var(n).ok()).filter(|t| !t.is_empty())
}

/// What git's credential helper already has for this host. It is not allowed to ask.
fn git_credential(root: &Path, host: &str) -> Option<Credential> {
    let mut child = git::command(root)
        .args(["credential", "fill"])
        .env("GCM_INTERACTIVE", "never")
        .env("GIT_ASKPASS", "")
        .env("SSH_ASKPASS", "")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;
    child.stdin.take()?.write_all(format!("protocol=https\nhost={host}\n\n").as_bytes()).ok()?;
    let out = child.wait_with_output().ok()?;
    if !out.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&out.stdout);
    let value = |key: &str| text.lines().find_map(|l| l.strip_prefix(key)).map(str::to_string);
    Some(Credential { user: value("username=").unwrap_or_default(), secret: value("password=").filter(|p| !p.is_empty())? })
}

/// What to sign in to a host with.
fn credential(root: &Path, host: &str) -> Option<Credential> {
    env_token(host).map(|secret| Credential { user: String::new(), secret }).or_else(|| git_credential(root, host))
}

/// A line of a curl config file with a quoted value.
fn setting(name: &str, value: &str) -> String {
    let value: String = value.chars().filter(|c| !c.is_control()).collect();
    format!("{name} = \"{}\"\n", value.replace('\\', "\\\\").replace('"', "\\\""))
}

fn bearer(c: &Credential) -> String {
    setting("header", &format!("Authorization: Bearer {}", c.secret))
}

/// The ways to sign in with a credential, the likeliest first.
///
/// Git signs in to Bitbucket Cloud with a user name and a secret, but what Git Credential
/// Manager keeps there is usually an OAuth token, which the API only takes as a bearer
/// token. Nothing about it says which it is, so both are tried.
fn authorizations(kind: Kind, c: &Credential) -> Vec<String> {
    if matches!(kind, Kind::GitHub | Kind::GitLab) || c.user == "x-token-auth" || c.user.is_empty() {
        return vec![bearer(c)];
    }
    let basic = setting("user", &format!("{}:{}", c.user, c.secret));
    if kind == Kind::BitbucketCloud { vec![basic, bearer(c)] } else { vec![basic] }
}

/// A signed request. Only a 401, which means nothing was done, leads to another try.
fn signed(kind: Kind, method: &str, url: &str, json: Option<&Value>, c: &Credential) -> Result<(u16, String), String> {
    let mut answer = (401, String::new());
    for auth in authorizations(kind, c) {
        answer = send(method, url, json, Some(auth))?;
        if answer.0 != 401 {
            break;
        }
    }
    Ok(answer)
}

/// GET a URL: (status, body).
fn get(url: &str, auth: Option<String>) -> Result<(u16, String), String> {
    send("GET", url, None, auth)
}

/// What curl is told, on its standard input.
fn curl_config(method: &str, url: &str, json: Option<&Value>, auth: Option<String>) -> String {
    let mut config = setting("url", url) + &setting("header", "Accept: application/json");
    config += &setting("user-agent", "rustimal");
    if method != "GET" {
        config += &setting("request", method);
        // Bitbucket answers 400 to an empty body that is called JSON, as its approval would
        // be, so a request without a body names no type (curl would otherwise add its own).
        let kind = if json.is_some() { "Content-Type: application/json" } else { "Content-Type:" };
        config += &setting("header", kind);
        // Serialised JSON has no raw control characters, so it survives the config line whole.
        // An empty body is still sent, for its length of zero.
        config += &setting("data-raw", &json.map_or_else(String::new, Value::to_string));
    }
    // Redirects are followed only when there are no credentials to carry along.
    match auth {
        Some(line) => config += &line,
        None => config += "location\n",
    }
    config
}

/// A request with an optional JSON body: (status, body).
fn send(method: &str, url: &str, json: Option<&Value>, auth: Option<String>) -> Result<(u16, String), String> {
    let config = curl_config(method, url, json, auth);
    let mut child = git::quiet("curl")
        .args(["--silent", "--show-error", "--max-time", "20", "--proto", "=https,http", "--write-out", "\n%{http_code}", "--config", "-"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("could not run curl: {e}"))?;
    child.stdin.take().ok_or("curl has no input")?.write_all(config.as_bytes()).map_err(|e| e.to_string())?;
    let out = child.wait_with_output().map_err(|e| e.to_string())?;
    if !out.status.success() {
        return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());
    }
    let text = String::from_utf8_lossy(&out.stdout).into_owned();
    let (body, status) = text.rsplit_once('\n').ok_or("unexpected answer from curl")?;
    Ok((status.trim().parse().unwrap_or(0), body.to_string()))
}

/// GET a URL as JSON, signing in only if the host refuses an anonymous request.
fn get_json(root: &Path, kind: Kind, at: &Location, url: &str) -> Result<Value, String> {
    let (mut status, mut body) = get(url, None)?;
    let mut signed_in = false;
    // Private repositories answer 404 to strangers.
    if matches!(status, 401 | 403 | 404) && at.secure && let Some(c) = credential(root, &at.host) {
        signed_in = true;
        (status, body) = signed(kind, "GET", url, None, &c)?;
    }
    match status {
        200 => serde_json::from_str(&body).map_err(|_| format!("{} did not answer with JSON", at.host)),
        401 | 403 | 404 if signed_in => Err(format!(
            "{} answered {status} even with the sign-in git has saved. Check that its account can see this repository",
            at.host
        )),
        401 | 403 | 404 => Err(format!(
            "{} answered {status}: the repository is private or rate limited. Sign in with git once (git fetch), and rustimal uses the same credentials",
            at.host
        )),
        _ => Err(format!("{} answered {status}", at.host)),
    }
}

/// The remote pull requests are looked up on: `origin`, or else the first one.
pub fn remote(root: &Path) -> Result<(String, Option<Location>), String> {
    let remotes = git::output(root, &["remote"])?;
    let names: Vec<&str> = remotes.lines().filter(|l| !l.is_empty()).collect();
    let name = names.iter().find(|n| **n == "origin").or_else(|| names.first()).ok_or("this repository has no remote")?;
    // `get-url` applies `url.*.insteadOf` rewrites.
    let url = git::line(root, &["remote", "get-url", name])?;
    Ok((name.to_string(), parse_remote(&url)))
}

fn kinds(root: &Path, at: &Location) -> Vec<Kind> {
    // For a self-hosted server with a name that gives nothing away: `git config rustimal.forge gitea`.
    match git::line(root, &["config", "--get", "rustimal.forge"]).ok().and_then(|s| Kind::from_setting(&s)) {
        Some(k) => vec![k],
        None => guess(&at.host),
    }
}

/// Ask each kind of host the name could be, until one answers like itself.
fn ask<T>(root: &Path, number: Option<u64>, read: impl Fn(Kind, &Value) -> Option<T>) -> Result<(Kind, T), String> {
    let (name, at) = remote(root)?;
    let at = at.ok_or_else(|| format!("the remote `{name}` is not a hosted repository"))?;
    let mut first_error = None;
    for kind in kinds(root, &at) {
        let Some(url) = api_url(kind, &at, number) else { continue };
        match get_json(root, kind, &at, &url) {
            Ok(v) => match read(kind, &v) {
                Some(found) => return Ok((kind, found)),
                None => first_error.get_or_insert(format!("{} did not answer like {}", at.host, kind.label())),
            },
            Err(e) => first_error.get_or_insert(e),
        };
    }
    Err(first_error.unwrap_or_else(|| format!("do not know how to ask {} for pull requests", at.host)))
}

pub fn list(root: &Path) -> Result<(Kind, Vec<PullRequest>), String> {
    ask(root, None, parse_list)
}

pub fn pull_request(root: &Path, number: u64) -> Result<(Kind, PullRequest), String> {
    ask(root, Some(number), parse_one)
}

/// A pull request to be created.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NewPull {
    pub title: String,
    pub body: String,
    /// The branch with the changes, and the one to merge it into.
    pub head: String,
    pub base: String,
}

/// How to create a pull request on each kind of host: (address, body).
pub fn create_request(kind: Kind, at: &Location, new: &NewPull) -> Option<(String, Value)> {
    let list = api_url(kind, at, None)?;
    let url = list.split('?').next()?.to_string();
    let NewPull { title, body, head, base } = new;
    let title = title.trim();
    let body = match kind {
        Kind::GitHub | Kind::Gitea => serde_json::json!({"title": title, "body": body, "head": head, "base": base}),
        Kind::GitLab => serde_json::json!(
            {"title": title, "description": body, "source_branch": head, "target_branch": base}
        ),
        Kind::BitbucketCloud => serde_json::json!({"title": title, "description": body,
            "source": {"branch": {"name": head}}, "destination": {"branch": {"name": base}}}),
        Kind::BitbucketServer => {
            let (owner, repo) = at.path.rsplit_once('/')?;
            let owner = owner.strip_prefix("scm/").unwrap_or(owner);
            let side = |branch: &str| {
                serde_json::json!({"id": format!("refs/heads/{branch}"),
                    "repository": {"slug": repo, "project": {"key": owner}}})
            };
            serde_json::json!({"title": title, "description": body, "fromRef": side(head), "toRef": side(base)})
        }
    };
    Some((url, body))
}

/// Create a pull request as the person whose credentials git has. The branch has to be on
/// the host already. Returns the host's name and the new pull request.
pub fn create(root: &Path, new: &NewPull) -> Result<(&'static str, PullRequest), String> {
    let (name, at) = remote(root)?;
    let at = at.ok_or_else(|| format!("the remote `{name}` is not a hosted repository"))?;
    if !at.secure {
        return Err(format!("{} is reached over plain http; rustimal does not send credentials there", at.host));
    }
    // Asking for the list tells which kind of host this is.
    let (kind, _) = list(root)?;
    let credential = credential(root, &at.host)
        .ok_or_else(|| format!("git has no credentials for {}; sign in once (git fetch) and try again", at.host))?;
    let (url, body) = create_request(kind, &at, new).ok_or("cannot tell where to create it")?;
    let (status, answer) = signed(kind, "POST", &url, Some(&body), &credential)?;
    if !(200..300).contains(&status) {
        let why = reason(&answer).map(|r| format!(": {r}")).unwrap_or_default();
        return Err(format!("{} refused the pull request ({status}){why}", kind.label()));
    }
    let created = serde_json::from_str::<Value>(&answer).ok().and_then(|v| parse_one(kind, &v));
    created.map(|p| (kind.label(), p)).ok_or_else(|| {
        format!("{} accepted it, but its answer could not be read. Check the host before trying again", kind.label())
    })
}

/// How to approve a pull request on each kind of host: (method, address, body). `head` is the
/// commit that was reviewed; hosts that take one refuse the approval if the head has moved.
/// Bitbucket Server approves as a participant, so it needs the user's name.
pub fn approve_request(kind: Kind, at: &Location, number: u64, head: &str, user: &str) -> Option<(&'static str, String, Option<Value>)> {
    let pr = api_url(kind, at, Some(number))?;
    Some(match kind {
        Kind::GitHub => ("POST", format!("{pr}/reviews"), Some(serde_json::json!({"event": "APPROVE", "commit_id": head}))),
        Kind::Gitea => ("POST", format!("{pr}/reviews"), Some(serde_json::json!({"event": "APPROVED", "commit_id": head, "body": ""}))),
        Kind::GitLab => ("POST", format!("{pr}/approve"), Some(serde_json::json!({"sha": head}))),
        Kind::BitbucketCloud => ("POST", format!("{pr}/approve"), None),
        Kind::BitbucketServer => {
            if user.is_empty() {
                return None;
            }
            let body = serde_json::json!({"user": {"name": user}, "approved": true, "status": "APPROVED"});
            ("PUT", format!("{pr}/participants/{}", encode(user)), Some(body))
        }
    })
}

/// Whether the commit a host reports is the one reviewed. Bitbucket Cloud shortens it.
fn same_commit(host: &str, reviewed: &str) -> bool {
    host.len() >= 7 && reviewed.len() >= 7 && (reviewed.starts_with(host) || host.starts_with(reviewed))
}

/// The host's own words about why it refused, if it gave any.
fn reason(body: &str) -> Option<String> {
    let v: Value = serde_json::from_str(body).ok()?;
    // The most particular first: GitHub's "message" is only "Validation Failed".
    let text = ["/errors/0/message", "/error/message", "/message", "/message/0", "/error"]
        .iter()
        .find_map(|p| v.pointer(p).and_then(Value::as_str).map(str::to_string))?;
    let text: String = text.chars().filter(|c| !c.is_control()).take(200).collect();
    (!text.trim().is_empty()).then_some(text)
}

/// Approve pull request `number` as the person whose credentials git has, but only while its
/// head is still `head`, the commit that was reviewed. Returns the host's name.
pub fn approve(root: &Path, number: u64, head: &str) -> Result<&'static str, String> {
    let (name, at) = remote(root)?;
    let at = at.ok_or_else(|| format!("the remote `{name}` is not a hosted repository"))?;
    if !at.secure {
        return Err(format!("{} is reached over plain http; rustimal does not send credentials there", at.host));
    }
    let (kind, pr) = pull_request(root, number)?;
    if !same_commit(&pr.head_sha, head) {
        return Err(format!("pull request #{number} has new commits since it was loaded; reload and review them first"));
    }
    let credential = credential(root, &at.host)
        .ok_or_else(|| format!("git has no credentials for {}; sign in once (git fetch) and try again", at.host))?;
    let (method, url, body) = approve_request(kind, &at, number, head, &credential.user)
        .ok_or_else(|| format!("approving on {} needs a user name, and git's credentials have none", kind.label()))?;
    let (status, answer) = signed(kind, method, &url, body.as_ref(), &credential)?;
    match status {
        200..=299 => Ok(kind.label()),
        _ => {
            let why = reason(&answer).map(|r| format!(": {r}")).unwrap_or_default();
            Err(format!("{} refused the approval ({status}){why}", kind.label()))
        }
    }
}

/// How a pull request's commits go into the branch it merges into.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Method {
    /// As one new commit.
    Squash,
    /// All of them, joined by a merge commit.
    Commit,
}

/// How to merge a pull request on each kind of host: (method, address, body). `head` is the
/// commit that was reviewed; hosts that take one refuse to merge if the head has moved. The
/// source branch is left to the pull request's own settings.
pub fn merge_request(
    kind: Kind,
    at: &Location,
    number: u64,
    head: &str,
    how: Method,
    version: u64,
) -> Option<(&'static str, String, Value)> {
    let pr = api_url(kind, at, Some(number))?;
    let squash = how == Method::Squash;
    let word = if squash { "squash" } else { "merge" };
    Some(match kind {
        Kind::GitHub => ("PUT", format!("{pr}/merge"), serde_json::json!({"merge_method": word, "sha": head})),
        Kind::Gitea => ("POST", format!("{pr}/merge"), serde_json::json!({"Do": word, "head_commit_id": head})),
        Kind::GitLab => ("PUT", format!("{pr}/merge"), serde_json::json!({"squash": squash, "sha": head})),
        Kind::BitbucketCloud => {
            let strategy = if squash { "squash" } else { "merge_commit" };
            let body = serde_json::json!({"type": "pullrequest", "merge_strategy": strategy});
            ("POST", format!("{pr}/merge"), body)
        }
        Kind::BitbucketServer => {
            let strategy = if squash { "squash" } else { "no-ff" };
            let body = serde_json::json!({"version": version, "strategyId": strategy});
            ("POST", format!("{pr}/merge?version={version}"), body)
        }
    })
}

/// Merge pull request `number` as the person whose credentials git has, but only while it is
/// open and its head is still `head`, the commit that was reviewed. Returns the host's name,
/// and false if the host took the request but has not finished merging.
pub fn merge(root: &Path, number: u64, head: &str, how: Method) -> Result<(&'static str, bool), String> {
    let (name, at) = remote(root)?;
    let at = at.ok_or_else(|| format!("the remote `{name}` is not a hosted repository"))?;
    if !at.secure {
        return Err(format!("{} is reached over plain http; rustimal does not send credentials there", at.host));
    }
    let (kind, pr) = pull_request(root, number)?;
    if !pr.is_open() {
        return Err(format!("pull request #{number} is not open any more ({})", pr.state.to_lowercase()));
    }
    // Not every host checks this itself.
    if !same_commit(&pr.head_sha, head) {
        return Err(format!("pull request #{number} has new commits since it was loaded; reload and review them first"));
    }
    let credential = credential(root, &at.host)
        .ok_or_else(|| format!("git has no credentials for {}; sign in once (git fetch) and try again", at.host))?;
    let (method, url, body) =
        merge_request(kind, &at, number, head, how, pr.version).ok_or("cannot tell where to merge it")?;
    let (status, answer) = signed(kind, method, &url, Some(&body), &credential)
        // The request may have arrived even though the answer didn't.
        .map_err(|e| format!("could not tell whether it merged ({e}). Check {} before trying again", kind.label()))?;
    match status {
        202 => Ok((kind.label(), false)),
        200..=299 => Ok((kind.label(), true)),
        _ => {
            let why = reason(&answer).map(|r| format!(": {r}")).unwrap_or_default();
            Err(format!("{} refused to merge it ({status}){why}", kind.label()))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn at(url: &str) -> (bool, String, String) {
        let l = parse_remote(url).unwrap();
        (l.secure, l.host, l.path)
    }

    #[test]
    fn reads_the_usual_remote_addresses() {
        let gh = (true, "github.com".to_string(), "me/app".to_string());
        assert_eq!(at("https://github.com/me/app.git"), gh);
        assert_eq!(at("git@github.com:me/app.git"), gh);
        assert_eq!(at("ssh://git@github.com:22/me/app"), gh);
        assert_eq!(at("https://user:pw@GitHub.com/me/app/"), gh);
        assert_eq!(at("https://git.corp.example:8443/group/sub/app.git").1, "git.corp.example:8443");
        assert!(!at("http://gitea.lan/me/app").0);
        for local in ["C:\\repos\\app", "C:/repos/app", "/srv/git/app.git", "../app", "file:///srv/app", "https://github.com/nopath"] {
            assert_eq!(parse_remote(local), None, "{local}");
        }
    }

    #[test]
    fn builds_each_hosts_api_address() {
        let url = |k, remote: &str, n| api_url(k, &parse_remote(remote).unwrap(), n).unwrap();
        assert_eq!(url(Kind::GitHub, "git@github.com:me/app.git", None), "https://api.github.com/repos/me/app/pulls?state=open&per_page=50");
        assert_eq!(url(Kind::GitHub, "https://github.corp.example/me/app", Some(7)), "https://github.corp.example/api/v3/repos/me/app/pulls/7");
        assert_eq!(url(Kind::GitLab, "git@gitlab.com:g/sub/app.git", Some(3)), "https://gitlab.com/api/v4/projects/g%2Fsub%2Fapp/merge_requests/3");
        assert_eq!(url(Kind::Gitea, "https://git.example/me/app", Some(2)), "https://git.example/api/v1/repos/me/app/pulls/2");
        assert_eq!(
            url(Kind::BitbucketCloud, "git@bitbucket.org:ws/app.git", Some(4)),
            "https://api.bitbucket.org/2.0/repositories/ws/app/pullrequests/4"
        );
        assert_eq!(
            url(Kind::BitbucketServer, "https://stash.example/scm/KEY/app.git", Some(5)),
            "https://stash.example/rest/api/1.0/projects/KEY/repos/app/pull-requests/5"
        );
    }

    #[test]
    fn guesses_the_kind_from_the_host() {
        assert_eq!(guess("github.com"), [Kind::GitHub]);
        assert_eq!(guess("gitlab.corp.example:8443"), [Kind::GitLab]);
        assert_eq!(guess("codeberg.org"), [Kind::Gitea]);
        assert_eq!(guess("bitbucket.org"), [Kind::BitbucketCloud]);
        assert_eq!(guess("stash.corp.example"), [Kind::BitbucketServer]);
        assert!(guess("git.corp.example").len() > 1);
    }

    #[test]
    fn reads_pull_requests_from_each_shape_of_answer() {
        let github = json!([{"number": 12, "title": "Add export", "user": {"login": "sam"}, "base": {"ref": "main"},
            "head": {"ref": "export", "sha": "abc"}, "body": null, "html_url": "u", "draft": true}]);
        let p = &parse_list(Kind::GitHub, &github).unwrap()[0];
        assert_eq!((p.number, p.author.as_str(), p.base.as_str(), p.head_sha.as_str(), p.draft), (12, "sam", "main", "abc", true));
        assert_eq!(p.body, "");
        let gitlab = json!([{"iid": 3, "title": "t", "author": {"username": "kim"}, "target_branch": "dev", "source_branch": "f",
            "sha": "def", "description": "why", "web_url": "u"}]);
        let p = &parse_list(Kind::GitLab, &gitlab).unwrap()[0];
        assert_eq!((p.number, p.base.as_str(), p.body.as_str()), (3, "dev", "why"));
        let server = json!({"values": [{"id": 5, "title": "t", "author": {"user": {"displayName": "Jo"}},
            "toRef": {"displayId": "master"}, "fromRef": {"displayId": "f", "latestCommit": "123"}}]});
        let p = &parse_list(Kind::BitbucketServer, &server).unwrap()[0];
        assert_eq!((p.number, p.author.as_str(), p.base.as_str(), p.head_sha.as_str()), (5, "Jo", "master", "123"));
        assert!(parse_list(Kind::GitHub, &json!({"message": "Not Found"})).is_none());
        assert!(parse_list(Kind::GitLab, &github).is_none(), "another host's answer is not accepted");
    }

    #[test]
    fn credentials_cannot_break_out_of_the_curl_config() {
        let line = setting("header", "Authorization: Bearer a\"b\\c\nurl = \"https://evil.example\"");
        assert_eq!(line.lines().count(), 1);
        assert!(line.contains("a\\\"b\\\\c"));
    }

    #[test]
    fn approves_the_reviewed_commit_on_each_host() {
        let req = |k, remote: &str, user| approve_request(k, &parse_remote(remote).unwrap(), 7, "abc1234def", user);
        let (m, url, body) = req(Kind::GitHub, "git@github.com:me/app.git", "").unwrap();
        assert_eq!((m, url.as_str()), ("POST", "https://api.github.com/repos/me/app/pulls/7/reviews"));
        assert_eq!(body.unwrap(), json!({"event": "APPROVE", "commit_id": "abc1234def"}));
        let (_, url, body) = req(Kind::GitLab, "git@gitlab.com:g/app.git", "").unwrap();
        assert_eq!(url, "https://gitlab.com/api/v4/projects/g%2Fapp/merge_requests/7/approve");
        assert_eq!(body.unwrap()["sha"], "abc1234def");
        let (m, url, body) = req(Kind::BitbucketCloud, "git@bitbucket.org:ws/app.git", "").unwrap();
        assert_eq!((m, url.as_str(), body), ("POST", "https://api.bitbucket.org/2.0/repositories/ws/app/pullrequests/7/approve", None));
        let (m, url, _) = req(Kind::BitbucketServer, "https://stash.example/scm/KEY/app.git", "jo.doe").unwrap();
        assert_eq!((m, url.as_str()), ("PUT", "https://stash.example/rest/api/1.0/projects/KEY/repos/app/pull-requests/7/participants/jo.doe"));
        assert!(req(Kind::BitbucketServer, "https://stash.example/scm/KEY/app.git", "").is_none());
    }

    #[test]
    fn approval_needs_the_same_head_and_explains_refusals() {
        assert!(same_commit("abc1234def56", "abc1234def5678"), "Bitbucket Cloud's short hash");
        assert!(!same_commit("abc1234", "abc9999"));
        assert!(!same_commit("", "abc1234"), "a host that gives no head cannot be checked");
        assert_eq!(reason(r#"{"error": {"message": "You can't approve your own pull request"}}"#).unwrap(), "You can't approve your own pull request");
        assert_eq!(reason(r#"{"message": "Unprocessable\nEntity"}"#).unwrap(), "UnprocessableEntity");
        assert_eq!(reason("<html>"), None);
    }

    #[test]
    fn a_bitbucket_sign_in_is_also_tried_as_a_token() {
        let c = |user: &str| Credential { user: user.into(), secret: "s3cret".into() };
        let ways = authorizations(Kind::BitbucketCloud, &c("someone"));
        assert_eq!(ways.len(), 2);
        assert!(ways[0].starts_with("user = ") && ways[1].contains("Authorization: Bearer s3cret"), "{ways:?}");
        assert_eq!(authorizations(Kind::BitbucketCloud, &c("x-token-auth")).len(), 1);
        assert_eq!(authorizations(Kind::GitHub, &c("someone")).len(), 1);
        assert_eq!(authorizations(Kind::Gitea, &c("someone")).len(), 1);
    }

    #[test]
    fn asks_each_host_to_create_in_its_own_words() {
        let new = NewPull { title: " Add it ".into(), body: "why".into(), head: "topic".into(), base: "main".into() };
        let ask = |kind, remote: &str| create_request(kind, &parse_remote(remote).unwrap(), &new).unwrap();
        let (url, body) = ask(Kind::BitbucketCloud, "git@bitbucket.org:ws/app.git");
        assert_eq!(url, "https://api.bitbucket.org/2.0/repositories/ws/app/pullrequests");
        assert_eq!(body["source"]["branch"]["name"], "topic");
        assert_eq!(body["destination"]["branch"]["name"], "main");
        assert_eq!((body["title"].as_str(), body["description"].as_str()), (Some("Add it"), Some("why")));
        let (url, body) = ask(Kind::GitHub, "git@github.com:me/app.git");
        assert_eq!(url, "https://api.github.com/repos/me/app/pulls");
        assert_eq!(body, json!({"title": "Add it", "body": "why", "head": "topic", "base": "main"}));
        let (url, body) = ask(Kind::GitLab, "git@gitlab.com:g/app.git");
        assert_eq!(url, "https://gitlab.com/api/v4/projects/g%2Fapp/merge_requests");
        assert_eq!(body["target_branch"], "main");
        let (_, body) = ask(Kind::BitbucketServer, "https://stash.example/scm/KEY/app.git");
        assert_eq!(body["fromRef"]["id"], "refs/heads/topic");
        assert_eq!(body["toRef"]["repository"]["project"]["key"], "KEY");
        let github = r#"{"message":"Validation Failed","errors":[{"message":"A pull request already exists"}]}"#;
        assert_eq!(reason(github).unwrap(), "A pull request already exists");
    }

    #[test]
    fn only_a_request_with_a_body_calls_it_json() {
        let at = parse_remote("git@bitbucket.org:ws/app.git").unwrap();
        let (method, url, body) = approve_request(Kind::BitbucketCloud, &at, 7, "abc1234", "").unwrap();
        let bare = curl_config(method, &url, body.as_ref(), None);
        assert!(!bare.contains("application/json\"\ndata-raw") && !bare.contains("Content-Type: application"), "{bare}");
        assert!(bare.contains("header = \"Content-Type:\"\ndata-raw = \"\"\n"), "{bare}");
        let full = curl_config("POST", &url, Some(&json!({"a": 1})), None);
        assert!(full.contains("header = \"Content-Type: application/json\"\ndata-raw = "), "{full}");
        let read = curl_config("GET", &url, None, None);
        assert!(!read.contains("Content-Type") && !read.contains("data-raw"), "{read}");
    }

    #[test]
    fn merges_on_each_host_and_squashes_when_asked() {
        let req = |k, remote: &str, how| merge_request(k, &parse_remote(remote).unwrap(), 7, "abc1234", how, 3).unwrap();
        let bb = "git@bitbucket.org:ws/app.git";
        let (m, url, body) = req(Kind::BitbucketCloud, bb, Method::Squash);
        assert_eq!((m, url.as_str()), ("POST", "https://api.bitbucket.org/2.0/repositories/ws/app/pullrequests/7/merge"));
        assert_eq!(body, json!({"type": "pullrequest", "merge_strategy": "squash"}));
        assert_eq!(req(Kind::BitbucketCloud, bb, Method::Commit).2["merge_strategy"], "merge_commit");
        let (m, url, body) = req(Kind::GitHub, "git@github.com:me/app.git", Method::Squash);
        assert_eq!((m, url.as_str()), ("PUT", "https://api.github.com/repos/me/app/pulls/7/merge"));
        assert_eq!(body, json!({"merge_method": "squash", "sha": "abc1234"}));
        let (_, _, body) = req(Kind::GitLab, "git@gitlab.com:g/app.git", Method::Commit);
        assert_eq!(body, json!({"squash": false, "sha": "abc1234"}));
        let (_, _, body) = req(Kind::Gitea, "https://git.example/me/app", Method::Squash);
        assert_eq!(body, json!({"Do": "squash", "head_commit_id": "abc1234"}));
        let (_, url, body) = req(Kind::BitbucketServer, "https://stash.example/scm/KEY/app.git", Method::Squash);
        assert!(url.ends_with("/pull-requests/7/merge?version=3"), "{url}");
        assert_eq!(body["strategyId"], "squash");
    }

    #[test]
    fn only_an_open_pull_request_counts_as_open() {
        let with = |state: &str| PullRequest { state: state.into(), ..Default::default() }.is_open();
        assert!(with("") && with("open") && with("OPEN") && with("opened"));
        assert!(!with("MERGED") && !with("DECLINED") && !with("closed") && !with("merged"));
    }

    #[test]
    fn a_json_body_stays_one_config_line() {
        let body = json!({"body": "line one\nline \"two\""}).to_string();
        let line = setting("data-raw", &body);
        assert_eq!(line.lines().count(), 1);
        assert!(line.contains(r#"line one\\nline \\\"two\\\""#), "{line}");
    }

    #[test]
    fn only_public_hosts_get_environment_tokens() {
        assert_eq!(env_token("github.corp.example"), None);
        assert_eq!(env_token("github.com.evil.example"), None);
    }
}