Preserve partial Git metadata when worktree status is slow (#61939)

## Why

Memory requests have a one-second Git metadata deadline. Waiting for all Git lookups together discards an already observed HEAD or remote URL when the worktree scan exceeds that deadline. Shared status scans can also describe a different HEAD from the independent lookup.

## What changed

- Publish HEAD, verified remote URLs, and worktree status incrementally, retaining available metadata at the memory request deadline.
- Read HEAD and change status together using Git porcelain v2, and reject status observations that conflict with an independently observed HEAD.
- Run a positive-only change probe over up to four recently modified root directories during memory extraction preparation. Use a completed probe only when full status is unknown and its HEAD matches the request metadata, without waiting for it before sending the request.

## Testing

Add coverage for partial metadata at the deadline, delayed lookups, stale and unborn HEAD observations, positive-only probes, shared scans, and porcelain parsing. Extend remote credential redaction coverage to partial clones.

GitOrigin-RevId: e7b7c250bfc0e23fb8962fcd5cd5febd7c69e2bd
This commit is contained in:
ningyi-oai
2026-11-17 01:59:51 +00:00
committed by copyberry
parent 9537934ed6
commit cc356fd384
12 changed files with 960 additions and 151 deletions
+30 -11
View File
@@ -5,6 +5,7 @@ pub use remotes::get_git_remote_urls_assume_git_repo;
pub use remotes::observe_git_remote_urls;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::path::Path;
use std::path::PathBuf;
@@ -129,18 +130,36 @@ pub async fn collect_git_info(cwd: &Path) -> Option<GitInfo> {
/// Return the current HEAD commit hash without checking whether `cwd` is in a git repo.
pub async fn get_head_commit_hash(cwd: &Path) -> Option<GitSha> {
let output = run_git_command_with_timeout(&["rev-parse", "HEAD"], cwd).await?;
if !output.status.success() {
return None;
match get_head_state(cwd).await {
GitHeadState::Commit(hash) => Some(hash),
GitHeadState::Missing | GitHeadState::Unavailable => None,
}
}
let stdout = String::from_utf8(output.stdout).ok()?;
let hash = stdout.trim();
if hash.is_empty() {
None
} else {
Some(GitSha::new(hash))
/// Distinguishes a missing HEAD reference from an unavailable Git lookup.
#[derive(Clone, Debug, PartialEq)]
pub enum GitHeadState {
Commit(GitSha),
Missing,
Unavailable,
}
pub async fn get_head_state(cwd: &Path) -> GitHeadState {
let Some(output) =
run_git_command_with_timeout(&["rev-parse", "--verify", "--quiet", "HEAD"], cwd).await
else {
return GitHeadState::Unavailable;
};
if output.status.code() == Some(1) {
return GitHeadState::Missing;
}
if output.status.success()
&& let Ok(stdout) = str::from_utf8(&output.stdout)
&& !stdout.trim().is_empty()
{
return GitHeadState::Commit(GitSha::new(stdout.trim()));
}
GitHeadState::Unavailable
}
pub fn canonicalize_git_remote_url(url: &str) -> Option<String> {
@@ -363,7 +382,7 @@ pub(crate) async fn detect_local_fsmonitor_override(
pub(crate) async fn run_git_command_with_timeout_from(
git: &Path,
args: &[&str],
args: &[impl AsRef<OsStr>],
cwd: &Path,
fsmonitor: crate::FsmonitorOverride,
) -> Option<std::process::Output> {
@@ -373,7 +392,7 @@ pub(crate) async fn run_git_command_with_timeout_from(
pub(crate) fn local_git_command(
git: &Path,
args: &[&str],
args: &[impl AsRef<OsStr>],
cwd: &Path,
fsmonitor: crate::FsmonitorOverride,
) -> Command {
+5
View File
@@ -36,6 +36,7 @@ pub use fsmonitor::FsmonitorProbeRunner;
pub use fsmonitor::detect_fsmonitor_override;
pub use info::CommitLogEntry;
pub use info::GitDiffToRemote;
pub use info::GitHeadState;
pub use info::GitInfo;
pub use info::canonicalize_git_remote_url;
pub use info::collect_git_info;
@@ -46,13 +47,17 @@ pub use info::get_git_remote_urls;
pub use info::get_git_remote_urls_assume_git_repo;
pub use info::get_git_repo_root;
pub use info::get_head_commit_hash;
pub use info::get_head_state;
pub use info::git_diff_to_remote;
pub use info::local_git_branches;
pub use info::observe_git_remote_urls;
pub use info::recent_commits;
pub use operations::git_config_override_env;
pub use platform::create_symlink;
pub use status::GitWorktreeStatus;
pub use status::get_has_changes_in_repo;
pub use status::get_worktree_status_in_repo;
pub use status::probe_worktree_changes;
pub use trust::resolve_root_git_project_for_trust;
pub use trust::resolve_root_git_project_uri_for_trust;
pub use worktree::RepositoryIdentity;
+155 -19
View File
@@ -1,4 +1,7 @@
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::ffi::OsString;
use std::future::Future;
use std::path::Path;
use std::path::PathBuf;
@@ -9,58 +12,191 @@ use futures::FutureExt;
use futures::future::BoxFuture;
use futures::future::WeakShared;
use crate::GitSha;
use crate::get_git_repo_root;
use crate::info::detect_local_fsmonitor_override;
use crate::info::run_git_command_with_timeout_from;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct GitStatusKey {
git: PathBuf,
repo_root: PathBuf,
/// The HEAD and worktree changes observed by the same Git status command.
#[derive(Clone, Debug, PartialEq)]
pub struct GitWorktreeStatus {
pub head_commit_hash: Option<GitSha>,
pub has_changes: bool,
}
type GitStatusFuture = BoxFuture<'static, Option<bool>>;
type GitStatusFuture = BoxFuture<'static, Option<GitWorktreeStatus>>;
type GitStatusRuns = Mutex<HashMap<PathBuf, WeakShared<GitStatusFuture>>>;
fn git_status_runs() -> &'static Mutex<HashMap<GitStatusKey, WeakShared<GitStatusFuture>>> {
static RUNS: OnceLock<Mutex<HashMap<GitStatusKey, WeakShared<GitStatusFuture>>>> =
OnceLock::new();
const MAX_PROBE_DIRECTORIES: usize = 4;
fn git_status_runs() -> &'static GitStatusRuns {
static RUNS: OnceLock<GitStatusRuns> = OnceLock::new();
RUNS.get_or_init(|| Mutex::new(HashMap::new()))
}
fn change_probe_runs() -> &'static GitStatusRuns {
static RUNS: OnceLock<GitStatusRuns> = OnceLock::new();
RUNS.get_or_init(|| Mutex::new(HashMap::new()))
}
/// Reports repository changes without inspecting uncommitted submodule contents.
pub async fn get_has_changes_in_repo(cwd: &Path, repo_root: &Path) -> Option<bool> {
get_worktree_status_in_repo(cwd, repo_root)
.await
.map(|status| status.has_changes)
}
/// Reads HEAD and worktree changes together, skipping uncommitted submodule contents.
pub async fn get_worktree_status_in_repo(
cwd: &Path,
repo_root: &Path,
) -> Option<GitWorktreeStatus> {
let git = PathBuf::from("git");
let cwd = cwd.to_path_buf();
let key = git_status_key(git.clone(), repo_root).await;
let key = canonical_worktree_root(repo_root).await;
share_git_status_run(key, move || async move {
let fsmonitor = detect_local_fsmonitor_override(&git, &cwd).await;
// Submodule worktree scans can execute filters selected by task-writable
// Git configuration. Skip those scans while retaining gitlink changes.
let output = run_git_command_with_timeout_from(
&git,
&["status", "--porcelain", "--ignore-submodules=dirty"],
&[
"status",
"--porcelain=v2",
"--branch",
"--no-ahead-behind",
"--ignore-submodules=dirty",
],
&cwd,
fsmonitor,
)
.await?;
output.status.success().then_some(!output.stdout.is_empty())
if !output.status.success() {
return None;
}
parse_worktree_status(&output.stdout)
})
.await
}
async fn git_status_key(git: PathBuf, repo_root: &Path) -> GitStatusKey {
let repo_root = tokio::fs::canonicalize(repo_root)
.await
.unwrap_or_else(|_| repo_root.to_path_buf());
GitStatusKey { git, repo_root }
/// Returns a positive change observation from a few recently modified root
/// directories. A clean, failed, or incomplete probe cannot establish that the
/// complete worktree is clean and returns `None`.
pub async fn probe_worktree_changes(cwd: &Path) -> Option<(PathBuf, GitWorktreeStatus)> {
let root = get_git_repo_root(cwd)?;
let probe_root = root.clone();
let cwd = cwd.to_path_buf();
// Relative Git environment paths can resolve differently in sibling cwds.
let status = share_git_run(change_probe_runs(), cwd.clone(), move || async move {
run_change_probe(&cwd, &probe_root).await
})
.await?;
Some((root, status))
}
async fn share_git_status_run<F, Fut>(key: GitStatusKey, run: F) -> Option<bool>
async fn run_change_probe(cwd: &Path, root: &Path) -> Option<GitWorktreeStatus> {
let mut entries = tokio::fs::read_dir(root).await.ok()?;
let mut recent = BinaryHeap::new();
while let Some(entry) = entries.next_entry().await.ok()? {
if entry.file_name() == ".git" || !entry.file_type().await.is_ok_and(|kind| kind.is_dir()) {
continue;
}
if let Ok(metadata) = entry.metadata().await
&& let Ok(modified) = metadata.modified()
{
recent.push(Reverse((modified, entry.file_name())));
if recent.len() > MAX_PROBE_DIRECTORIES {
recent.pop();
}
}
}
if recent.is_empty() {
return None;
}
let mut args: Vec<OsString> = [
"status",
"--porcelain=v2",
"--branch",
"--no-ahead-behind",
"--ignore-submodules=dirty",
"--",
]
.into_iter()
.map(OsString::from)
.collect();
args.extend(recent.into_iter().map(|Reverse((_, name))| {
let mut pathspec = OsString::from(":(top,literal)");
pathspec.push(name);
pathspec
}));
let git = Path::new("git");
let fsmonitor = detect_local_fsmonitor_override(git, cwd).await;
let output = run_git_command_with_timeout_from(git, &args, cwd, fsmonitor).await?;
if !output.status.success() {
return None;
}
parse_worktree_status(&output.stdout).filter(|status| status.has_changes)
}
fn parse_worktree_status(output: &[u8]) -> Option<GitWorktreeStatus> {
let mut oid = None;
let mut has_changes = false;
// Without -z, Git quotes newlines in paths, including both paths in a rename.
for line in output.strip_suffix(b"\n")?.split(|&byte| byte == b'\n') {
let line = line.strip_suffix(b"\r").unwrap_or(line);
if let Some(value) = line.strip_prefix(b"# branch.oid ") {
if oid.replace(value).is_some() {
return None;
}
} else {
// Porcelain v2: # header; 1 ordinary, 2 rename/copy, u unmerged, ? untracked.
match line {
[b'#', b' ', ..] => {}
[b'1' | b'2' | b'u' | b'?', b' ', ..] => has_changes = true,
_ => return None,
}
}
}
let head_commit_hash = match oid? {
b"(initial)" => None,
hash if matches!(hash.len(), 40 | 64) && hash.iter().all(u8::is_ascii_hexdigit) => {
Some(GitSha::new(str::from_utf8(hash).ok()?))
}
_ => return None,
};
Some(GitWorktreeStatus {
head_commit_hash,
has_changes,
})
}
async fn canonical_worktree_root(repo_root: &Path) -> PathBuf {
tokio::fs::canonicalize(repo_root)
.await
.unwrap_or_else(|_| repo_root.to_path_buf())
}
async fn share_git_status_run<F, Fut>(key: PathBuf, run: F) -> Option<GitWorktreeStatus>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Option<bool>> + Send + 'static,
Fut: Future<Output = Option<GitWorktreeStatus>> + Send + 'static,
{
share_git_run(git_status_runs(), key, run).await
}
async fn share_git_run<F, Fut>(
runs: &'static GitStatusRuns,
key: PathBuf,
run: F,
) -> Option<GitWorktreeStatus>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Option<GitWorktreeStatus>> + Send + 'static,
{
let result = {
let mut runs = git_status_runs()
let mut runs = runs
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(result) = runs
+224 -61
View File
@@ -1,4 +1,3 @@
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
@@ -9,11 +8,51 @@ use futures::future::join_all;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::GitStatusKey;
use super::GitWorktreeStatus;
use super::canonical_worktree_root;
use super::change_probe_runs;
use super::get_has_changes_in_repo;
use super::git_status_key;
use super::get_worktree_status_in_repo;
use super::git_status_runs;
use super::parse_worktree_status;
use super::probe_worktree_changes;
use super::share_git_run;
use super::share_git_status_run;
use crate::GitSha;
const CLEAN_STATUS: Option<GitWorktreeStatus> = Some(GitWorktreeStatus {
head_commit_hash: None,
has_changes: false,
});
const DIRTY_STATUS: Option<GitWorktreeStatus> = Some(GitWorktreeStatus {
head_commit_hash: None,
has_changes: true,
});
#[tokio::test]
async fn head_probe_distinguishes_missing_commit_and_unavailable_repository() {
let repository = TempDir::new().expect("create repository");
assert_eq!(
crate::get_head_state(repository.path()).await,
crate::GitHeadState::Unavailable
);
gix::init(repository.path()).expect("initialize repository");
std::fs::write(repository.path().join("HEAD"), "untracked").expect("write HEAD file");
assert_eq!(
crate::get_head_state(repository.path()).await,
crate::GitHeadState::Missing
);
crate::ensure_git_baseline_repository(repository.path())
.await
.expect("create commit");
let hash = crate::get_head_commit_hash(repository.path())
.await
.expect("read commit");
assert_eq!(
crate::get_head_state(repository.path()).await,
crate::GitHeadState::Commit(hash)
);
}
#[tokio::test]
async fn metadata_status_does_not_execute_submodule_clean_filter() {
@@ -126,11 +165,156 @@ async fn status_requests_from_sibling_directories_use_the_known_worktree_root()
std::fs::create_dir(&second_directory).expect("create second directory");
let results = tokio::join!(
get_has_changes_in_repo(&first_directory, repository.path()),
get_worktree_status_in_repo(&first_directory, repository.path()),
get_has_changes_in_repo(&second_directory, repository.path()),
);
assert_eq!(results, (Some(false), Some(false)));
assert_eq!(results, (CLEAN_STATUS, Some(false)));
}
#[tokio::test]
async fn status_reports_the_commit_for_clean_and_dirty_worktrees() {
let repository = TempDir::new().expect("create repository");
let root = repository.path();
crate::ensure_git_baseline_repository(root)
.await
.expect("create initial commit");
let head = crate::get_head_commit_hash(root).await.expect("read HEAD");
let mut expected = GitWorktreeStatus {
head_commit_hash: Some(head),
has_changes: false,
};
assert_eq!(
get_worktree_status_in_repo(root, root).await,
Some(expected.clone())
);
std::fs::write(root.join("untracked"), "worktree change").expect("create untracked file");
expected.has_changes = true;
assert_eq!(
get_worktree_status_in_repo(root, root).await,
Some(expected)
);
assert!(
std::process::Command::new("git")
.args(["config", "status.renames", "invalid"])
.current_dir(root)
.status()
.expect("configure invalid status setting")
.success()
);
assert_eq!(get_worktree_status_in_repo(root, root).await, None);
}
#[tokio::test]
async fn change_probe_only_returns_git_verified_positive_status() {
let repository = TempDir::new().expect("create repository");
let root = repository.path();
crate::ensure_git_baseline_repository(root)
.await
.expect("create initial commit");
let head = crate::get_head_commit_hash(root).await.expect("read HEAD");
assert_eq!(probe_worktree_changes(root).await, None);
// The pathspec must treat names containing Git pathspec syntax literally.
let candidate = root.join("[recent]");
std::fs::create_dir(&candidate).expect("create candidate directory");
std::fs::write(candidate.join("leaf"), "new file").expect("create untracked leaf");
assert_eq!(
probe_worktree_changes(root).await,
Some((
root.to_path_buf(),
GitWorktreeStatus {
head_commit_hash: Some(head),
has_changes: true,
}
))
);
assert!(
std::process::Command::new("git")
.args(["config", "status.showUntrackedFiles", "no"])
.current_dir(root)
.status()
.expect("configure hidden untracked files")
.success()
);
assert_eq!(probe_worktree_changes(root).await, None);
}
#[tokio::test]
async fn concurrent_change_probes_share_one_scan() {
let repository = TempDir::new().expect("create repository");
let key = repository.path().to_path_buf();
let scans = AtomicUsize::new(0);
let (release, gate) = tokio::sync::oneshot::channel();
let first = share_git_run(change_probe_runs(), key.clone(), || async move {
gate.await.ok()?;
DIRTY_STATUS
});
futures::pin_mut!(first);
assert!(futures::poll!(&mut first).is_pending());
let second = share_git_run(change_probe_runs(), key, || {
scans.fetch_add(1, Ordering::Relaxed);
async { CLEAN_STATUS }
});
futures::pin_mut!(second);
assert!(futures::poll!(&mut second).is_pending());
release.send(()).expect("release shared probe");
assert_eq!(tokio::join!(first, second), (DIRTY_STATUS, DIRTY_STATUS));
assert_eq!(scans.load(Ordering::Relaxed), 0);
}
#[tokio::test]
async fn change_probes_do_not_share_sibling_cwds_or_full_status() {
let repository = TempDir::new().expect("create repository");
let root = repository.path().to_path_buf();
let nested = root.join("nested");
let (first, second, full) = tokio::join!(
share_git_run(change_probe_runs(), root.clone(), || async {
tokio::task::yield_now().await;
CLEAN_STATUS
}),
share_git_run(change_probe_runs(), nested, || async {
tokio::task::yield_now().await;
DIRTY_STATUS
}),
share_git_status_run(root, || async {
tokio::task::yield_now().await;
DIRTY_STATUS
}),
);
assert_eq!(
(first, second, full),
(CLEAN_STATUS, DIRTY_STATUS, DIRTY_STATUS)
);
}
#[test]
fn porcelain_status_accepts_sha256_and_non_utf8_path_bytes() {
let hash = "ab".repeat(32);
let mut output = format!("# branch.head (detached)\n# branch.oid {hash}\n").into_bytes();
output.extend_from_slice(b"? file-\xff\n");
assert_eq!(
parse_worktree_status(&output),
Some(GitWorktreeStatus {
head_commit_hash: Some(GitSha::new(&hash)),
has_changes: true
})
);
}
#[test]
fn porcelain_status_requires_one_valid_head_observation() {
for output in [
b"# branch.head main\n".as_slice(),
b"# branch.oid abc123\n",
b"# branch.oid xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n",
b"# branch.oid (initial)\n# branch.oid (initial)\n",
] {
assert_eq!(parse_worktree_status(output), None);
}
}
#[cfg(unix)]
@@ -142,8 +326,8 @@ async fn status_keys_coalesce_symlink_aliases_of_the_same_worktree() {
std::fs::create_dir(&repository).expect("create repository");
std::os::unix::fs::symlink(&repository, &repository_alias).expect("create repository alias");
let key = git_status_key(PathBuf::from("git"), &repository).await;
let alias_key = git_status_key(PathBuf::from("git"), &repository_alias).await;
let key = canonical_worktree_root(&repository).await;
let alias_key = canonical_worktree_root(&repository_alias).await;
assert_eq!(key, alias_key);
}
@@ -151,10 +335,7 @@ async fn status_keys_coalesce_symlink_aliases_of_the_same_worktree() {
#[tokio::test]
async fn concurrent_status_requests_share_one_repository_scan() {
let repository = TempDir::new().expect("create repository");
let key = GitStatusKey {
git: PathBuf::from("git"),
repo_root: repository.path().to_path_buf(),
};
let key = repository.path().to_path_buf();
let scan_count = Arc::new(AtomicUsize::new(0));
let results = join_all((0..32).map(|_| {
@@ -163,12 +344,12 @@ async fn concurrent_status_requests_share_one_repository_scan() {
share_git_status_run(key, move || async move {
scan_count.fetch_add(1, Ordering::Relaxed);
tokio::time::sleep(Duration::from_millis(25)).await;
Some(true)
DIRTY_STATUS
})
}))
.await;
assert_eq!(results, vec![Some(true); 32]);
assert_eq!(results, vec![DIRTY_STATUS; 32]);
assert_eq!(scan_count.load(Ordering::Relaxed), 1);
}
@@ -177,8 +358,8 @@ async fn status_requests_do_not_share_different_repositories() {
let first_repository = TempDir::new().expect("create first repository");
let second_repository = TempDir::new().expect("create second repository");
let scan_count = Arc::new(AtomicUsize::new(0));
let first_key = git_status_key(PathBuf::from("git"), first_repository.path()).await;
let second_key = git_status_key(PathBuf::from("git"), second_repository.path()).await;
let first_key = canonical_worktree_root(first_repository.path()).await;
let second_key = canonical_worktree_root(second_repository.path()).await;
let first_scan_count = Arc::clone(&scan_count);
let second_scan_count = Arc::clone(&scan_count);
@@ -186,64 +367,55 @@ async fn status_requests_do_not_share_different_repositories() {
share_git_status_run(first_key, move || async move {
first_scan_count.fetch_add(1, Ordering::Relaxed);
tokio::time::sleep(Duration::from_millis(25)).await;
Some(false)
CLEAN_STATUS
}),
share_git_status_run(second_key, move || async move {
second_scan_count.fetch_add(1, Ordering::Relaxed);
tokio::time::sleep(Duration::from_millis(25)).await;
Some(true)
DIRTY_STATUS
}),
);
assert_eq!(results, (Some(false), Some(true)));
assert_eq!(results, (CLEAN_STATUS, DIRTY_STATUS));
assert_eq!(scan_count.load(Ordering::Relaxed), 2);
}
#[tokio::test]
async fn completed_status_requests_start_fresh_scans_and_prune_expired_entries() {
let first_repository = TempDir::new().expect("create first repository");
let first_key = GitStatusKey {
git: PathBuf::from("git"),
repo_root: first_repository.path().to_path_buf(),
};
let first_key = first_repository.path().to_path_buf();
let scan_count = Arc::new(AtomicUsize::new(0));
let first_scan_count = Arc::clone(&scan_count);
assert_eq!(
share_git_status_run(first_key.clone(), move || async move {
first_scan_count.fetch_add(1, Ordering::Relaxed);
Some(true)
DIRTY_STATUS
})
.await,
Some(true)
DIRTY_STATUS
);
let second_scan_count = Arc::clone(&scan_count);
assert_eq!(
share_git_status_run(first_key.clone(), move || async move {
second_scan_count.fetch_add(1, Ordering::Relaxed);
Some(false)
CLEAN_STATUS
})
.await,
Some(false)
CLEAN_STATUS
);
assert_eq!(scan_count.load(Ordering::Relaxed), 2);
let second_repository = TempDir::new().expect("create second repository");
let third_scan_count = Arc::clone(&scan_count);
assert_eq!(
share_git_status_run(
GitStatusKey {
git: PathBuf::from("git"),
repo_root: second_repository.path().to_path_buf(),
},
move || async move {
third_scan_count.fetch_add(1, Ordering::Relaxed);
Some(true)
},
)
share_git_status_run(second_repository.path().to_path_buf(), move || async move {
third_scan_count.fetch_add(1, Ordering::Relaxed);
DIRTY_STATUS
})
.await,
Some(true)
DIRTY_STATUS
);
assert_eq!(scan_count.load(Ordering::Relaxed), 3);
assert!(
@@ -257,10 +429,7 @@ async fn completed_status_requests_start_fresh_scans_and_prune_expired_entries()
#[tokio::test]
async fn completed_status_requests_are_not_reused_while_a_consumer_retains_them() {
let repository = TempDir::new().expect("create repository");
let key = GitStatusKey {
git: PathBuf::from("git"),
repo_root: repository.path().to_path_buf(),
};
let key = repository.path().to_path_buf();
let scan_count = Arc::new(AtomicUsize::new(0));
let (release_sender, release_receiver) = tokio::sync::oneshot::channel();
@@ -270,7 +439,7 @@ async fn completed_status_requests_are_not_reused_while_a_consumer_retains_them(
share_git_status_run(first_key, move || async move {
first_scan_count.fetch_add(1, Ordering::Relaxed);
release_receiver.await.ok()?;
Some(true)
DIRTY_STATUS
})
.await
});
@@ -284,28 +453,25 @@ async fn completed_status_requests_are_not_reused_while_a_consumer_retains_them(
.expect("retain the pending shared status scan");
release_sender.send(()).expect("release shared status scan");
assert_eq!(first.await.expect("status task completed"), Some(true));
assert_eq!(retained_result.peek(), Some(&Some(true)));
assert_eq!(first.await.expect("status task completed"), DIRTY_STATUS);
assert_eq!(retained_result.peek(), Some(&DIRTY_STATUS));
let second_scan_count = Arc::clone(&scan_count);
let result = share_git_status_run(key, move || async move {
second_scan_count.fetch_add(1, Ordering::Relaxed);
Some(false)
CLEAN_STATUS
})
.await;
assert_eq!(result, Some(false));
assert_eq!(result, CLEAN_STATUS);
assert_eq!(scan_count.load(Ordering::Relaxed), 2);
assert_eq!(retained_result.peek(), Some(&Some(true)));
assert_eq!(retained_result.peek(), Some(&DIRTY_STATUS));
}
#[tokio::test]
async fn canceling_one_consumer_preserves_the_shared_status_scan() {
let repository = TempDir::new().expect("create repository");
let key = GitStatusKey {
git: PathBuf::from("git"),
repo_root: repository.path().to_path_buf(),
};
let key = repository.path().to_path_buf();
let scan_count = Arc::new(AtomicUsize::new(0));
let (release_sender, release_receiver) = tokio::sync::oneshot::channel();
@@ -315,7 +481,7 @@ async fn canceling_one_consumer_preserves_the_shared_status_scan() {
share_git_status_run(first_key, move || async move {
first_scan_count.fetch_add(1, Ordering::Relaxed);
release_receiver.await.ok()?;
Some(true)
DIRTY_STATUS
})
.await
});
@@ -327,7 +493,7 @@ async fn canceling_one_consumer_preserves_the_shared_status_scan() {
let second = tokio::spawn(async move {
share_git_status_run(second_key, move || async move {
second_scan_count.fetch_add(1, Ordering::Relaxed);
Some(false)
CLEAN_STATUS
})
.await
});
@@ -343,7 +509,7 @@ async fn canceling_one_consumer_preserves_the_shared_status_scan() {
assert_eq!(scan_count.load(Ordering::Relaxed), 1);
release_sender.send(()).expect("release shared status scan");
assert_eq!(first.await.expect("status task completed"), Some(true));
assert_eq!(first.await.expect("status task completed"), DIRTY_STATUS);
assert!(
git_status_runs()
.lock()
@@ -357,10 +523,7 @@ async fn canceling_one_consumer_preserves_the_shared_status_scan() {
#[tokio::test]
async fn canceling_the_last_consumer_allows_a_fresh_status_scan() {
let repository = TempDir::new().expect("create repository");
let key = GitStatusKey {
git: PathBuf::from("git"),
repo_root: repository.path().to_path_buf(),
};
let key = repository.path().to_path_buf();
let scan_count = Arc::new(AtomicUsize::new(0));
let first_key = key.clone();
let first_scan_count = Arc::clone(&scan_count);
@@ -368,7 +531,7 @@ async fn canceling_the_last_consumer_allows_a_fresh_status_scan() {
let first = tokio::spawn(async move {
share_git_status_run(first_key, move || async move {
first_scan_count.fetch_add(1, Ordering::Relaxed);
std::future::pending::<Option<bool>>().await
std::future::pending().await
})
.await
});
@@ -386,11 +549,11 @@ async fn canceling_the_last_consumer_allows_a_fresh_status_scan() {
let second_scan_count = Arc::clone(&scan_count);
let result = share_git_status_run(key.clone(), move || async move {
second_scan_count.fetch_add(1, Ordering::Relaxed);
Some(false)
CLEAN_STATUS
})
.await;
assert_eq!(result, Some(false));
assert_eq!(result, CLEAN_STATUS);
assert_eq!(scan_count.load(Ordering::Relaxed), 2);
assert!(
git_status_runs()