use std::{
fs::Metadata,
path::{Component, Path, PathBuf},
process::Output,
};
use futures_util::{stream, StreamExt as _};
use rho_protocol::{
methods::{
GitCloneParams, GitCloneResponse, GitDiff, GitDiffParams, GitFolder, GitHead, GitIcon,
GitRepo, GitReposParams, GitReposResponse, HostPath, GIT_REPOS,
},
Caller, ClientEnvironment, GitService, RpcError,
};
#[cfg(unix)]
use super::machine::kill_group;
use super::{
machine::{
absolute, blocking, failed, host_path, log_call, log_call_counted, spawn_stream, Machine,
},
machine_fs::{canonical, check_name, make_root, modified_ns, project_root},
};
use crate::git::{host_command as git_command, output_within, NoOutput};
mod clone;
mod diff;
mod dot_git;
const REPOS_AT_ONCE: usize = 8;
const PIPE_READ_BYTES: usize = 64 << 10;
impl GitService for Machine {
async fn repos(
&self,
caller: Caller,
params: GitReposParams,
) -> Result<GitReposResponse, RpcError> {
let GitReposParams {
folders,
icon_candidates,
..
} = params;
log_call_counted(&caller, GIT_REPOS, &folders);
for folder in &folders {
absolute(folder)?;
}
let environment = self.login_environment().await;
let files = dot_git::Files::for_environment(&environment);
let (environment, candidates) = (&environment, icon_candidates.as_slice());
let folders = stream::iter(folders)
.map(move |folder| look_at(folder, environment, files, candidates))
.buffered(REPOS_AT_ONCE)
.collect::<Vec<_>>()
.await
.into_iter()
.collect::<Result<_, _>>()?;
Ok(GitReposResponse::new(folders))
}
async fn diff(&self, caller: Caller, params: GitDiffParams) -> Result<GitDiff, RpcError> {
diff::diff(self, caller, params).await
}
async fn clone_repo(
&self,
caller: Caller,
params: GitCloneParams,
) -> Result<GitCloneResponse, RpcError> {
clone::clone_repo(self, caller, params).await
}
}
async fn git_line(folder: &Path, environment: &ClientEnvironment, args: &[&str]) -> Option<String> {
git_answer(folder, environment, args).await.ok().flatten()
}
async fn git_answer(
folder: &Path,
environment: &ClientEnvironment,
args: &[&str],
) -> Result<Option<String>, String> {
let output = match output_within(git_command(folder, environment).args(args), folder).await {
Ok(output) => output,
Err(late @ NoOutput::Late) => return Err(late.message(folder)),
Err(NoOutput::DidNotStart(_)) => return Ok(None),
};
Ok(line_of(output))
}
fn line_of(output: Output) -> Option<String> {
if !output.status.success() {
return None;
}
let mut line = String::from_utf8(output.stdout).ok()?;
if line.ends_with('\n') {
line.pop();
}
Some(line)
}
async fn toplevel(
folder: &Path,
environment: &ClientEnvironment,
) -> Result<Option<PathBuf>, String> {
let Some(top) = git_answer(folder, environment, &["rev-parse", "--show-toplevel"]).await?
else {
return Ok(None);
};
let top = PathBuf::from(top);
Ok(blocking(move || canonical(&top).ok()).await.ok().flatten())
}
enum Place {
Repo(HostPath),
Outside(HostPath),
}
enum Reader {
Files(GitRepo),
Git,
}
async fn look_at(
folder: HostPath,
environment: &ClientEnvironment,
files: Option<dot_git::Files>,
candidates: &[String],
) -> Result<GitFolder, RpcError> {
let path = PathBuf::from(folder.as_str());
let read = match files {
Some(files) => {
let path = path.clone();
blocking(move || files.read(&path)).await?
}
None => Err(dot_git::AskGit),
};
let (top, reader) = match read {
Ok(Some(dot_git::Checkout { top, repo })) => (Some(top), Reader::Files(repo)),
Ok(None) => (None, Reader::Git),
Err(dot_git::AskGit) => (
toplevel(&path, environment).await.ok().flatten(),
Reader::Git,
),
};
let candidates = candidates.to_vec();
let (place, icon) = blocking(move || place(folder, top, &candidates)).await?;
let (repo, project) = match place {
Place::Repo(project) => {
let repo = match reader {
Reader::Files(repo) => repo,
Reader::Git => read_repo(&path, environment).await,
};
(Some(repo), project)
}
Place::Outside(project) => (None, project),
};
Ok(GitFolder::new(repo, project, icon))
}
fn place(
folder: HostPath,
top: Option<PathBuf>,
candidates: &[String],
) -> (Place, Option<GitIcon>) {
let path = PathBuf::from(folder.as_str());
let in_repo = top
.map(|top| project_root(&top))
.and_then(|root| Some((host_path(&root).ok()?, root)));
let (place, root) = match in_repo {
Some((project, root)) => (Place::Repo(project), root),
None => {
let resolved = canonical(&path)
.ok()
.and_then(|real| Some((host_path(&real).ok()?, real)));
match resolved {
Some((project, real)) => (Place::Outside(project), real),
None => (Place::Outside(folder), path),
}
}
};
let icon = icon(&root, candidates);
(place, icon)
}
async fn read_repo(folder: &Path, environment: &ClientEnvironment) -> GitRepo {
let head = match git_line(folder, environment, &["symbolic-ref", "-q", "HEAD"]).await {
Some(reference) => Some(GitHead::Branch { reference }),
None => git_line(
folder,
environment,
&["rev-parse", "-q", "--verify", "HEAD"],
)
.await
.map(|commit| GitHead::Detached { commit }),
};
let origin_url = git_line(
folder,
environment,
&["config", "--get", "remote.origin.url"],
)
.await;
GitRepo::new(head, origin_url)
}
fn icon(project: &Path, candidates: &[String]) -> Option<GitIcon> {
candidates.iter().find_map(|candidate| {
let path = project.join(within(candidate)?);
let metadata = std::fs::metadata(path).ok().filter(Metadata::is_file)?;
Some(GitIcon::new(
candidate.clone(),
metadata.len(),
modified_ns(&metadata),
))
})
}
fn within(candidate: &str) -> Option<PathBuf> {
candidate
.split('/')
.map(|part| {
let mut components = Path::new(part).components();
matches!(
(components.next(), components.next()),
(Some(Component::Normal(_)), None)
)
.then_some(part)
})
.collect()
}
#[cfg(test)]
#[path = "machine_git_tests.rs"]
mod tests;