use std::{path::Path, process::Command};
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::{resolve, Checkout};
use crate::app::pull_requests::model::{BranchId, RepoId};
fn git(dir: &Path, args: &[&str]) -> String {
let mut command = Command::new("git");
for name in crate::git::LOCATION_ENV {
command.env_remove(name);
}
let output = command
.arg("-C")
.arg(dir)
.args([
"-c",
"user.name=rho",
"-c",
"user.email=rho@example.com",
"-c",
"commit.gpgsign=false",
])
.args(args)
.output()
.unwrap();
assert!(
output.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout).unwrap().trim().to_owned()
}
enum Given {
Plain,
OnFeature { origin: Option<&'static str> },
Detached,
}
fn make(workspace: &Path, given: &Given) -> Option<String> {
match given {
Given::Plain => None,
Given::OnFeature { origin } => {
git(workspace, &["init", "--quiet", "--initial-branch=feature"]);
if let Some(url) = *origin {
git(workspace, &["remote", "add", "origin", url]);
}
None
}
Given::Detached => {
git(workspace, &["init", "--quiet", "--initial-branch=main"]);
git(
workspace,
&["commit", "--quiet", "--allow-empty", "-m", "base"],
);
git(workspace, &["checkout", "--quiet", "--detach"]);
Some(git(workspace, &["rev-parse", "--short", "HEAD"]))
}
}
}
#[tokio::test]
async fn a_workspace_names_its_checkout() {
let feature = || "feature".to_owned();
let cases = [
("not a repository", Given::Plain, Checkout::NotGit),
(
"a branch with a forge origin",
Given::OnFeature {
origin: Some("git@github.com:acme/widgets.git"),
},
Checkout::Branch(BranchId {
repo: RepoId {
host: "github.com".to_owned(),
owner: "acme".to_owned(),
name: "widgets".to_owned(),
},
branch: feature(),
}),
),
(
"a detached head",
Given::Detached,
Checkout::Detached {
commit: String::new(),
},
),
(
"no origin",
Given::OnFeature { origin: None },
Checkout::NoForge { branch: feature() },
),
(
"an origin on another forge than github.com",
Given::OnFeature {
origin: Some("https://gitlab.com/acme/widgets.git"),
},
Checkout::NoForge { branch: feature() },
),
(
"an origin that is a local path",
Given::OnFeature {
origin: Some("/srv/git/widgets.git"),
},
Checkout::NoForge { branch: feature() },
),
];
for (name, given, mut expected) in cases {
let dir = TempDir::new().unwrap();
let head = make(dir.path(), &given);
if let (Checkout::Detached { commit }, Some(head)) = (&mut expected, head) {
*commit = head;
}
assert_eq!(resolve(dir.path()).await, expected, "{name}");
}
}