docs(comments): rewrite comments across all crates to the guidelines

Sweep every first-party crate source (1956 .rs files) to the project comment
guidelines: delete redundant restatements, decorative banners, change
narration, and end-of-line comments; keep and tighten the crucial ones
(invariants, bug rationale, SAFETY blocks, ported-source attribution).

No functional code changed. Every edit is proven comment-only against the
prior tree by a comment-stripping lexer (string/char/raw-string aware) plus a
separate doctest-fence check. Where removing a comment made rustfmt or clippy
want to re-lay-out adjacent code, the minimal triggering comment is restored so
code tokens stay byte-identical.

Gates green: cargo fmt --all --check (0 diffs), cargo check and cargo clippy
--workspace --all-targets (0 warnings).

Adds scripts/check_codegen_comment_guidelines.py — the enforcement gate for
these guidelines (flags banners, end-of-line comments, change narration, and
commented-out code).
This commit is contained in:
2026-07-23 16:55:39 -04:00
parent ff0fb56c67
commit a02b555e66
1458 changed files with 10729 additions and 21750 deletions
@@ -3,7 +3,7 @@
//! All scenarios build ~12k total dirs so inotify-watch creation cost is
//! comparable across them:
//!
//! - `favorable` — most dirs live in a gitignored `target/` the new code skips.
//! - `favorable` — most dirs live in a gitignored `target/` that fan-out skips.
//! - `fanout_w48_with_target` — 48 non-ignored top-level children PLUS a
//! gitignored `target/`: a realistic moderate-width repo that fans out and
//! skips the build dir (net win).
@@ -38,8 +38,8 @@ fn make_dirs(base: &Path, count: usize) {
}
}
/// Favorable: three watched subtrees plus a large gitignored `target/` holding
/// ~2/3 of the dirs. Kept at ~`TOTAL_DIRS` for comparability with the others.
/// Three watched subtrees plus a large gitignored `target/` holding ~2/3 of
/// the dirs, totalling ~`TOTAL_DIRS` for comparability with the other shapes.
fn build_favorable_tree() -> TempDir {
let temp = TempDir::new().unwrap();
let root = temp.path();
@@ -105,7 +105,7 @@ fn gen_large(root: &Path) {
make_dirs(&root.join("target"), 34_000, 50);
}
/// Ground truth: total inotify watches held by this process (Linux).
/// Kernel-side ground truth for the crate's own accounting; always 0 off Linux.
fn inotify_watches() -> usize {
#[cfg(target_os = "linux")]
{
@@ -62,16 +62,13 @@ mod tests {
#[test]
fn classify_returns_none() {
let g = "/r/.git";
// Excluded git internals.
assert_eq!(classify("/r/.git/COMMIT_EDITMSG", g), None);
assert_eq!(classify("/r/.git/MERGE_HEAD", g), None);
assert_eq!(classify("/r/.git/objects/ab/1234", g), None);
assert_eq!(classify("/r/.git/index.lock", g), None);
// Workspace files.
assert_eq!(classify("/r/src/main.rs", g), None);
// Substring false-positive prevented by strip_prefix.
assert_eq!(classify("/r/.git-backup/HEAD", g), None);
// Path under a different git_dir.
assert_eq!(classify("/other/.git/HEAD", g), None);
}
+8 -10
View File
@@ -442,7 +442,7 @@ async fn event_loop(
) {
let mut state = LockState::Idle;
let mut stale_warn = StaleWarn::default();
// Baseline for the next op's head_changed: the head last observed while
// Baseline for the next op's `head_changed`: the head last observed while
// no op was running. Fast ops complete their whole lock cycle inside one
// debounce batch, so the batch-time head is already post-op; this keeps
// the pre-op value.
@@ -539,16 +539,16 @@ fn process_event(
}
// Accepted race: if a settle expires while the next op's lock event is
// still in the debounce window, the baseline recorded here is already
// that op's post-op head, so its Completed can read head_changed:false.
// Self-healing: buffered FilesChanged force the consumer's rebuild, and
// that op's post-op head, so its Completed can read `head_changed`:false.
// Self-healing: buffered `FilesChanged` force the consumer's rebuild, and
// the hunk refresh has its own head_oid/index-mtime check.
if matches!(state, LockState::Idle | LockState::Cooldown { .. }) {
*last_idle_head = head_now;
}
// While in_op: suppress GitMetaChanged (one wake on Completed, not N).
// While in_op: suppress `GitMetaChanged` (one wake on Completed, not N).
// Settling is in_op — the inter-cycle HEAD moves of a merged op must not
// leak as meta wakes — but not in_cooldown: FilesChanged keeps flowing
// leak as meta wakes — but not in_cooldown: `FilesChanged` keeps flowing
// during Locked/Settling (consumer buffers); Cooldown drops it.
let in_op = matches!(
state,
@@ -1078,9 +1078,7 @@ mod tests {
);
}
// ========================================================================
// Sapling (`.sl`) — the existing VCS-agnostic lock machine, fed `.sl` facts.
// ========================================================================
/// Two distinct 20-byte working-copy parents (p1) for head-change tests.
const SL_P1_A: [u8; 20] = [0x11; 20];
@@ -1221,7 +1219,7 @@ mod tests {
assert!(!lock_present(&VcsDirs::default()));
// Degraded: a present `.sl` with an unreadable dirstate stays Some("|")
// (head_changed:false path), not the no-repo None branch.
// (`head_changed`:false path), not the no-repo None branch.
let degraded = make_fake_sl_repo_no_lock();
std::fs::remove_file(degraded.path().join(".sl/dirstate")).unwrap();
assert_eq!(read_head(&sl_vcs(&degraded)), Some("|".to_string()));
@@ -1282,7 +1280,7 @@ mod tests {
#[test]
fn workspace_file_surfaces_when_root_under_unrelated_sl_ancestor() {
// A watch root under an unrelated `.sl` ancestor must not suppress its
// workspace files: a normal file still surfaces as FilesChanged.
// workspace files: a normal file still surfaces as `FilesChanged`.
let vcs = VcsDirs {
git_dir: None,
sl_dir: Some(PathBuf::from("/x/.sl/proj/.sl")),
@@ -1415,7 +1413,7 @@ mod tests {
cd(),
&out_tx,
);
// Exact: only Started (no stray FilesChanged from the wlock path).
// Exact: only Started (no stray `FilesChanged` from the wlock path).
assert_eq!(collect_events(&mut rx), vec![FsEvent::GitOperationStarted]);
// p1 moves while wlock is held, then wlock is released; Completed
+2 -2
View File
@@ -226,7 +226,7 @@ mod tests {
}
/// Settle expiry emits exactly one Completed comparing the first pick's
/// pre-op HEAD against the final HEAD (head_changed spans the merged op).
/// pre-op HEAD against the final HEAD (`head_changed` spans the merged op).
#[test]
fn settling_expiry_emits_completed_spanning_merged_op() {
let now = Instant::now();
@@ -300,7 +300,7 @@ mod tests {
}
/// Regression: timer-arm `drive()` must report Started so the consumer's
/// `in_op` flag flips; otherwise FilesChanged events skip buffering.
/// `in_op` flag flips; otherwise `FilesChanged` events skip buffering.
#[test]
fn cooldown_to_locked_when_lock_reappears_at_timer_fire() {
let now = Instant::now();
+33 -22
View File
@@ -101,7 +101,7 @@ fn is_git_path_for_watcher(path: &Path) -> bool {
}
/// Sapling analogue of [`is_git_path_for_watcher`]: lets **only** `.sl/wlock`
/// through. `.sl/dirstate` is intentionally not watched — it is read on demand,
/// through. `.sl/dirstate` is deliberately not watched — it is read on demand,
/// because a read-only `sl status` rewrites dirstate without moving the parent,
/// so watching it would turn every status into a refresh storm. Forward-slash
/// only, like its git sibling.
@@ -466,7 +466,8 @@ fn scan_per_dir_updates(
let is_dir = p.symlink_metadata().is_ok_and(|m| m.file_type().is_dir());
if is_dir {
if structural {
pruned.push(p.clone()); // Re-arm a possibly-dead watch.
// Re-arm a possibly-dead watch.
pruned.push(p.clone());
}
added.push(p.clone());
} else {
@@ -550,7 +551,8 @@ fn passes_custom_globs(
/// symlinks (so watches can't leave the workspace via a symlinked dir).
fn ignore_walker(root: &Path, max_depth: Option<usize>) -> ignore::Walk {
WalkBuilder::new(root)
.hidden(false) // Let gitignore, not the leading dot, decide.
// Let gitignore, not the leading dot, decide.
.hidden(false)
.git_ignore(true)
.git_global(true)
.git_exclude(true)
@@ -594,7 +596,8 @@ fn select_top_level_watch_dirs_capped(
let mut dirs = Vec::new();
for entry in ignore_walker(root, Some(1)).flatten() {
if entry.depth() == 0 {
continue; // `root` itself.
// `root` itself.
continue;
}
let path = entry.path();
if !entry.file_type().is_some_and(|ft| ft.is_dir()) {
@@ -607,7 +610,8 @@ fn select_top_level_watch_dirs_capped(
}
if passes_custom_globs(path, custom_ignore, custom_include) {
if dirs.len() == max {
return None; // one past the cap
// one past the cap
return None;
}
dirs.push(path.to_path_buf());
}
@@ -626,7 +630,8 @@ fn pruning_walker(
) -> ignore::Walk {
let mut walker = WalkBuilder::new(root);
walker
.hidden(false) // Let gitignore, not the leading dot, decide.
// Let gitignore, not the leading dot, decide.
.hidden(false)
.git_ignore(true)
.git_global(true)
.git_exclude(true)
@@ -636,11 +641,13 @@ fn pruning_walker(
let custom_include = custom_include.clone();
walker.filter_entry(move |entry| {
if !entry.file_type().is_some_and(|ft| ft.is_dir()) {
return true; // Files pass here; callers filter them separately.
// Files pass here; callers filter them separately.
return true;
}
let path = entry.path();
if dir_named(path, ".git") || dir_named(path, ".sl") {
return false; // VCS metadata is watched separately (or not at all).
// VCS metadata is watched separately (or not at all).
return false;
}
passes_custom_globs(path, &custom_ignore, &custom_include)
});
@@ -892,7 +899,8 @@ fn prune_subtree_watches(
.cloned()
.collect();
for dir in stale {
let _ = debouncer.unwatch(&dir); // Usually already gone; errors expected.
// Usually already gone; errors expected.
let _ = debouncer.unwatch(&dir);
watched.remove(&dir);
}
}
@@ -1121,7 +1129,8 @@ pub(crate) fn start_with_timeout(
let (head, tail): (Vec<PathBuf>, Vec<PathBuf>) = dirs
.into_iter()
.partition(|d| d.parent() == Some(watch_path.as_path()));
pending_dirs = tail.into(); // Still shallow-first.
// Still shallow-first.
pending_dirs = tail.into();
head
} else {
dirs
@@ -1420,11 +1429,9 @@ mod tests {
assert_eq!(map_event_kind(&EventKind::Other), None);
}
// ========================================================================
// Integration tests with real filesystem and debouncer
// These tests are serialized because macOS FSEvents has limited resources
// when many watchers are created simultaneously.
// ========================================================================
mod integration {
use super::*;
@@ -1706,7 +1713,8 @@ mod tests {
let watch_path = dunce::canonicalize(temp_dir.path()).unwrap();
let config = FsNotifyConfig {
debounce_ms: 50, // Slightly longer debounce to batch events
// Slightly longer debounce to batch events
debounce_ms: 50,
ignore_patterns: vec![],
};
@@ -1873,7 +1881,8 @@ mod tests {
};
let (mut rx, handle) = start_with_retry(watch_path.clone(), config).unwrap();
let _ = collect_events(&mut rx); // drain startup stragglers
// drain startup stragglers
let _ = collect_events(&mut rx);
// Drop joins the watcher thread, which drops the debouncer and the
// event sender. Run it on a watchdog thread so a broken Shutdown
@@ -1896,7 +1905,8 @@ mod tests {
let disconnected = loop {
match rx.try_recv() {
Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => break true,
Ok(_) => {} // drain any straggler before disconnect
// drain any straggler before disconnect
Ok(_) => {}
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
if std::time::Instant::now() >= deadline {
break false;
@@ -2015,7 +2025,8 @@ mod tests {
#[test]
#[serial]
#[ignore] // Flaky on macOS due to recursive watcher behavior
// Flaky on macOS due to recursive watcher behavior
#[ignore]
fn test_debouncer_git_directory_ignored() {
// .git directory contents should always be ignored
let temp_dir = TempDir::new().unwrap();
@@ -2373,8 +2384,8 @@ mod tests {
);
}
// ── per-dir strategy (Linux default; forced here so it runs on any
// platform without process-global env races) ──────────────────────
// per-dir strategy (Linux default; forced here so it runs on any
// platform without process-global env races)
/// Watch-count accounting: nested gitignored dirs cost zero watches
/// and `.git` costs a handful, not one per internal dir.
@@ -2545,9 +2556,7 @@ mod tests {
}
}
// ========================================================================
// Unit tests for merge_events and build_globsets
// ========================================================================
mod merge_events_tests {
use super::*;
@@ -3517,7 +3526,8 @@ mod tests {
let temp = TempDir::new().unwrap();
let new_dir = temp.path().join("new");
fs::create_dir(&new_dir).unwrap();
let old_dir = temp.path().join("old"); // never created — "moved away"
// never created — "moved away"
let old_dir = temp.path().join("old");
let mut pruned = Vec::new();
let mut added = Vec::new();
@@ -3663,7 +3673,8 @@ mod tests {
// A `.git` SYMLINK to an external (non-git) dir must NOT be followed
// and watched: the cheap dir branch is gated on a real (non-symlink)
// dir, and git validation rejects the target.
let external = TempDir::new().unwrap(); // stands in for ~/.ssh, /etc
// stands in for ~/.ssh, /etc
let external = TempDir::new().unwrap();
let proj = TempDir::new().unwrap();
std::os::unix::fs::symlink(external.path(), proj.path().join(".git")).unwrap();
@@ -1,9 +1,8 @@
//! Integration tests using the public API only. Each test exercises the
//! real OS watcher against a `tempfile`-rooted fake git repo.
//!
//! These can be flaky on some CI runners where FS events aren't reliably
//! delivered (matches the existing pattern in `watcher.rs` integration
//! tests). Marked `#[ignore]` for now; run locally with
//! The watcher-driven tests are `#[ignore]`d because some CI runners do not
//! reliably deliver FS events. Run them locally with
//! `cargo test --test integration -- --ignored`.
use std::fs;
@@ -224,8 +223,8 @@ async fn source_emits_completed_with_head_change_on_sl_goto() {
.await
.unwrap();
// Move the working-copy parent (p1) before releasing wlock, then release.
// `read_head` reads the new p1 on demand when the wlock-removal is processed.
// `read_head` reads p1 on demand when the wlock removal is processed, so
// p1 must move before the release for the change to be observed.
fs::write(temp.path().join(".sl/dirstate"), sl_dirstate(0x22)).unwrap();
fs::remove_file(&wlock).unwrap();
@@ -251,9 +250,7 @@ async fn shared_dedupes_by_directory() {
let temp = TempDir::new().unwrap();
let path = temp.path().to_path_buf();
// First call creates the watcher; subsequent calls for the same canonical
// directory hand back clones of the *same* source rather than opening a
// new OS watch. Skip gracefully where the OS denies watches (CI limits).
// Skip gracefully where the OS denies watches (CI descriptor limits).
let Ok(a) = kigi_fsnotify::shared(path.clone(), FsConfig::default()) else {
eprintln!("skipping: OS watcher unavailable (resource limit?)");
return;
@@ -267,7 +264,6 @@ async fn shared_dedupes_by_directory() {
"second shared() must clone the existing source, not create a new one"
);
// The reuse must be counted as a cache hit (no new OS watcher created).
let after = kigi_fsnotify::stats();
assert_eq!(
after.reused_total - before.reused_total,
@@ -280,7 +276,6 @@ async fn shared_dedupes_by_directory() {
);
assert!(after.live_watchers >= 1, "the shared watcher must be live");
// A different directory gets its own independent watcher (a real miss).
let other = TempDir::new().unwrap();
let c = kigi_fsnotify::shared(other.path().to_path_buf(), FsConfig::default()).unwrap();
assert!(!Arc::ptr_eq(&a, &c), "different dirs must not share");
@@ -290,8 +285,7 @@ async fn shared_dedupes_by_directory() {
"a new directory must create a new watcher"
);
// Once the last sharer drops, the registry entry is reclaimed and a later
// request rebuilds a fresh source (exercises the recreate-after-drop path).
// Dropping the last sharer must reclaim the registry entry.
drop(a);
drop(b);
let d = kigi_fsnotify::shared(path, FsConfig::default()).unwrap();
@@ -340,7 +334,6 @@ async fn shared_watcher_scaling_demo() {
" before sharing this needed {SESSIONS} OS watchers; after sharing it needs {created}."
);
// One real OS watch for the whole fleet; the rest are cache hits.
assert_eq!(created, 1, "all sessions on one cwd share a single watcher");
assert_eq!(reused, (SESSIONS - 1) as u64);
assert!(after.live_watchers >= 1);