use std::{
path::{Path, PathBuf},
process::{Output, Stdio},
};
use futures_util::{stream, StreamExt as _};
use tokio::process::Command;
use super::model::{BranchId, RepoId, GITHUB};
use crate::git::output_within;
const RESOLVES_AT_ONCE: usize = 8;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Checkout {
NotGit,
Detached { commit: String },
NoForge { branch: String },
Branch {
branch: BranchId,
worktree: Worktree,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Worktree {
Own { added_at: u64 },
Shared,
}
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, worktree: Worktree) -> 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 {
branch: BranchId { repo, branch },
worktree,
},
Some(_) | None => Checkout::NoForge { branch },
}
}
pub(crate) async fn resolve_each(workspaces: Vec<(PathBuf, Worktree)>) -> Vec<Checkout> {
stream::iter(workspaces)
.map(|(workspace, worktree)| async move { resolve(&workspace, worktree).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);
output_within(&mut command, workspace).await.ok()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).trim().to_owned()
}
#[cfg(test)]
#[path = "checkout_tests.rs"]
mod tests;