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,
})
}
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 {
pub secure: bool,
pub host: String,
pub path: String,
}
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 {
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()?;
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() })
}
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],
_ => 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,
pub state: String,
pub version: u64,
}
impl PullRequest {
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()
}
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 => {
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),
})
}
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,
}
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())
}
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())? })
}
fn credential(root: &Path, host: &str) -> Option<Credential> {
env_token(host).map(|secret| Credential { user: String::new(), secret }).or_else(|| git_credential(root, host))
}
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))
}
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] }
}
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)
}
fn get(url: &str, auth: Option<String>) -> Result<(u16, String), String> {
send("GET", url, None, auth)
}
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);
let kind = if json.is_some() { "Content-Type: application/json" } else { "Content-Type:" };
config += &setting("header", kind);
config += &setting("data-raw", &json.map_or_else(String::new, Value::to_string));
}
match auth {
Some(line) => config += &line,
None => config += "location\n",
}
config
}
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()))
}
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;
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)),
}
}
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")?;
let url = git::line(root, &["remote", "get-url", name])?;
Ok((name.to_string(), parse_remote(&url)))
}
fn kinds(root: &Path, at: &Location) -> Vec<Kind> {
match git::line(root, &["config", "--get", "rustimal.forge"]).ok().and_then(|s| Kind::from_setting(&s)) {
Some(k) => vec![k],
None => guess(&at.host),
}
}
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)
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NewPull {
pub title: String,
pub body: String,
pub head: String,
pub base: String,
}
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))
}
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));
}
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())
})
}
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))
}
})
}
fn same_commit(host: &str, reviewed: &str) -> bool {
host.len() >= 7 && reviewed.len() >= 7 && (reviewed.starts_with(host) || host.starts_with(reviewed))
}
fn reason(body: &str) -> Option<String> {
let v: Value = serde_json::from_str(body).ok()?;
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)
}
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()))
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Method {
Squash,
Commit,
}
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)
}
})
}
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()));
}
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)
.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);
}
}