use std::{
path::{Path, PathBuf},
process::{Output, Stdio},
time::Duration,
};
use futures_util::{stream, StreamExt as _};
use tokio::process::Command;
use super::model::{BranchId, RepoId, GITHUB};
const GIT_DEADLINE: Duration = Duration::from_secs(5);
const RESOLVES_AT_ONCE: usize = 8;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Checkout {
NotGit,
Detached { commit: String },
NoForge { branch: String },
Branch(BranchId),
}
impl Checkout {
pub(super) fn branch(&self) -> Option<&BranchId> {
match self {
Self::Branch(branch) => Some(branch),
Self::NotGit | Self::Detached { .. } | Self::NoForge { .. } => None,
}
}
}
pub(crate) async fn resolve(workspace: &Path) -> Checkout {
let Some(head) = git(workspace, &["symbolic-ref", "--short", "-q", "HEAD"]).await else {
return Checkout::NotGit;
};
match head.status.code() {
Some(0) => {}
Some(1) => {
let commit = git(workspace, &["rev-parse", "--short", "HEAD"]).await;
return match commit {
Some(commit) if commit.status.success() => Checkout::Detached {
commit: stdout(&commit),
},
Some(_) | None => Checkout::NotGit,
};
}
Some(_) | None => return Checkout::NotGit,
}
let branch = stdout(&head);
match origin(workspace).await {
Some(repo) if repo.host == GITHUB => Checkout::Branch(BranchId { repo, branch }),
Some(_) | None => Checkout::NoForge { branch },
}
}
pub(crate) async fn resolve_each(workspaces: Vec<PathBuf>) -> Vec<Checkout> {
stream::iter(workspaces)
.map(|workspace| async move { resolve(&workspace).await })
.buffered(RESOLVES_AT_ONCE)
.collect()
.await
}
pub(super) async fn origin(workspace: &Path) -> Option<RepoId> {
let output = git(workspace, &["remote", "get-url", "origin"]).await?;
if !output.status.success() {
return None;
}
RepoId::from_url(std::str::from_utf8(&output.stdout).ok()?)
}
async fn git(workspace: &Path, args: &[&str]) -> Option<Output> {
let mut command = Command::new("git");
for name in crate::git::LOCATION_ENV {
command.env_remove(name);
}
command
.arg("-C")
.arg(workspace)
.args(args)
.stdin(Stdio::null())
.kill_on_drop(true);
match tokio::time::timeout(GIT_DEADLINE, command.output()).await {
Ok(output) => output.ok(),
Err(_) => {
tracing::warn!(
workspace = %workspace.display(),
?args,
deadline_secs = GIT_DEADLINE.as_secs(),
"git did not answer in time; reading the workspace's checkout without it"
);
None
}
}
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).trim().to_owned()
}
#[cfg(test)]
#[path = "checkout_tests.rs"]
mod tests;