use pretty_assertions::assert_eq;
use rho_protocol::{
methods::{FsRead, FsReadParams, HostStreamEnd, GIT_DIFF_MAX_BYTES},
ErrorCode, FsService,
};
use super::*;
use crate::app::daemon_host::machine_test_support::*;
async fn patch(caller: &Caller, diff: GitDiff, repo: &Path) -> (Vec<u8>, HostStreamEnd) {
let GitDiff::Patch { top, stream } = diff else {
panic!("not a patch: {diff:?}");
};
assert_eq!(top, real(repo));
read_out(caller, stream).await
}
fn headers(patch: &[u8]) -> Vec<String> {
String::from_utf8_lossy(patch)
.lines()
.filter(|line| line.starts_with("diff --git "))
.map(str::to_owned)
.collect()
}
#[tokio::test]
async fn repos_reads_each_folder_in_order() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let main = root.join("main");
repository(&main, &[("assets/icon.svg", "<svg/>")]);
let origin = "https://example.com/rho/main.git";
git(&main, &["remote", "add", "origin", origin]);
git(
&main,
&["worktree", "add", "-q", "-b", "feature", "../linked"],
);
git(&main, &["worktree", "add", "-q", "--detach", "../detached"]);
let commit = git(&main, &["rev-parse", "HEAD"]);
let included = root.join("included");
repository(&included, &[("a.txt", "a")]);
git(&included, &["config", "include.path", "more"]);
let plain = root.join("plain");
std::fs::create_dir(&plain).unwrap();
let missing = root.join("missing");
std::fs::write(root.join("outside.svg"), "<svg/>").unwrap();
let candidates = ["../outside.svg", "favicon.ico", "assets/icon.svg"]
.map(str::to_owned)
.to_vec();
let machine = machine();
let read = machine
.read(
caller(),
FsReadParams::new(real(&main), HostPath::new("assets/icon.svg"), 0, 0),
)
.await
.unwrap();
let FsRead::File {
size, modified_ns, ..
} = read
else {
panic!("not a file: {read:?}");
};
let icon = Some(GitIcon::new("assets/icon.svg", size, modified_ns));
let repo = |head| Some(GitRepo::new(Some(head), Some(origin.to_owned())));
let branch = |reference: &str| GitHead::Branch {
reference: reference.to_owned(),
};
let answered = machine
.repos(
caller(),
GitReposParams::new(
vec![
host(&main.join("assets")),
host(&root.join("linked")),
host(&root.join("detached")),
host(&included),
host(&plain),
host(&missing),
],
candidates,
),
)
.await
.unwrap();
assert_eq!(
answered.folders,
[
GitFolder::new(repo(branch("refs/heads/main")), real(&main), icon.clone()),
GitFolder::new(
repo(branch("refs/heads/feature")),
real(&main),
icon.clone()
),
GitFolder::new(repo(GitHead::Detached { commit }), real(&main), icon),
GitFolder::new(
Some(GitRepo::new(Some(branch("refs/heads/main")), None)),
real(&included),
None
),
GitFolder::new(None, real(&plain), None),
GitFolder::new(None, host(&missing), None),
]
);
}
#[tokio::test]
async fn diff_streams_whole_files_up_to_the_limit() {
let dir = tempfile::tempdir().unwrap();
let repo = dir.path().join("repo");
repository(
&repo,
&[
(".gitignore", "ignored.txt\n"),
("sub/tracked.txt", "old\n"),
],
);
std::fs::write(repo.join("sub/tracked.txt"), "new\n").unwrap();
std::fs::write(repo.join("untracked.txt"), "fresh\n").unwrap();
std::fs::write(repo.join("ignored.txt"), "ignored\n").unwrap();
let machine = machine();
let caller = caller();
let diff = |limit| {
machine.diff(
caller.clone(),
GitDiffParams::new(host(&repo.join("sub")), limit),
)
};
let (whole, whole_end) = patch(&caller, diff(1 << 20).await.unwrap(), &repo).await;
let first = String::from_utf8_lossy(&whole)
.find("\ndiff --git a/untracked.txt")
.unwrap()
+ 1;
let into_second = first as u64 + 3;
let cut = patch(&caller, diff(into_second).await.unwrap(), &repo).await;
let none = patch(&caller, diff(3).await.unwrap(), &repo).await;
assert_eq!(
headers(&whole),
[
"diff --git a/sub/tracked.txt b/sub/tracked.txt",
"diff --git a/untracked.txt b/untracked.txt",
]
);
assert_eq!(whole_end, HostStreamEnd::Done);
assert_eq!(cut, (whole[..first].to_vec(), HostStreamEnd::Truncated));
assert_eq!(none, (Vec::new(), HostStreamEnd::Truncated));
}
#[tokio::test]
async fn diff_reads_a_first_commit_and_refuses_what_it_cannot_diff() {
let dir = tempfile::tempdir().unwrap();
let repo = dir.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q"]);
std::fs::write(repo.join("staged.txt"), "staged\n").unwrap();
git(&repo, &["add", "staged.txt"]);
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
let plain = dir.path().join("plain");
std::fs::create_dir(&plain).unwrap();
let machine = machine();
let caller = caller();
let diff =
|folder: HostPath, limit| machine.diff(caller.clone(), GitDiffParams::new(folder, limit));
let fresh = diff(host(&repo), 1 << 20).await.unwrap();
let outside = diff(host(&plain), 1 << 20).await.unwrap();
let too_much = diff(host(&repo), GIT_DIFF_MAX_BYTES + 1).await.unwrap_err();
let relative = diff(HostPath::new("repo"), 1 << 20).await.unwrap_err();
let (bytes, end) = patch(&caller, fresh, &repo).await;
assert_eq!(
headers(&bytes),
[
"diff --git a/staged.txt b/staged.txt",
"diff --git a/new.txt b/new.txt",
]
);
assert_eq!(end, HostStreamEnd::Done);
assert_eq!(outside, GitDiff::NotRepo);
assert_eq!(too_much.code, ErrorCode::InvalidParams.code());
assert!(
too_much.message.contains(&GIT_DIFF_MAX_BYTES.to_string()),
"{}",
too_much.message
);
assert_eq!(relative.code, ErrorCode::InvalidParams.code());
}
async fn clone_into(
machine: &Machine,
caller: &Caller,
url: &str,
folder: &Path,
name: &str,
) -> Result<GitCloneResponse, RpcError> {
machine
.clone_repo(caller.clone(), GitCloneParams::new(url, host(folder), name))
.await
}
#[tokio::test]
async fn clone_clones_once_and_refuses_what_else_is_there() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let source = root.join("source");
repository(&source, &[("a.txt", "a")]);
let url = source.to_str().unwrap();
let projects = root.join("projects/deeper");
let machine = machine();
let caller = caller();
let first = clone_into(&machine, &caller, url, &projects, "copy")
.await
.unwrap();
let copy = canonical(&projects).unwrap().join("copy");
assert_eq!(first.path, host(©));
let (_, end) = read_out(&caller, first.progress.unwrap()).await;
assert_eq!(end, HostStreamEnd::Done);
assert_eq!(
git(©, &["rev-parse", "HEAD"]),
git(&source, &["rev-parse", "HEAD"])
);
let again = clone_into(&machine, &caller, url, &projects, "copy")
.await
.unwrap();
assert_eq!(again, GitCloneResponse::new(host(©), None));
std::fs::create_dir_all(projects.join("other")).unwrap();
std::fs::write(projects.join("other/file.txt"), "kept").unwrap();
let other = clone_into(&machine, &caller, url, &projects, "other")
.await
.unwrap_err();
assert_eq!(other.code, ErrorCode::HostCallFailed.code());
assert!(
other.message.ends_with("already holds something else."),
"{}",
other.message
);
assert!(projects.join("other/file.txt").exists());
let started = projects.join("started");
std::fs::create_dir(&started).unwrap();
git(&started, &["init", "-q"]);
git(&started, &["remote", "add", "origin", url]);
let unfinished = clone_into(&machine, &caller, url, &projects, "started")
.await
.unwrap_err();
assert_eq!(unfinished.code, ErrorCode::HostCallFailed.code());
assert!(
unfinished.message.contains("with no commit yet"),
"{}",
unfinished.message
);
let enclosing = root.join("enclosing");
repository(&enclosing, &[("a.txt", "a")]);
git(&enclosing, &["remote", "add", "origin", url]);
std::fs::create_dir(enclosing.join("inner")).unwrap();
let inside = clone_into(&machine, &caller, url, &enclosing, "inner")
.await
.unwrap_err();
assert!(
inside.message.ends_with("already holds something else."),
"{}",
inside.message
);
let missing = root.join("missing");
let failing = clone_into(
&machine,
&caller,
missing.to_str().unwrap(),
&projects,
"failed",
)
.await
.unwrap();
let (_, failed_end) = read_out(&caller, failing.progress.unwrap()).await;
let HostStreamEnd::Failed { message, .. } = failed_end else {
panic!("not failed: {failed_end:?}");
};
assert!(message.contains("fatal: "), "{message}");
assert!(!projects.join("failed").exists());
let dots = clone_into(&machine, &caller, url, &projects, "..")
.await
.unwrap_err();
assert_eq!(dots.code, ErrorCode::InvalidParams.code());
}
#[test]
fn a_clone_url_is_shown_without_its_credentials() {
use super::clone::without_credentials;
assert_eq!(
without_credentials("https://user:token@example.com/a/b.git"),
"https://example.com/a/b.git"
);
assert_eq!(
without_credentials("https://token@example.com/a/b.git"),
"https://example.com/a/b.git"
);
assert_eq!(
without_credentials("https://user:token@exa mple.com/a/b.git"),
"https://exa mple.com/a/b.git"
);
assert_eq!(
without_credentials("https://token@exa mple.com"),
"https://exa mple.com"
);
assert_eq!(
without_credentials("https://user:ab/cd@example.com/a/b.git"),
"https://example.com/a/b.git"
);
assert_eq!(
without_credentials("git@example.com:a/b.git"),
"git@example.com:a/b.git"
);
}
#[cfg(unix)]
#[tokio::test]
async fn closing_a_clone_stream_kills_git_and_removes_the_clone() {
use std::time::Duration;
use tokio::io::AsyncReadExt as _;
const WAIT: Duration = Duration::from_secs(10);
let dir = tempfile::tempdir().unwrap();
let server = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/x.git", server.local_addr().unwrap());
let machine = machine();
let caller = caller();
let started = clone_into(&machine, &caller, &url, dir.path(), "x")
.await
.unwrap();
let (mut connection, _) = tokio::time::timeout(WAIT, server.accept())
.await
.expect("git never connected")
.unwrap();
caller.close_stream(&started.progress.unwrap());
let mut asked = Vec::new();
let closed = tokio::time::timeout(WAIT, connection.read_to_end(&mut asked)).await;
assert!(
matches!(closed, Ok(Ok(_))),
"the connection didn't end: {closed:?}"
);
let clone = Path::new(started.path.as_str());
let removed = tokio::time::timeout(WAIT, async {
while clone.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await;
assert!(removed.is_ok(), "{} is still there", clone.display());
}