Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/core/src/updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,9 +363,9 @@ fn launch_installer(path: &Path) -> Result<(), UpdaterError> {
#[cfg(target_os = "linux")]
{
let _ = path;
return Err(UpdaterError::Untrusted(
Err(UpdaterError::Untrusted(
"on Linux, install updates from the release page".to_owned(),
));
))
}
#[cfg(not(target_os = "linux"))]
Ok(())
Expand Down
40 changes: 29 additions & 11 deletions crates/core/src/watcher.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
//! Filesystem watching for open repositories (`repository-changed`).
//!
//! Each non-ignored directory in the working tree is watched non-recursively
//! (walking directories upfront and skipping `.git` and gitignored directories
//! at any depth so nested `node_modules` or `target` never allocate OS watch
//! handles). The per-worktree Git directory (index, HEAD) and the common
//! directory's refs are watched separately so linked worktrees work. Events
//! are debounced: 300 ms after the last event, at most 2 s after the first.
//! On Linux and macOS each non-ignored directory in the working tree is
//! watched non-recursively (walking directories upfront and skipping `.git`
//! and gitignored directories at any depth so nested `node_modules` or
//! `target` never allocate OS watch handles).
//!
//! On Windows every watch holds an open directory handle, and an open handle
//! on a nested directory stops its ancestors from being renamed or deleted.
//! There the working tree root is watched once, recursively, and events from
//! ignored directories are dropped by the debouncer's ignore cache.
//!
//! The per-worktree Git directory (index, HEAD) and the common directory's
//! refs are watched separately so linked worktrees work. Events are
//! debounced: 300 ms after the last event, at most 2 s after the first.

use std::collections::{BTreeSet, HashMap, VecDeque};
use std::path::{Path, PathBuf};
Expand All @@ -23,6 +30,8 @@ pub const MAX_DELAY: Duration = Duration::from_secs(2);
pub const MAX_WATCHED: usize = 8;
const MAX_EVENT_PATHS: usize = 100;
const IGNORE_CHECK_BATCH: usize = 256;
/// Windows watches the root recursively instead of each directory (see the module docs).
const RECURSIVE_ROOT: bool = cfg!(windows);

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -303,13 +312,21 @@ impl RepositoryWatchers {
) = mpsc::channel();
let mut watcher: RecommendedWatcher = notify::recommended_watcher(sender)?;

watch_non_ignored_tree(&mut watcher, git, &layout.root, &layout.root)?;
watcher.watch(&layout.git_dir, RecursiveMode::NonRecursive)?;
if layout.common_dir != layout.git_dir {
if RECURSIVE_ROOT {
watcher.watch(&layout.root, RecursiveMode::Recursive)?;
} else {
watch_non_ignored_tree(&mut watcher, git, &layout.root, &layout.root)?;
}
// A recursive root watch already covers Git directories inside the root.
let covered = |path: &Path| RECURSIVE_ROOT && path.starts_with(&layout.root);
if !covered(&layout.git_dir) {
watcher.watch(&layout.git_dir, RecursiveMode::NonRecursive)?;
}
if layout.common_dir != layout.git_dir && !covered(&layout.common_dir) {
watcher.watch(&layout.common_dir, RecursiveMode::NonRecursive)?;
}
let refs: PathBuf = layout.common_dir.join("refs");
if refs.is_dir() {
if refs.is_dir() && !covered(&refs) {
watcher.watch(&refs, RecursiveMode::Recursive)?;
}

Expand Down Expand Up @@ -429,7 +446,8 @@ fn spawn_debouncer(
}
pending.insert(scope);
}
if path.starts_with(&layout.root)
if !RECURSIVE_ROOT
&& path.starts_with(&layout.root)
&& !layout.is_root(path)
&& path.is_dir()
&& !matches!(event.kind, EventKind::Remove(_))
Expand Down
31 changes: 31 additions & 0 deletions crates/core/tests/watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,34 @@ fn unwatch_stops_events() {
std::fs::write(fixture.root.join("src/lib.rs"), "3\n").expect("edit");
assert!(receiver.recv_timeout(Duration::from_millis(1500)).is_err());
}

#[test]
fn watched_directories_can_still_be_renamed() {
let fixture: Fixture = fixture();
std::fs::create_dir_all(fixture.root.join("src/a/b")).expect("mkdir nested");
std::fs::write(
fixture.root.join("src/a/b/x.rs"),
"1
",
)
.expect("write nested");
let watchers: RepositoryWatchers = RepositoryWatchers::default();
let receiver = watch(&fixture, &watchers);

// Watch handles on nested directories must not lock their ancestors.
std::fs::rename(fixture.root.join("src/a"), fixture.root.join("src/a2"))
.expect("rename a nested watched directory");
std::fs::rename(fixture.root.join("src"), fixture.root.join("src2"))
.expect("rename a top-level watched directory");
expect_scope(&receiver, ChangeScope::Worktree);

// Files inside a renamed directory keep reporting changes.
drain(&receiver);
std::fs::write(
fixture.root.join("src2/a2/b/x.rs"),
"2
",
)
.expect("edit after rename");
expect_scope(&receiver, ChangeScope::Worktree);
}
10 changes: 8 additions & 2 deletions crates/git-engine/src/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,13 +272,19 @@ fn resolve_initial_tips(
{
return Ok(None);
}
let mut args: Vec<String> = vec!["rev-parse".to_owned(), "--end-of-options".to_owned()];
// `log_page` has already rejected option-like revisions. Do not pass
// `--end-of-options`: `rev-parse` echoes it back as an output line.
let mut args: Vec<String> = vec!["rev-parse".to_owned()];
for rev in revs {
args.push(format!("{rev}^{{commit}}"));
}
let output: std::process::Output = git.run(root, &args, None)?;
for line in String::from_utf8_lossy(&output.stdout).lines() {
push_tip(line.trim().to_owned());
let oid: &str = line.trim();
// Only commit ids may become cursor entries.
if validate_cursor_oid(oid).is_ok() {
push_tip(oid.to_owned());
}
}
}
None => {
Expand Down
89 changes: 56 additions & 33 deletions crates/git-engine/src/status.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::collections::VecDeque;
use std::path::{Path, PathBuf};

use serde::Serialize;
Expand All @@ -11,6 +10,8 @@ const LITERAL: &str = "--literal-pathspecs";
pub const MAX_STATUS_BYTES: usize = 2 * 1024 * 1024;
pub const UNTRACKED_DIR_COUNT_CAP: u32 = 10_000;
pub const MAX_UNTRACKED_DIR_LIST: u32 = 2_000;
/// Untracked folders counted per `git ls-files` call, to stay under OS argument limits.
const UNTRACKED_COUNT_CHUNK: usize = 100;

/// The kind of change recorded for one side (index or working tree) of a file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
Expand Down Expand Up @@ -158,16 +159,7 @@ pub fn read_status(git: &GitExecutor, root: &Path) -> GitResult<StatusSnapshot>
let mut snapshot: StatusSnapshot =
parse_porcelain_v2_capped(&output.output.stdout, output.truncated)?;
snapshot.truncated = output.truncated;
for file in &mut snapshot.files {
if file.unstaged == Some(ChangeKind::Untracked) && file.path.ends_with('/') {
let (count, capped) = count_files_bounded(
&root.join(file.path.trim_end_matches('/')),
UNTRACKED_DIR_COUNT_CAP,
);
file.untracked_count = Some(count);
file.untracked_count_capped = capped;
}
}
count_untracked_folders(git, root, &mut snapshot.files);
snapshot.in_progress = in_progress(git, root)?;
Ok(snapshot)
}
Expand Down Expand Up @@ -214,33 +206,64 @@ pub fn list_untracked_directory(
Ok(UntrackedDirectory { files, truncated })
}

fn count_files_bounded(dir: &Path, cap: u32) -> (u32, bool) {
let mut queue: VecDeque<PathBuf> = VecDeque::new();
queue.push_back(dir.to_path_buf());
let mut count: u32 = 0;

while let Some(current) = queue.pop_front() {
let Ok(entries) = std::fs::read_dir(&current) else {
continue;
};
for entry in entries.flatten() {
if entry.file_name() == ".git" {
/// Fills in the file counts of collapsed untracked folders. Counts come from
/// `git ls-files --others --exclude-standard`, so ignored files are left out
/// and ignored directories are never walked. Output is byte-capped; a folder
/// whose count may be incomplete is marked capped. Counting is best effort:
/// if Git fails, the folders are shown without a count.
fn count_untracked_folders(git: &GitExecutor, root: &Path, files: &mut [FileStatus]) {
let mut folders: Vec<(String, usize)> = files
.iter()
.enumerate()
.filter(|(_, file)| {
file.unstaged == Some(ChangeKind::Untracked) && file.path.ends_with('/')
})
.map(|(index, file)| (file.path.clone(), index))
.collect();
if folders.is_empty() {
return;
}
folders.sort();
for chunk in folders.chunks(UNTRACKED_COUNT_CHUNK) {
let mut args: Vec<&str> = vec![
LITERAL,
"ls-files",
"--others",
"--exclude-standard",
"-z",
"--",
];
args.extend(chunk.iter().map(|(path, _)| path.as_str()));
let output: CappedOutput = match git.run_capped(root, args, MAX_STATUS_BYTES, &[0]) {
Ok(output) => output,
Err(error) => {
tracing::warn!(%error, "could not count untracked folder contents");
continue;
}
let Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_dir() {
queue.push_back(entry.path());
} else {
count = count.saturating_add(1);
if count >= cap {
return (cap, true);
}
};
let mut counts: Vec<u32> = vec![0; chunk.len()];
let mut entries = output.output.stdout.split(|byte: &u8| *byte == 0);
if output.truncated {
// The last entry may be cut off mid-path.
let _ = entries.next_back();
}
for entry in entries.filter(|entry: &&[u8]| !entry.is_empty()) {
let entry: std::borrow::Cow<'_, str> = String::from_utf8_lossy(entry);
// Folders are disjoint and sorted: the owner is the last one <= entry.
let owner: usize =
chunk.partition_point(|(folder, _)| folder.as_str() <= entry.as_ref());
if let Some(index) = owner.checked_sub(1)
&& entry.starts_with(chunk[index].0.as_str())
{
counts[index] = counts[index].saturating_add(1);
}
}
for ((_, file_index), count) in chunk.iter().zip(counts) {
let file: &mut FileStatus = &mut files[*file_index];
file.untracked_count = Some(count.min(UNTRACKED_DIR_COUNT_CAP));
file.untracked_count_capped = output.truncated || count >= UNTRACKED_DIR_COUNT_CAP;
}
}
(count, false)
}

/// Parses NUL-separated porcelain v2 status output.
Expand Down
52 changes: 52 additions & 0 deletions crates/git-engine/tests/changes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -610,3 +610,55 @@ fn untracked_directories_collapse_expand_and_discard() {
discard_paths(&repo.git, &repo.root(), &paths(&["new_dir/"])).expect("discard dir");
assert!(!repo.root().join("new_dir").exists());
}

#[test]
fn untracked_folder_counts_leave_out_ignored_files() {
let repo = TestRepo::new();
repo.commit_file(
".gitignore",
"node_modules/
*.log
",
"ignore",
);
repo.write(
"newpkg/index.js",
"x
",
);
repo.write(
"newpkg/debug.log",
"x
",
);
for index in 0..20 {
repo.write(
&format!("newpkg/node_modules/dep/{index}.js"),
"x
",
);
}
repo.write(
"other/a.txt",
"a
",
);
repo.write(
"other/b.txt",
"b
",
);

let status = read_status(&repo.git, &repo.root()).expect("status");
let count = |path: &str| {
let folder = status
.files
.iter()
.find(|file| file.path == path)
.unwrap_or_else(|| panic!("{path} missing from {:?}", status.files));
assert!(!folder.untracked_count_capped);
folder.untracked_count
};
assert_eq!(count("newpkg/"), Some(1));
assert_eq!(count("other/"), Some(2));
}
45 changes: 45 additions & 0 deletions crates/git-engine/tests/history_branches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,3 +551,48 @@ fn log_cursor_walks_branched_history_without_duplicates_and_writes_commit_graph(
.exists()
);
}

#[test]
fn log_cursor_pages_a_single_revision() {
let repo: TestRepo = TestRepo::new();
let mut oids: Vec<String> = Vec::new();
for index in 0..8 {
oids.push(repo.commit_file(
"f.txt",
&format!(
"{index}
"
),
&format!("c {index}"),
));
}
let revisions: Option<Vec<String>> = Some(vec!["main".to_owned()]);
let mut seen: Vec<String> = Vec::new();
let mut cursor: Option<Vec<String>> = None;
loop {
let page = log_page(
&repo.git,
&repo.root(),
&LogQuery {
revisions: revisions.clone(),
skip: u32::try_from(seen.len()).expect("small"),
cursor: cursor.clone(),
..query(3)
},
)
.expect("revision page");
seen.extend(page.commits.iter().map(|commit| commit.oid.clone()));
if !page.has_more {
break;
}
let next = page.next_cursor.expect("cursor for the next page");
assert!(
next.iter()
.all(|oid| oid.chars().all(|c| c.is_ascii_hexdigit())),
"cursor holds only commit ids: {next:?}"
);
cursor = Some(next);
}
oids.reverse();
assert_eq!(seen, oids);
}
Loading