diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 000000000..e0828fa5b --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,8 @@ +[profile.default] +# Keep nextest's 200 ms threshold, but do not accept leaked output handles as a pass. +leak-timeout = { period = "200ms", result = "fail" } + +[[profile.default.overrides]] +# This otherwise starts near the end and leaves the other test workers idle. +filter = 'test(=highlight::tests::shipped_syntax_set_compiles_under_active_regex_backend)' +priority = 100 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c73793edb..b7f409b41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,34 +21,71 @@ env: RUST_BACKTRACE: 1 jobs: - desktop: - name: ${{ matrix.name }} - runs-on: ${{ matrix.os }} + # Not a matrix: a job can only wait for a whole matrix, and each platform's + # required check must wait for that platform's Clippy and tests alone. + linux-clippy: + name: Linux x64 / clippy + runs-on: ubuntu-24.04 timeout-minutes: 60 - strategy: - fail-fast: false - matrix: - include: - - name: Linux x64 - os: ubuntu-24.04 - - name: macOS arm64 - os: macos-26 - - name: Windows x64 - os: windows-2022 - steps: - - uses: actions/checkout@v7 + steps: &clippy-steps + - &checkout + uses: actions/checkout@v7 - - name: Disable Windows Defender real-time scanning + - &disable-defender + name: Disable Windows Defender real-time scanning if: runner.os == 'Windows' shell: pwsh continue-on-error: true run: Set-MpPreference -DisableRealtimeMonitoring $true - - name: Install stable Rust + - &install-rust + name: Install stable Rust uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy + # Clippy restores the test jobs' cache but never saves its own: it already + # finishes before the tests, and a second cache per platform would overflow + # the repository's Actions cache quota and evict the test caches. + - name: Restore Cargo build data + uses: Swatinem/rust-cache@v2 + with: + shared-key: ci-${{ runner.os }}-${{ runner.arch }} + save-if: false + + - &install-linux-dependencies + name: Install Linux system dependencies + if: runner.os == 'Linux' + run: | + # The Azure mirror has delivered packages at ~65 kB/s on these runners. + for source in /etc/apt/sources.list.d/ubuntu.sources /etc/apt/apt-mirrors.txt; do + if [[ -f "$source" ]]; then + sudo sed -i 's|http://azure\.archive\.ubuntu\.com/ubuntu|https://archive.ubuntu.com/ubuntu|g' "$source" + fi + done + apt_get=(sudo apt-get -o Acquire::ForceIPv4=true -o Acquire::Retries=3) + "${apt_get[@]}" update + "${apt_get[@]}" install -y --no-install-recommends \ + build-essential clang cmake pkg-config libssl-dev libzstd-dev \ + libasound2-dev libfontconfig-dev libwayland-dev libxkbcommon-dev \ + libxkbcommon-x11-dev libx11-xcb-dev libxcb1-dev libgbm-dev \ + libvulkan-dev xvfb + + - name: Check formatting + run: cargo fmt --all --check + + - name: Run Clippy + run: cargo clippy --workspace --all-targets --locked -- -D warnings + + linux-tests: + name: Linux x64 / tests + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: &test-steps + - *checkout + - *disable-defender + - *install-rust + # Only main writes the cache so pull requests share one warm copy per # platform instead of evicting each other from the repository quota. - name: Cache Cargo build data @@ -73,26 +110,15 @@ jobs: Expand-Archive -Path $archive -DestinationPath "$env:USERPROFILE\.cargo\bin" -Force cargo nextest --version - - name: Install Linux system dependencies - if: runner.os == 'Linux' - run: | - apt_get=(sudo apt-get -o Acquire::ForceIPv4=true -o Acquire::Retries=3) - "${apt_get[@]}" update - "${apt_get[@]}" install -y --no-install-recommends \ - build-essential clang cmake pkg-config libssl-dev libzstd-dev \ - libasound2-dev libfontconfig-dev libwayland-dev libxkbcommon-dev \ - libxkbcommon-x11-dev libx11-xcb-dev libxcb1-dev libgbm-dev \ - libvulkan-dev xvfb - if cargo tree -e normal -i glib-sys >/dev/null 2>&1; then - "${apt_get[@]}" install -y --no-install-recommends \ - libgtk-3-dev libwebkit2gtk-4.1-dev - fi - - - name: Check formatting - run: cargo fmt --all --check + - *install-linux-dependencies - - name: Run Clippy - run: cargo clippy --workspace --all-targets --locked -- -D warnings + # Two slots per CPU: most tests wait on child processes rather than compute. + - name: Set nextest test concurrency + shell: python + run: | + import os + with open(os.environ["GITHUB_ENV"], "a") as env_file: + env_file.write(f"NEXTEST_TEST_THREADS={os.cpu_count() * 2}\n") - name: Run tests if: runner.os != 'Linux' @@ -106,6 +132,60 @@ jobs: if: runner.os == 'Linux' run: xvfb-run -a cargo nextest run --workspace --locked + macos-clippy: + name: macOS arm64 / clippy + runs-on: macos-26 + timeout-minutes: 60 + steps: *clippy-steps + + macos-tests: + name: macOS arm64 / tests + runs-on: macos-26 + timeout-minutes: 60 + steps: *test-steps + + windows-clippy: + name: Windows x64 / clippy + runs-on: windows-2022 + timeout-minutes: 60 + steps: *clippy-steps + + windows-tests: + name: Windows x64 / tests + runs-on: windows-2022 + timeout-minutes: 60 + steps: *test-steps + + # The required checks keep their platform names. A skipped or cancelled job + # must not let its platform's check pass. + linux: + name: Linux x64 + needs: [linux-clippy, linux-tests] + if: always() + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: &require-platform + - name: Require the platform's Clippy and tests + env: + RESULTS: ${{ join(needs.*.result, ' ') }} + run: test "$RESULTS" = "success success" + + macos: + name: macOS arm64 + needs: [macos-clippy, macos-tests] + if: always() + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: *require-platform + + windows: + name: Windows x64 + needs: [windows-clippy, windows-tests] + if: always() + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: *require-platform + dependencies: name: Dependency hygiene runs-on: ubuntu-24.04 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6ea5d546b..b8803cc5c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,6 +17,8 @@ concurrency: group: release-${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }} cancel-in-progress: false +# Tag-scoped Cargo caches cannot warm the next release and evict the main CI +# caches from the shared Actions quota. jobs: setup: runs-on: ubuntu-24.04 @@ -98,11 +100,6 @@ jobs: with: targets: ${{ matrix.target }} - - name: Cache Cargo build data - uses: Swatinem/rust-cache@v2 - with: - shared-key: release-${{ matrix.target }} - - name: Install Linux system dependencies if: matrix.platform == 'linux' run: | @@ -112,10 +109,6 @@ jobs: build-essential clang cmake pkg-config libssl-dev libzstd-dev \ libasound2-dev libfontconfig-dev libwayland-dev libxkbcommon-dev \ libxkbcommon-x11-dev libx11-xcb-dev libxcb1-dev libgbm-dev libvulkan-dev - if cargo tree -e normal -i glib-sys >/dev/null 2>&1; then - "${apt_get[@]}" install -y --no-install-recommends \ - libgtk-3-dev libwebkit2gtk-4.1-dev - fi - name: Build release binary shell: bash @@ -416,11 +409,6 @@ jobs: with: targets: wasm32-unknown-unknown - - name: Cache Cargo build data - uses: Swatinem/rust-cache@v2 - with: - shared-key: release-web-bundle - - name: Install wasm tools run: | cargo install wasm-bindgen-cli --version 0.2.127 --locked @@ -504,11 +492,6 @@ jobs: with: targets: ${{ matrix.target }} - - name: Cache Cargo build data - uses: Swatinem/rust-cache@v2 - with: - shared-key: release-headless-${{ matrix.target }} - - name: Install Linux system dependencies if: matrix.platform == 'linux' run: | @@ -614,11 +597,6 @@ jobs: with: targets: ${{ matrix.target }} - - name: Cache Cargo build data - uses: Swatinem/rust-cache@v2 - with: - shared-key: release-traverse-${{ matrix.target }} - - name: Install Linux system dependencies if: matrix.platform == 'linux' run: | @@ -683,11 +661,6 @@ jobs: with: targets: aarch64-linux-android - - name: Cache Cargo build data - uses: Swatinem/rust-cache@v2 - with: - shared-key: release-android-arm64 - - name: Set up JDK 21 uses: actions/setup-java@v6 with: diff --git a/Cargo.lock b/Cargo.lock index 27f4612fe..dd23e892d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -170,6 +170,7 @@ dependencies = [ "toml 1.1.6+spec-1.1.0", "ureq", "uuid", + "windows 0.62.2", ] [[package]] diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml index 595d5ba19..d3eac58df 100644 --- a/crates/agent/Cargo.toml +++ b/crates/agent/Cargo.toml @@ -13,6 +13,7 @@ process = [ "dep:smol", "dep:ureq", "dep:uuid", + "dep:windows", ] [dependencies] @@ -31,6 +32,9 @@ smol = { version = "2", optional = true } ureq = { version = "2", default-features = false, features = ["tls", "gzip"], optional = true } uuid = { version = "1", features = ["v4"], optional = true } +[target.'cfg(windows)'.dependencies] +windows = { version = "=0.62.2", features = ["Win32_Foundation"], optional = true } + [dev-dependencies] env_logger = "0.11" toml = "1.1" diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs index fb6b4d17d..4a0b25e44 100644 --- a/crates/agent/src/lib.rs +++ b/crates/agent/src/lib.rs @@ -38,6 +38,8 @@ pub mod pi; #[cfg(feature = "process")] mod process; #[cfg(feature = "process")] +pub use process::keep_own_stdio_from_children; +#[cfg(feature = "process")] mod subagent_tail; use std::path::PathBuf; diff --git a/crates/agent/src/process.rs b/crates/agent/src/process.rs index 789273bba..5b517c576 100644 --- a/crates/agent/src/process.rs +++ b/crates/agent/src/process.rs @@ -1,4 +1,5 @@ -//! Child-process constructors that never flash a console window on Windows. +//! Child-process constructors that never flash a console window on Windows, +//! and never hand a child this process's own standard handles. //! //! Provider CLIs are spawned from a GUI app; a plain `Command` on Windows //! allocates a console for the child, which pops a black box on screen. @@ -17,8 +18,41 @@ const STDERR_TAIL_LINES: usize = 20; #[cfg(windows)] const CREATE_NO_WINDOW: u32 = 0x0800_0000; +/// Keep this process's own standard handles out of every child it starts. +/// +/// Windows gives a child each inheritable handle of its parent, not only the +/// stdio its `Command` names, so a child that outlives the parent keeps open +/// the pipes whoever runs the parent reads from. A child spawned with +/// `Stdio::inherit` still gets them: std hands it an inheritable duplicate. +/// No-op elsewhere. +pub fn keep_own_stdio_from_children() { + #[cfg(windows)] + { + use std::os::windows::io::AsRawHandle as _; + use windows::Win32::Foundation::{ + HANDLE, HANDLE_FLAG_INHERIT, HANDLE_FLAGS, SetHandleInformation, + }; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + for handle in [ + std::io::stdin().as_raw_handle(), + std::io::stdout().as_raw_handle(), + std::io::stderr().as_raw_handle(), + ] { + // SAFETY: these are this process's standard handles, open for + // its lifetime; a missing one only makes the call fail, which + // leaves nothing to keep from a child. + let _ = unsafe { + SetHandleInformation(HANDLE(handle), HANDLE_FLAG_INHERIT.0, HANDLE_FLAGS(0)) + }; + } + }); + } +} + /// A blocking `std::process::Command` with the console suppressed. pub(crate) fn command>(program: S) -> std::process::Command { + keep_own_stdio_from_children(); #[cfg_attr(not(windows), allow(unused_mut))] // Approved constructor: this is the helper every other site must use. #[allow(clippy::disallowed_methods)] diff --git a/crates/runtime/src/app/pull_request_watch_tests.rs b/crates/runtime/src/app/pull_request_watch_tests.rs index 80d4162bf..98d123639 100644 --- a/crates/runtime/src/app/pull_request_watch_tests.rs +++ b/crates/runtime/src/app/pull_request_watch_tests.rs @@ -323,6 +323,10 @@ impl Harness { ] { self.events.try_send(event).unwrap(); } + // The host's event pump queues each event for the host as it takes it, + // whether or not the host still acts on it. + let events = self.events.clone(); + self.cx.run_until(|_| events.is_empty()); self.cx.run_until_parked(); } @@ -837,7 +841,11 @@ fn a_wake_steers_into_a_running_turn_and_is_not_repeated() { .events .try_send(AgentEvent::TurnAccepted { delivery_id }) .unwrap(); - harness.cx.run_until_parked(); + harness.cx.run_until(|state| { + state + .resident("thread") + .is_some_and(|session| session.delivery_in_flight.is_none() && session.turn_in_flight) + }); harness.pass(); let commands = harness.commands.clone(); diff --git a/crates/runtime/src/app/pull_requests.rs b/crates/runtime/src/app/pull_requests.rs index 4a2304ad2..a25efd4f0 100644 --- a/crates/runtime/src/app/pull_requests.rs +++ b/crates/runtime/src/app/pull_requests.rs @@ -8,7 +8,7 @@ use tcode_protocol::{ CommandResponse, ProtocolError, PullRequestAction, PullRequestActionResult, PullRequestRead, PullRequestReadResponse, QueryResponse, }; -use tcode_services::forge::{Forge, ForgeError, ForgeErrorKind, Summary}; +use tcode_services::forge::{Checkout, Forge, ForgeError, ForgeErrorKind, Summary}; pub(super) struct PullRequestRuntime { pub(super) forge: Arc, @@ -170,7 +170,7 @@ fn resolve_reference( message: format!("This project has no {hosts} repository. Use a full PR URL."), }; let key = forge - .checkout_repository(cwd) + .checkout_repository(&Checkout::new(cwd)) .ok_or_else(no_repository)? .key(number); let url = forge.url(&key).ok_or_else(no_repository)?; @@ -431,7 +431,11 @@ impl AppState { let name = target.repository.ok_or_else(missing)?; let host = target .host - .or_else(|| forge.checkout_repository(&cwd).map(|r| r.host)) + .or_else(|| { + forge + .checkout_repository(&Checkout::new(&cwd)) + .map(|r| r.host) + }) .ok_or_else(|| "Pass host or a full PR URL.".to_owned())?; let invalid = || format!("Invalid {hosts} repository."); let key = forge @@ -1485,7 +1489,9 @@ impl AppState { metas, cwd, root, - host.unblock(move || forge.discover(&read_cwd, &read_root, refresh)), + host.unblock(move || { + forge.discover(&read_cwd, &Checkout::new(&read_root), refresh) + }), )); } for (metas, cwd, root, task) in tasks { diff --git a/crates/runtime/src/app/pull_requests_tests.rs b/crates/runtime/src/app/pull_requests_tests.rs index be7f3dfb7..06e390f79 100644 --- a/crates/runtime/src/app/pull_requests_tests.rs +++ b/crates/runtime/src/app/pull_requests_tests.rs @@ -100,6 +100,8 @@ fn linked_meta(id: &str, settled: bool) -> SessionMeta { meta } fn sweep(state: &TestEntity, cx: &mut TestAppContext) { + // A sweep that finds a sync still running is skipped; let that one finish. + cx.run_until(|state| !state.pull_requests.syncing); state.update(cx, |state, cx| { state.sweep_pull_requests(false, cx).detach() }); @@ -1045,7 +1047,11 @@ fn instructions_reach_the_provider_at_launch_and_no_turn_carries_them() { .events .try_send(AgentEvent::TurnAccepted { delivery_id }) .unwrap(); - cx.run_until_parked(); + cx.run_until(|state| { + state + .resident("thread") + .is_some_and(|session| session.delivery_in_flight.is_none()) + }); let stored = store .read_events("thread") .unwrap() @@ -1091,9 +1097,11 @@ fn instructions_reach_the_provider_at_launch_and_no_turn_carries_them() { .events .try_send(AgentEvent::McpServersNotAttached) .unwrap(); - cx.run_until_parked(); + cx.run_until(|state| { + let tools = state.session_status_snapshot("thread").unwrap(); + !tools.pull_request_tools.unwrap().attached + }); let tools = disclosed(&state); - assert!(!tools.attached); assert!(tools.instructions.is_empty()); assert!(!tools.tools.is_empty()); } @@ -2316,7 +2324,10 @@ fn a_partly_posted_review_keeps_only_unposted_drafts_for_the_next_submission() { fn pull_request_url(&self, _: &str) -> Option<(PullRequestKey, String)> { unreachable!() } - fn checkout_repository(&self, _: &Path) -> Option { + fn checkout_repository( + &self, + _: &tcode_services::forge::Checkout<'_>, + ) -> Option { unreachable!() } fn repository(&self, _: &str, _: &str) -> Option { @@ -2325,7 +2336,12 @@ fn a_partly_posted_review_keeps_only_unposted_drafts_for_the_next_submission() { fn url(&self, _: &PullRequestKey) -> Option { unreachable!() } - fn discover(&self, _: &Path, _: &Path, _: bool) -> Result, ForgeError> { + fn discover( + &self, + _: &Path, + _: &tcode_services::forge::Checkout<'_>, + _: bool, + ) -> Result, ForgeError> { unreachable!() } fn summary(&self, _: &PullRequestKey) -> Result { diff --git a/crates/runtime/src/app/test_support.rs b/crates/runtime/src/app/test_support.rs index e8b18cb6f..8be7e6d86 100644 --- a/crates/runtime/src/app/test_support.rs +++ b/crates/runtime/src/app/test_support.rs @@ -79,6 +79,10 @@ impl TestAppContext { HostCx::new(self.mailbox_tx.clone(), self.outgoing_tx.clone()) } + /// Run what is already queued for the host, and what that queues in turn, + /// until the mailbox is empty. Work running off the host (thread-pool + /// hops, timers) reports only when it finishes; a test that needs its + /// result waits for that state with [`Self::run_until`]. pub(super) fn run_until_parked(&mut self) { let state = self .state @@ -86,11 +90,13 @@ impl TestAppContext { .and_then(Weak::upgrade) .expect("test state must outlive its context"); let deadline = Instant::now() + Duration::from_secs(5); - let mut idle_passes = 0_u32; - let mut saw_work = false; let mut store_flushed = false; - while Instant::now() < deadline { + loop { + assert!( + Instant::now() < deadline, + "test host failed to park within five seconds" + ); let mut had_work = false; while let Ok(message) = self.mailbox_rx.try_recv() { had_work = true; @@ -104,44 +110,30 @@ impl TestAppContext { had_work = true; } if had_work { - idle_passes = 0; - saw_work = true; store_flushed = false; - } else { - idle_passes += 1; - // Loaded CI runners (notably Windows) can take well past 50ms - // to schedule a background completion; calls that processed - // work get a wider idle window before declaring parked. - let threshold = if saw_work && !store_flushed { 250 } else { 50 }; - if idle_passes >= threshold { - if !store_flushed { - // Barrier the store-writer task so persisted state is - // visible before callers assert on it. Its failure - // path can enqueue more work, so keep draining. - store_flushed = true; - if self.flush_store_writer(&state, deadline) { - idle_passes = 0; - continue; - } - } - let mut host_cx = self.host_cx(); - state.borrow().sync_terminal_handles(); - self.domain_diff - .as_mut() - .expect("test domain diff must be initialized") - .emit_changes(&mut state.borrow_mut(), &mut host_cx); - return; + continue; + } + if !store_flushed { + // Barrier the store-writer task so persisted state is + // visible before callers assert on it. Its failure path can + // enqueue more work, so keep draining. + store_flushed = true; + if self.flush_store_writer(&state, deadline) { + continue; } } - std::thread::sleep(Duration::from_millis(1)); + break; } - panic!("test host failed to park within five seconds"); + let mut host_cx = self.host_cx(); + state.borrow().sync_terminal_handles(); + self.domain_diff + .as_mut() + .expect("test domain diff must be initialized") + .emit_changes(&mut state.borrow_mut(), &mut host_cx); } /// Park repeatedly until `done` observes the state a background chain - /// must reach. `run_until_parked` only watches the mailbox, so a chain - /// that hops through `unblock` (thread-pool filesystem work) between the - /// last event and its completion can look idle longer than the window. + /// must reach. pub(super) fn run_until(&mut self, mut done: impl FnMut(&TestClientState) -> bool) { let deadline = Instant::now() + Duration::from_secs(5); loop { @@ -158,6 +150,7 @@ impl TestAppContext { Instant::now() < deadline, "test host condition not reached within five seconds" ); + std::thread::sleep(Duration::from_millis(1)); } } diff --git a/crates/runtime/src/app/tests.rs b/crates/runtime/src/app/tests.rs index 76aa21a5e..eaa786c81 100644 --- a/crates/runtime/src/app/tests.rs +++ b/crates/runtime/src/app/tests.rs @@ -340,13 +340,28 @@ fn assert_native_mirror_turn_lifecycle(evict: bool, late: bool, end: MirrorEnd, state.load_background_session(meta, cx); } }); + // The turn's end can show before its last reply is folded in. + let replies = |mirror: &ActiveSession| { + mirror + .timeline + .entries + .iter() + .filter(|entry| { + matches!( + entry.content, + EntryContent::Item(ItemContent::AssistantMessage { .. }) + ) + }) + .count() + }; cx.run_until(|state| { state.resident(&mirror_id).is_some_and(|mirror| { - mirror - .timeline - .turns - .first() - .is_some_and(|turn| turn.end_ts.is_some()) + replies(mirror) == expected_items + && mirror + .timeline + .turns + .first() + .is_some_and(|turn| turn.end_ts.is_some()) }) }); state.update(cx, |state, _| { @@ -365,18 +380,6 @@ fn assert_native_mirror_turn_lifecycle(evict: bool, late: bool, end: MirrorEnd, .activity .working ); - assert_eq!( - mirror - .timeline - .entries - .iter() - .filter(|entry| matches!( - entry.content, - EntryContent::Item(ItemContent::AssistantMessage { .. }) - )) - .count(), - expected_items - ); }); } @@ -9355,6 +9358,8 @@ fn an_appended_snapshot_drops_the_superseded_ones_diffs_in_the_same_commit() { &through_pipe(&state, cx, 1, subscribe_events("thread", None)), 1, ); + // The window can be served before the whole log is read and kept. + cx.run_until(|state| state.event_records.contains_key("thread")); let snapshot = |diff: &str| AgentEvent::TurnChangesUpdated { turn_id: "t".into(), changes: vec![agent::FileChange { @@ -10279,9 +10284,10 @@ fn pages_and_outputs_of_a_thread_nobody_opened_are_read_and_not_kept() { query_reply(&through_pipe(&state, cx, 2, read_output), 2), QueryResponse::ItemOutput(output) ); + // The bounded read answers first; the whole log's read finishes after. + cx.run_until(|state| state.log_hydrations.is_empty()); state.read(|state| { assert!(state.resident("cold").is_none()); - assert!(state.log_hydrations.is_empty()); assert!(state.event_records.is_empty()); }); } @@ -11511,7 +11517,7 @@ fn a_finished_child_holds_its_lead_until_settled_and_cancel_never_delivers() { let op = |state: &TestEntity, cx: &mut TestAppContext, op| { let (reply, response) = smol::channel::bounded(1); state.update(cx, |state, cx| state.handle_orchestrate_op(op, reply, cx)); - cx.run_until_parked(); + cx.run_until(|_| !response.is_empty()); response.try_recv().unwrap() }; // Every run here started and ended at `stamp`. diff --git a/crates/services/src/azure/mod.rs b/crates/services/src/azure/mod.rs index b14c71b9b..f30e7d869 100644 --- a/crates/services/src/azure/mod.rs +++ b/crates/services/src/azure/mod.rs @@ -753,8 +753,8 @@ impl Forge for Azure { repository::pull_request_url(url) } - fn checkout_repository(&self, cwd: &Path) -> Option { - repository::resolve(cwd) + fn checkout_repository(&self, checkout: &crate::forge::Checkout<'_>) -> Option { + repository::resolve(checkout) } fn repository(&self, name: &str, host: &str) -> Option { @@ -770,14 +770,14 @@ impl Forge for Azure { fn discover( &self, cwd: &Path, - root: &Path, + root: &crate::forge::Checkout<'_>, refresh: bool, ) -> Result, ForgeError> { - let cwd = if cwd.exists() { cwd } else { root }; + let cwd = if cwd.exists() { cwd } else { root.cwd() }; let Some(target) = repository::resolve(root) else { return Ok(None); }; - let Some(branch) = repository::branch(cwd) else { + let Some(branch) = repository::branch(root, cwd) else { return Ok(None); }; let slot = ( diff --git a/crates/services/src/azure/repository.rs b/crates/services/src/azure/repository.rs index 6181c00df..2666b9cff 100644 --- a/crates/services/src/azure/repository.rs +++ b/crates/services/src/azure/repository.rs @@ -141,12 +141,15 @@ pub(super) fn selector(value: &str, host: &str) -> Option { ) } -pub(super) fn resolve(cwd: &Path) -> Option { - crate::forge::checkout::resolve(cwd, remote) +pub(super) fn resolve(checkout: &crate::forge::Checkout<'_>) -> Option { + crate::forge::checkout::resolve(checkout, remote) } -pub(super) fn branch(cwd: &Path) -> Option { - crate::forge::checkout::branch(cwd, remote) +pub(super) fn branch( + root: &crate::forge::Checkout<'_>, + cwd: &Path, +) -> Option { + crate::forge::checkout::branch(root, cwd, remote) } #[cfg(test)] diff --git a/crates/services/src/bitbucket/mod.rs b/crates/services/src/bitbucket/mod.rs index ad2fda5e3..ea4c8ab72 100644 --- a/crates/services/src/bitbucket/mod.rs +++ b/crates/services/src/bitbucket/mod.rs @@ -609,8 +609,8 @@ impl Forge for Bitbucket { repository::pull_request_url(url) } - fn checkout_repository(&self, cwd: &Path) -> Option { - repository::resolve(cwd) + fn checkout_repository(&self, checkout: &crate::forge::Checkout<'_>) -> Option { + repository::resolve(checkout) } fn repository(&self, name: &str, _: &str) -> Option { @@ -626,14 +626,14 @@ impl Forge for Bitbucket { fn discover( &self, cwd: &Path, - root: &Path, + root: &crate::forge::Checkout<'_>, refresh: bool, ) -> Result, ForgeError> { - let cwd = if cwd.exists() { cwd } else { root }; + let cwd = if cwd.exists() { cwd } else { root.cwd() }; let Some(target) = repository::resolve(root) else { return Ok(None); }; - let Some(branch) = repository::branch(cwd) else { + let Some(branch) = repository::branch(root, cwd) else { return Ok(None); }; let slot = ( diff --git a/crates/services/src/bitbucket/repository.rs b/crates/services/src/bitbucket/repository.rs index acf787c05..cb17f1cca 100644 --- a/crates/services/src/bitbucket/repository.rs +++ b/crates/services/src/bitbucket/repository.rs @@ -91,12 +91,15 @@ pub(super) fn remote(value: &str) -> Option { repository(&segments) } -pub(super) fn resolve(cwd: &Path) -> Option { - crate::forge::checkout::resolve(cwd, remote) +pub(super) fn resolve(checkout: &crate::forge::Checkout<'_>) -> Option { + crate::forge::checkout::resolve(checkout, remote) } -pub(super) fn branch(cwd: &Path) -> Option { - crate::forge::checkout::branch(cwd, remote) +pub(super) fn branch( + root: &crate::forge::Checkout<'_>, + cwd: &Path, +) -> Option { + crate::forge::checkout::branch(root, cwd, remote) } #[cfg(test)] diff --git a/crates/services/src/forge.rs b/crates/services/src/forge.rs index 40e06ab4e..fb0230a05 100644 --- a/crates/services/src/forge.rs +++ b/crates/services/src/forge.rs @@ -5,6 +5,7 @@ pub(crate) mod anchors; pub(crate) mod checkout; +pub use checkout::Checkout; mod http; mod rate_limit; #[cfg(test)] @@ -74,7 +75,7 @@ pub trait Forge: Send + Sync { /// The key and canonical URL of a pull request's web URL, or `None` for any other URL. fn pull_request_url(&self, url: &str) -> Option<(PullRequestKey, String)>; /// The repository a checkout's remote names on the host. - fn checkout_repository(&self, cwd: &Path) -> Option; + fn checkout_repository(&self, checkout: &Checkout<'_>) -> Option; /// A repository named as the host writes it, on `host`. fn repository(&self, name: &str, host: &str) -> Option; /// The web URL of a pull request. @@ -85,7 +86,7 @@ pub trait Forge: Send + Sync { fn discover( &self, cwd: &Path, - root: &Path, + root: &Checkout<'_>, refresh: bool, ) -> Result, ForgeError>; @@ -511,10 +512,10 @@ impl Forge for Hosts { }) } - fn checkout_repository(&self, cwd: &Path) -> Option { + fn checkout_repository(&self, checkout: &Checkout<'_>) -> Option { self.all().into_iter().find_map(|forge| { forge - .checkout_repository(cwd) + .checkout_repository(checkout) .filter(|repository| self.serves(forge, &repository.host)) }) } @@ -530,7 +531,7 @@ impl Forge for Hosts { fn discover( &self, cwd: &Path, - root: &Path, + root: &Checkout<'_>, refresh: bool, ) -> Result, ForgeError> { let Some(repository) = self.checkout_repository(root) else { @@ -679,6 +680,49 @@ impl Forge for Hosts { mod tests { use super::*; + #[test] + fn checkout_routing_follows_git_init_and_remote_changes() { + let root = std::env::temp_dir().join(format!("tcode-checkout-{}", uuid::Uuid::new_v4())); + let cwd = root.join("checkout"); + std::fs::create_dir_all(&cwd).unwrap(); + let forge = connect(SettingsStore::new(root.clone()), []); + let git = |args: &[&str]| crate::git::run_git(&cwd, args).unwrap(); + let repository = || forge.checkout_repository(&Checkout::new(&cwd)); + assert!(repository().is_none()); + git(&["init", "-b", "main"]); + assert!(repository().is_none()); + git(&["remote", "add", "origin", "https://github.com/team/app.git"]); + for (url, host, name) in [ + ("https://github.com/team/app.git", "github.com", "team/app"), + ( + "https://codeberg.org/team/app.git", + "codeberg.org", + "team/app", + ), + ("https://gitlab.com/team/app.git", "gitlab.com", "team/app"), + ( + "https://bitbucket.org/team/app.git", + "bitbucket.org", + "team/app", + ), + ( + "https://dev.azure.com/team/project/_git/app", + "dev.azure.com/team", + "project/app", + ), + ] { + git(&["remote", "set-url", "origin", url]); + assert_eq!( + repository().map(|repository| repository.key(1)), + Some(PullRequestKey::new(host, name, 1)), + "{url}" + ); + } + git(&["remote", "remove", "origin"]); + assert!(repository().is_none()); + std::fs::remove_dir_all(root).unwrap(); + } + /// A host that only rebases refuses a merge-style branch update before any request; a /// rebase passes the gate and reaches the host, here one turned off in settings. #[test] diff --git a/crates/services/src/forge/checkout.rs b/crates/services/src/forge/checkout.rs index f25e024ba..65c3e39ef 100644 --- a/crates/services/src/forge/checkout.rs +++ b/crates/services/src/forge/checkout.rs @@ -2,33 +2,66 @@ //! URLs each kind reads in its own way. use super::Repository; +use std::cell::OnceCell; use std::path::Path; +/// One repository lookup, sharing the fetch remotes across host implementations. +/// A new lookup reads again so remote edits and a later `git init` are visible. +pub struct Checkout<'a> { + cwd: &'a Path, + remotes: OnceCell>, +} + +impl<'a> Checkout<'a> { + pub fn new(cwd: &'a Path) -> Self { + Self { + cwd, + remotes: OnceCell::new(), + } + } + + pub(crate) fn cwd(&self) -> &Path { + self.cwd + } + + pub(crate) fn remotes(&self) -> &[(String, String)] { + self.remotes.get_or_init(|| { + git(self.cwd, &["remote", "-v"]) + .unwrap_or_default() + .lines() + .filter_map(|line| { + let mut parts = line.split_whitespace(); + let name = parts.next()?; + let url = parts.next()?; + (parts.next()? == "(fetch)").then(|| (name.to_owned(), url.to_owned())) + }) + .collect() + }) + } +} + fn git(cwd: &Path, args: &[&str]) -> Option { crate::github::repository::git_read(cwd, args) } /// The fetch remotes of the checkout that `remote` reads as a repository, by remote name. -fn remotes(cwd: &Path, remote: impl Fn(&str) -> Option) -> Vec<(String, Repository)> { - git(cwd, &["remote", "-v"]) - .unwrap_or_default() - .lines() - .filter_map(|line| { - let mut parts = line.split_whitespace(); - let name = parts.next()?; - let url = parts.next()?; - (parts.next()? == "(fetch)").then_some(())?; - Some((name.to_owned(), remote(url)?)) - }) +pub(crate) fn remotes( + checkout: &Checkout<'_>, + remote: impl Fn(&str) -> Option, +) -> Vec<(String, T)> { + checkout + .remotes() + .iter() + .filter_map(|(name, url)| Some((name.clone(), remote(url)?))) .collect() } /// The checkout's repository: `upstream`, then `origin`, then the first remote `remote` reads. pub(crate) fn resolve( - cwd: &Path, + checkout: &Checkout<'_>, remote: impl Fn(&str) -> Option, ) -> Option { - let remotes = remotes(cwd, remote); + let remotes = remotes(checkout, remote); ["upstream", "origin"] .iter() .find_map(|name| remotes.iter().find(|(remote, _)| remote == name)) @@ -44,11 +77,23 @@ pub(crate) struct Branch { pub(crate) source_branch: String, } -pub(crate) fn branch(cwd: &Path, remote: impl Fn(&str) -> Option) -> Option { +/// The branch checked out at `cwd`; `root`'s remote listing serves when that is the root itself. +pub(crate) fn branch( + root: &Checkout<'_>, + cwd: &Path, + remote: impl Fn(&str) -> Option, +) -> Option { + let elsewhere; + let checkout = if cwd == root.cwd() { + root + } else { + elsewhere = Checkout::new(cwd); + &elsewhere + }; let branch = git(cwd, &["symbolic-ref", "--short", "HEAD"])?; let pushed_to = git(cwd, &["config", &format!("branch.{branch}.remote")])?; let merge = git(cwd, &["config", &format!("branch.{branch}.merge")])?; - let source = remotes(cwd, remote) + let source = remotes(checkout, remote) .into_iter() .find(|(name, _)| *name == pushed_to)? .1; diff --git a/crates/services/src/forgejo/mod.rs b/crates/services/src/forgejo/mod.rs index e13c9604b..ffe59f106 100644 --- a/crates/services/src/forgejo/mod.rs +++ b/crates/services/src/forgejo/mod.rs @@ -775,8 +775,8 @@ impl Forge for Forgejo { repository::pull_request_url(&self.known(), url) } - fn checkout_repository(&self, cwd: &Path) -> Option { - repository::resolve(&self.known(), cwd) + fn checkout_repository(&self, checkout: &crate::forge::Checkout<'_>) -> Option { + repository::resolve(&self.known(), checkout) } fn repository(&self, name: &str, host: &str) -> Option { @@ -792,15 +792,15 @@ impl Forge for Forgejo { fn discover( &self, cwd: &Path, - root: &Path, + root: &crate::forge::Checkout<'_>, refresh: bool, ) -> Result, ForgeError> { let known = self.known(); - let cwd = if cwd.exists() { cwd } else { root }; + let cwd = if cwd.exists() { cwd } else { root.cwd() }; let Some(repository) = repository::resolve(&known, root) else { return Ok(None); }; - let Some(branch) = repository::branch(&known, cwd) else { + let Some(branch) = repository::branch(&known, root, cwd) else { return Ok(None); }; let slot = ( diff --git a/crates/services/src/forgejo/repository.rs b/crates/services/src/forgejo/repository.rs index 005a672bf..d3640a75c 100644 --- a/crates/services/src/forgejo/repository.rs +++ b/crates/services/src/forgejo/repository.rs @@ -152,8 +152,11 @@ pub(super) fn remote(known: &[String], value: &str) -> Option { } /// The checkout's repository: `upstream`, then `origin`, then the first remote here. -pub(super) fn resolve(known: &[String], cwd: &Path) -> Option { - crate::forge::checkout::resolve(cwd, |url| remote(known, url)) +pub(super) fn resolve( + known: &[String], + checkout: &crate::forge::Checkout<'_>, +) -> Option { + crate::forge::checkout::resolve(checkout, |url| remote(known, url)) } /// The checked-out branch and where it is pushed: the head owner and branch a pull request @@ -164,8 +167,12 @@ pub(super) struct Branch { pub(super) head_branch: String, } -pub(super) fn branch(known: &[String], cwd: &Path) -> Option { - let found = crate::forge::checkout::branch(cwd, |url| remote(known, url))?; +pub(super) fn branch( + known: &[String], + root: &crate::forge::Checkout<'_>, + cwd: &Path, +) -> Option { + let found = crate::forge::checkout::branch(root, cwd, |url| remote(known, url))?; Some(Branch { head_owner: found.source.locator.split('/').next()?.to_owned(), head_branch: found.source_branch, diff --git a/crates/services/src/git.rs b/crates/services/src/git.rs index be5330328..bb04b73f3 100644 --- a/crates/services/src/git.rs +++ b/crates/services/src/git.rs @@ -473,9 +473,8 @@ pub fn read_status(cwd: &Path) -> GitStatus { } let porcelain = run_git(cwd, &["status", "--porcelain=2", "--branch"]).unwrap_or_default(); let numstat = read_numstat(cwd); - let has_origin_remote = run_git(cwd, &["remote"]) - .map(|out| out.lines().any(|line| line.trim() == "origin")) - .unwrap_or(false); + let checkout = crate::forge::Checkout::new(cwd); + let has_origin_remote = checkout.remotes().iter().any(|(name, _)| name == "origin"); let default_branch = run_git(cwd, &["symbolic-ref", "refs/remotes/origin/HEAD"]) .ok() .map(|value| { @@ -491,7 +490,7 @@ pub fn read_status(cwd: &Path) -> GitStatus { default_branch.as_deref(), has_origin_remote, ); - status.github_repository = crate::github::repository::resolve(cwd) + status.github_repository = crate::github::repository::resolve(&checkout) .map(|repository| format!("{}/{}", repository.owner, repository.name)); status } diff --git a/crates/services/src/github/forge.rs b/crates/services/src/github/forge.rs index bf6aff4c6..eb9282282 100644 --- a/crates/services/src/github/forge.rs +++ b/crates/services/src/github/forge.rs @@ -99,8 +99,8 @@ impl Forge for GitHub { repository::pull_request_url(url) } - fn checkout_repository(&self, cwd: &Path) -> Option { - repository::resolve(cwd).map(neutral) + fn checkout_repository(&self, checkout: &crate::forge::Checkout<'_>) -> Option { + repository::resolve(checkout).map(neutral) } fn repository(&self, name: &str, host: &str) -> Option { @@ -114,10 +114,10 @@ impl Forge for GitHub { fn discover( &self, cwd: &Path, - root: &Path, + root: &crate::forge::Checkout<'_>, refresh: bool, ) -> Result, ForgeError> { - let cwd = if cwd.exists() { cwd } else { root }; + let cwd = if cwd.exists() { cwd } else { root.cwd() }; let (Some(head), Some(project_repository)) = (repository::branch_head(cwd), repository::resolve(root)) else { @@ -134,7 +134,8 @@ impl Forge for GitHub { if result.key.host != project_repository.host || result.key.repository != project_repository.key(result.key.number).repository || repository::branch_head(cwd).as_ref() != Some(&head) - || repository::resolve(root).as_ref() != Some(&project_repository) + || repository::resolve(&crate::forge::Checkout::new(root.cwd())).as_ref() + != Some(&project_repository) { return Err(ForgeError { kind: ForgeErrorKind::Uncertain, diff --git a/crates/services/src/github/repository.rs b/crates/services/src/github/repository.rs index 3d8ce9bd3..ab7a88377 100644 --- a/crates/services/src/github/repository.rs +++ b/crates/services/src/github/repository.rs @@ -115,43 +115,24 @@ pub fn git_read(cwd: &Path, args: &[&str]) -> Option { .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string()) } -fn fetch_remotes(cwd: &Path) -> Vec<(String, String)> { - git_read(cwd, &["remote", "-v"]) - .unwrap_or_default() - .lines() - .filter_map(|line| { - let mut parts = line.split_whitespace(); - let name = parts.next()?; - let url = parts.next()?; - if parts.next()? != "(fetch)" { - return None; - } - Some((name.to_owned(), url.to_owned())) - }) - .collect() -} - -fn remotes(cwd: &Path) -> Vec<(String, Repository)> { - fetch_remotes(cwd) - .into_iter() - .filter_map(|(name, url)| Some((name, remote(&url)?.0))) - .collect() +fn remotes(checkout: &crate::forge::Checkout<'_>) -> Vec<(String, Repository)> { + crate::forge::checkout::remotes(checkout, |url| Some(remote(url)?.0)) } -pub fn resolve(cwd: &Path) -> Option { +pub fn resolve(checkout: &crate::forge::Checkout<'_>) -> Option { let default_host = std::env::var("GH_HOST").unwrap_or_else(|_| "github.com".into()); if let Ok(value) = std::env::var("GH_REPO") && let Some(repository) = selector(&value, &default_host) { return Some(repository); } - let fetch = fetch_remotes(cwd); - let remotes: Vec<_> = fetch - .iter() - .filter_map(|(name, url)| Some((name.clone(), remote(url)?.0))) - .collect(); + let fetch = checkout.remotes(); + let remotes = remotes(checkout); + if remotes.is_empty() { + return None; + } let marks = git_read( - cwd, + checkout.cwd(), &["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"], ) .unwrap_or_default(); @@ -208,7 +189,8 @@ pub struct BranchHead { pub fn branch_head(cwd: &Path) -> Option { let cwd = cwd.canonicalize().ok()?; let branch = git_read(&cwd, &["symbolic-ref", "--short", "HEAD"])?; - let repository = resolve(&cwd)?; + let checkout = crate::forge::Checkout::new(&cwd); + let repository = resolve(&checkout)?; let refs = git_read( &cwd, &[ @@ -221,7 +203,7 @@ pub fn branch_head(cwd: &Path) -> Option { .lines() .find(|line| line.split('\0').next() == Some(format!("refs/heads/{branch}").as_str()))?; let parts: Vec<_> = line.split('\0').collect(); - let remotes = remotes(&cwd); + let remotes = remotes(&checkout); let saved = parts.get(1).copied().unwrap_or_default(); let saved_ref = parts.get(2).copied().unwrap_or_default(); if !saved.is_empty() && saved_ref.is_empty() { diff --git a/crates/services/src/gitlab/mod.rs b/crates/services/src/gitlab/mod.rs index 25ad058de..dd37c0121 100644 --- a/crates/services/src/gitlab/mod.rs +++ b/crates/services/src/gitlab/mod.rs @@ -594,8 +594,8 @@ impl Forge for GitLab { repository::pull_request_url(&self.known(), url) } - fn checkout_repository(&self, cwd: &Path) -> Option { - repository::resolve(&self.known(), cwd) + fn checkout_repository(&self, checkout: &crate::forge::Checkout<'_>) -> Option { + repository::resolve(&self.known(), checkout) } fn repository(&self, name: &str, host: &str) -> Option { @@ -611,15 +611,15 @@ impl Forge for GitLab { fn discover( &self, cwd: &Path, - root: &Path, + root: &crate::forge::Checkout<'_>, refresh: bool, ) -> Result, ForgeError> { let known = self.known(); - let cwd = if cwd.exists() { cwd } else { root }; + let cwd = if cwd.exists() { cwd } else { root.cwd() }; let Some(target) = repository::resolve(&known, root) else { return Ok(None); }; - let Some(branch) = repository::branch(&known, cwd) else { + let Some(branch) = repository::branch(&known, root, cwd) else { return Ok(None); }; let slot = ( diff --git a/crates/services/src/gitlab/repository.rs b/crates/services/src/gitlab/repository.rs index 6d37cc422..26bae2ebe 100644 --- a/crates/services/src/gitlab/repository.rs +++ b/crates/services/src/gitlab/repository.rs @@ -137,14 +137,21 @@ pub(super) fn remote(known: &[String], value: &str) -> Option { } /// The checkout's project: `upstream`, then `origin`, then the first remote here. -pub(super) fn resolve(known: &[String], cwd: &Path) -> Option { - crate::forge::checkout::resolve(cwd, |url| remote(known, url)) +pub(super) fn resolve( + known: &[String], + checkout: &crate::forge::Checkout<'_>, +) -> Option { + crate::forge::checkout::resolve(checkout, |url| remote(known, url)) } /// The checked-out branch and the project and branch a merge request from it names as its /// source. -pub(super) fn branch(known: &[String], cwd: &Path) -> Option { - crate::forge::checkout::branch(cwd, |url| remote(known, url)) +pub(super) fn branch( + known: &[String], + root: &crate::forge::Checkout<'_>, + cwd: &Path, +) -> Option { + crate::forge::checkout::branch(root, cwd, |url| remote(known, url)) } #[cfg(test)] diff --git a/crates/services/src/process.rs b/crates/services/src/process.rs index 582d3e794..c591d9e23 100644 --- a/crates/services/src/process.rs +++ b/crates/services/src/process.rs @@ -1,7 +1,7 @@ //! Child-process helpers. //! //! Every process tcode spawns (git, the provider CLIs, npm, editors, …) must go -//! through these constructors, for two Windows reasons: +//! through these constructors, for three Windows reasons: //! //! 1. A plain `Command` pops a console window for the child, which is jarring in //! a GUI app. `CREATE_NO_WINDOW` suppresses it. @@ -9,8 +9,11 @@ //! `npm` / `pnpm` / `bun` (and `claude`) **`.cmd` shims** are invisible to it. //! [`resolve_program`] does a `PATHEXT`-aware PATH search first (shared with //! the agent crate's provider-binary resolution). +//! 3. A child inherits every inheritable handle of tcode's, tcode's own stdout +//! and stderr included, so a child that outlives tcode keeps whoever reads +//! tcode's output waiting. [`agent::keep_own_stdio_from_children`] stops it. //! -//! On other platforms both are no-ops / passthroughs — `exec` resolves PATH. +//! On other platforms all three are no-ops / passthroughs — `exec` resolves PATH. /// `CREATE_NO_WINDOW`: run the child without allocating a console. #[cfg(windows)] @@ -44,6 +47,7 @@ pub fn resolve_program>(program: S) -> std::ffi::OsStr /// A `std::process::Command` that never flashes a console window, with its /// program resolved through [`resolve_program`]. pub fn command>(program: S) -> std::process::Command { + agent::keep_own_stdio_from_children(); // Approved constructor: this is the helper every other site must use. #[allow(clippy::disallowed_methods)] let mut cmd = std::process::Command::new(resolve_program(program)); diff --git a/crates/services/tests/github.rs b/crates/services/tests/github.rs index 3a1616671..f06d48f8d 100644 --- a/crates/services/tests/github.rs +++ b/crates/services/tests/github.rs @@ -1230,11 +1230,18 @@ fn real_git_fork_heads_follow_gh_default_without_mistaking_the_base_for_a_publis git(&["config", "branch.topic.merge", "refs/heads/main"]); let subdirectory = cwd.join("nested"); std::fs::create_dir(&subdirectory).unwrap(); - assert_eq!(repository::resolve(&subdirectory).unwrap().owner, "sample"); + assert_eq!( + repository::resolve(&tcode_services::forge::Checkout::new(&subdirectory)) + .unwrap() + .owner, + "sample" + ); git(&["config", "--unset", "remote.upstream.gh-resolved"]); git(&["config", "remote.origin.gh-resolved", "base"]); assert_eq!( - repository::resolve(&subdirectory).unwrap().owner, + repository::resolve(&tcode_services::forge::Checkout::new(&subdirectory)) + .unwrap() + .owner, "sample", "mixed hosts and SSH aliases reject the strict gh mark and use the host-ranked remote" ); diff --git a/crates/ui/src/highlight.rs b/crates/ui/src/highlight.rs index 99b8f4b82..5fea903be 100644 --- a/crates/ui/src/highlight.rs +++ b/crates/ui/src/highlight.rs @@ -543,9 +543,10 @@ mod tests { assert!(SYNTAX_SET.find_syntax_by_name("Plain Text").is_some()); } - /// Mirror of syntect's private `substitute_backrefs_in_regex` with the - /// placeholder substituter its YAML loader validates patterns with; kept - /// in sync with `examples/sanitize_syntaxes.rs`. + /// syntect keeps `substitute_backrefs_in_regex` private, so the probe + /// substitutes back-references with the placeholder its YAML loader + /// validates patterns with, as `examples/sanitize_syntaxes.rs` does when it + /// regenerates the dump. fn substitute_backrefs(regex_str: &str) -> String { let mut result = String::with_capacity(regex_str.len()); let mut last_was_escape = false; @@ -581,8 +582,11 @@ mod tests { syntect::dumps::from_uncompressed_data(include_bytes!("../assets/syntaxes.bin")) .expect("load shipped dump"); let mut failures = Vec::new(); + // Compilation depends only on the pattern, which many syntaxes share. + let mut checked = HashSet::new(); for syntax in set.into_builder().syntaxes() { if let Some(first_line) = &syntax.first_line_match + && checked.insert(first_line.clone()) && let Some(err) = Regex::try_compile(first_line) { failures.push(format!("{}: first_line_match: {err}", syntax.name)); @@ -597,7 +601,9 @@ mod tests { } else { pattern.regex.regex_str().to_string() }; - if let Some(err) = Regex::try_compile(&probe) { + if checked.insert(probe.clone()) + && let Some(err) = Regex::try_compile(&probe) + { failures.push(format!("{}: {err}", syntax.name)); } }