Skip to main content

lean_ctx/lsp/format/
mod.rs

1//! Formatter routing for `ctx_refactor action=reformat`: pick a formatter by
2//! file extension, using built-in routing per extension.
3
4/// The formatter selected for a file: either the IDE HTTP backend or an external
5/// shell command (template with a `{file}` placeholder).
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum Formatter {
8    Jetbrains,
9    Command(String),
10}
11
12/// Pick the formatter for `abs_path` using built-in defaults per extension.
13/// Extension match is case-insensitive; no extension or an unknown extension → `Jetbrains`.
14pub fn resolve_formatter(abs_path: &str) -> Formatter {
15    let ext = std::path::Path::new(abs_path)
16        .extension()
17        .and_then(|e| e.to_str())
18        .map(str::to_ascii_lowercase)
19        .unwrap_or_default();
20    builtin_default(&ext)
21}
22
23/// Built-in routing when the config has no entry for this extension.
24fn builtin_default(ext: &str) -> Formatter {
25    match ext {
26        "rs" => Formatter::Command("rustfmt {file}".to_string()),
27        _ => Formatter::Jetbrains,
28    }
29}
30
31/// The binary name of a command template, for the `via <name>` output label.
32pub fn command_label(template: &str) -> &str {
33    template.split_whitespace().next().unwrap_or("formatter")
34}
35
36/// Split a command template into argv, substituting the `{file}` placeholder with
37/// `abs_path`. `{file}` may be a standalone token or embedded in a token. If no
38/// placeholder is present, `abs_path` is appended as the final argument. The path
39/// is always a single argv element (spaces in the path are preserved).
40pub fn build_argv(template: &str, abs_path: &str) -> Vec<String> {
41    let mut argv: Vec<String> = Vec::new();
42    let mut saw_placeholder = false;
43    for tok in template.split_whitespace() {
44        if tok == "{file}" {
45            argv.push(abs_path.to_string());
46            saw_placeholder = true;
47        } else if tok.contains("{file}") {
48            argv.push(tok.replace("{file}", abs_path));
49            saw_placeholder = true;
50        } else {
51            argv.push(tok.to_string());
52        }
53    }
54    if !saw_placeholder {
55        argv.push(abs_path.to_string());
56    }
57    argv
58}
59
60/// Run an external formatter command on `abs_path` with cwd `project_root` (so
61/// tool config like `rustfmt.toml` is discovered). Returns `Err` with a clear
62/// message if the binary is missing or the command exits non-zero.
63///
64/// Formatter commands are trusted local executables. LeanCTX terminates the
65/// formatter and ordinary descendants through a Unix process group or Windows
66/// Job Object; a deliberately detached Unix process (`setsid`) is outside this
67/// cooperative cleanup boundary.
68pub fn run_command_formatter(
69    template: &str,
70    abs_path: &str,
71    project_root: &str,
72) -> Result<(), String> {
73    run_command_formatter_with_timeout(
74        template,
75        abs_path,
76        project_root,
77        std::time::Duration::from_secs(30),
78    )
79}
80
81fn run_command_formatter_with_timeout(
82    template: &str,
83    abs_path: &str,
84    project_root: &str,
85    timeout: std::time::Duration,
86) -> Result<(), String> {
87    let formatter = spawn_command_formatter(template, abs_path, project_root)?;
88    wait_for_command_formatter(formatter, timeout)
89}
90
91struct CapturedFormatter {
92    child: std::process::Child,
93    stdout: std::fs::File,
94    stderr: std::fs::File,
95    bin: String,
96    cleanup: FormatterCleanup,
97}
98
99#[derive(Default)]
100struct FormatterCleanup {
101    #[cfg(windows)]
102    job: Option<FormatterJob>,
103}
104
105#[cfg(windows)]
106struct FormatterJob(windows_sys::Win32::Foundation::HANDLE);
107
108#[cfg(windows)]
109impl Drop for FormatterJob {
110    fn drop(&mut self) {
111        // SAFETY: this instance exclusively owns the CreateJobObjectW handle.
112        unsafe {
113            windows_sys::Win32::Foundation::CloseHandle(self.0);
114        }
115    }
116}
117
118fn spawn_command_formatter(
119    template: &str,
120    abs_path: &str,
121    project_root: &str,
122) -> Result<CapturedFormatter, String> {
123    use std::process::{Command, Stdio};
124
125    let argv = build_argv(template, abs_path);
126    let (bin, rest) = argv
127        .split_first()
128        .ok_or_else(|| "INVALID_TARGET: empty formatter template".to_string())?;
129    let stdout = tempfile::tempfile()
130        .map_err(|error| format!("failed to create formatter '{bin}' stdout capture: {error}"))?;
131    let stderr = tempfile::tempfile()
132        .map_err(|error| format!("failed to create formatter '{bin}' stderr capture: {error}"))?;
133    let mut command = Command::new(bin);
134    command
135        .args(rest)
136        .current_dir(project_root)
137        .stdin(Stdio::null())
138        .stdout(Stdio::from(stdout.try_clone().map_err(|error| {
139            format!("failed to clone formatter '{bin}' stdout capture: {error}")
140        })?))
141        .stderr(Stdio::from(stderr.try_clone().map_err(|error| {
142            format!("failed to clone formatter '{bin}' stderr capture: {error}")
143        })?));
144    #[cfg(unix)]
145    {
146        use std::os::unix::process::CommandExt;
147        command.process_group(0);
148    }
149    #[cfg(windows)]
150    {
151        use std::os::windows::process::CommandExt;
152        command.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED);
153    }
154    let mut child = command.spawn().map_err(|e| {
155        if e.kind() == std::io::ErrorKind::NotFound {
156            format!("formatter '{bin}' not found in PATH")
157        } else {
158            format!("failed to run '{bin}': {e}")
159        }
160    })?;
161
162    let cleanup = match formatter_cleanup(&child, bin) {
163        Ok(cleanup) => cleanup,
164        Err(error) => {
165            let _ = child.kill();
166            let _ = child.wait();
167            return Err(error);
168        }
169    };
170
171    Ok(CapturedFormatter {
172        child,
173        stdout,
174        stderr,
175        bin: bin.clone(),
176        cleanup,
177    })
178}
179
180#[cfg(windows)]
181fn formatter_cleanup(child: &std::process::Child, bin: &str) -> Result<FormatterCleanup, String> {
182    use std::os::windows::io::AsRawHandle;
183    use windows_sys::Win32::System::JobObjects::{
184        AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
185        JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
186        SetInformationJobObject,
187    };
188
189    // SAFETY: null attributes/name create a private job owned by FormatterJob.
190    let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
191    if handle.is_null() {
192        return Err(format!(
193            "failed to create formatter job for '{bin}': {}",
194            std::io::Error::last_os_error()
195        ));
196    }
197    let job = FormatterJob(handle);
198    let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
199    limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
200    // SAFETY: limits has the exact structure and size required by this info class.
201    let configured = unsafe {
202        SetInformationJobObject(
203            job.0,
204            JobObjectExtendedLimitInformation,
205            std::ptr::from_ref(&limits).cast(),
206            std::mem::size_of_val(&limits) as u32,
207        )
208    };
209    if configured == 0 {
210        return Err(format!(
211            "failed to configure formatter job for '{bin}': {}",
212            std::io::Error::last_os_error()
213        ));
214    }
215    // SAFETY: Child owns a live process handle for the formatter process.
216    let assigned = unsafe { AssignProcessToJobObject(job.0, child.as_raw_handle() as _) };
217    if assigned == 0 {
218        return Err(format!(
219            "failed to assign formatter '{bin}' to its job: {}",
220            std::io::Error::last_os_error()
221        ));
222    }
223    resume_formatter_threads(child.id(), bin)?;
224    Ok(FormatterCleanup { job: Some(job) })
225}
226
227#[cfg(windows)]
228fn resume_formatter_threads(process_id: u32, bin: &str) -> Result<(), String> {
229    use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
230    use windows_sys::Win32::System::Diagnostics::ToolHelp::{
231        CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
232    };
233    use windows_sys::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
234
235    // SAFETY: snapshot handle is closed on every return path below.
236    let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
237    if snapshot == INVALID_HANDLE_VALUE {
238        return Err(format!(
239            "failed to inspect suspended formatter '{bin}' threads: {}",
240            std::io::Error::last_os_error()
241        ));
242    }
243    let mut entry = THREADENTRY32 {
244        dwSize: std::mem::size_of::<THREADENTRY32>() as u32,
245        ..THREADENTRY32::default()
246    };
247    // SAFETY: snapshot and entry are valid for ToolHelp thread enumeration.
248    let mut has_entry = unsafe { Thread32First(snapshot, &mut entry) } != 0;
249    let mut resumed = false;
250    let result = loop {
251        if !has_entry {
252            break if resumed {
253                Ok(())
254            } else {
255                Err(format!(
256                    "suspended formatter '{bin}' exposed no resumable thread"
257                ))
258            };
259        }
260        if entry.th32OwnerProcessID == process_id {
261            // SAFETY: entry names a thread owned by the suspended child process.
262            let thread = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
263            if thread.is_null() {
264                break Err(format!(
265                    "failed to open suspended formatter '{bin}' thread: {}",
266                    std::io::Error::last_os_error()
267                ));
268            }
269            // SAFETY: thread is a live handle with THREAD_SUSPEND_RESUME access.
270            let resume_result = unsafe { ResumeThread(thread) };
271            // SAFETY: this scope owns the OpenThread handle.
272            unsafe { CloseHandle(thread) };
273            if resume_result == u32::MAX {
274                break Err(format!(
275                    "failed to resume formatter '{bin}' thread: {}",
276                    std::io::Error::last_os_error()
277                ));
278            }
279            resumed = true;
280        }
281        // SAFETY: snapshot and entry remain valid until CloseHandle below.
282        has_entry = unsafe { Thread32Next(snapshot, &mut entry) } != 0;
283    };
284    // SAFETY: this scope owns the ToolHelp snapshot handle.
285    unsafe { CloseHandle(snapshot) };
286    result
287}
288
289#[cfg(not(windows))]
290fn formatter_cleanup(_: &std::process::Child, _: &str) -> Result<FormatterCleanup, String> {
291    Ok(FormatterCleanup::default())
292}
293
294fn wait_for_command_formatter(
295    CapturedFormatter {
296        mut child,
297        mut stdout,
298        mut stderr,
299        bin,
300        mut cleanup,
301    }: CapturedFormatter,
302    timeout: std::time::Duration,
303) -> Result<(), String> {
304    const CLEANUP_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
305
306    let deadline = std::time::Instant::now() + timeout;
307    let (status, timed_out, cleanup_error) = loop {
308        match child.try_wait() {
309            Err(wait_error) => {
310                let cleanup_error = terminate_timed_out_formatter(&mut child, &bin, &mut cleanup)
311                    .err()
312                    .map(|error| format!("cleanup failed: {error}"));
313                let reap_error = reap_formatter(&mut child, &bin, CLEANUP_GRACE)
314                    .err()
315                    .map(|error| format!("reap failed: {error}"));
316                let details = [cleanup_error, reap_error]
317                    .into_iter()
318                    .flatten()
319                    .collect::<Vec<_>>()
320                    .join("; ");
321                return Err(if details.is_empty() {
322                    format!("failed to wait for '{bin}': {wait_error}")
323                } else {
324                    format!("failed to wait for '{bin}': {wait_error}; {details}")
325                });
326            }
327            Ok(Some(status)) => {
328                break (
329                    status,
330                    false,
331                    stop_remaining_formatter_group(&child, &bin, &mut cleanup).err(),
332                );
333            }
334            Ok(None) if std::time::Instant::now() >= deadline => {
335                let cleanup_error =
336                    terminate_timed_out_formatter(&mut child, &bin, &mut cleanup).err();
337                break (
338                    reap_formatter(&mut child, &bin, CLEANUP_GRACE)?,
339                    true,
340                    cleanup_error,
341                );
342            }
343            Ok(None) => std::thread::sleep(std::time::Duration::from_millis(10)),
344        }
345    };
346    let _stdout = read_capture(&mut stdout, &bin, "stdout")?;
347    let stderr = read_capture(&mut stderr, &bin, "stderr")?;
348
349    if let Some(error) = cleanup_error {
350        return Err(error);
351    }
352
353    if timed_out {
354        return Err(format!(
355            "formatter '{bin}' timed out after {}s",
356            timeout.as_secs()
357        ));
358    }
359    if !status.success() {
360        let code = status
361            .code()
362            .map_or_else(|| "signal".to_string(), |c| c.to_string());
363        let stderr = String::from_utf8_lossy(&stderr);
364        return Err(format!("{bin} exited {code}: {}", stderr.trim()));
365    }
366    Ok(())
367}
368
369fn read_capture(capture: &mut std::fs::File, bin: &str, stream: &str) -> Result<Vec<u8>, String> {
370    use std::io::{Read, Seek};
371
372    capture
373        .rewind()
374        .map_err(|error| format!("failed to rewind formatter '{bin}' {stream}: {error}"))?;
375    let mut bytes = Vec::new();
376    capture
377        .read_to_end(&mut bytes)
378        .map_err(|error| format!("failed to read formatter '{bin}' {stream}: {error}"))?;
379    Ok(bytes)
380}
381
382fn reap_formatter(
383    child: &mut std::process::Child,
384    bin: &str,
385    timeout: std::time::Duration,
386) -> Result<std::process::ExitStatus, String> {
387    let deadline = std::time::Instant::now() + timeout;
388    loop {
389        match child
390            .try_wait()
391            .map_err(|error| format!("failed to reap formatter '{bin}': {error}"))?
392        {
393            Some(status) => return Ok(status),
394            None if std::time::Instant::now() >= deadline => {
395                return Err(format!("formatter '{bin}' did not exit after termination"));
396            }
397            None => std::thread::sleep(std::time::Duration::from_millis(10)),
398        }
399    }
400}
401
402#[cfg(unix)]
403fn stop_remaining_formatter_group(
404    child: &std::process::Child,
405    bin: &str,
406    _: &mut FormatterCleanup,
407) -> Result<(), String> {
408    let pgid = child.id() as libc::pid_t;
409    if pgid <= 0 {
410        return Err(format!(
411            "failed to stop formatter process group '{bin}': invalid process group id {pgid}"
412        ));
413    }
414    // SAFETY: the formatter was spawned as leader of its dedicated process group.
415    if unsafe { libc::killpg(pgid, libc::SIGKILL) } == 0 {
416        return Ok(());
417    }
418    let error = std::io::Error::last_os_error();
419    if error.raw_os_error() == Some(libc::ESRCH) {
420        Ok(())
421    } else {
422        Err(format!(
423            "failed to stop formatter process group '{bin}': {error}"
424        ))
425    }
426}
427
428#[cfg(windows)]
429fn stop_remaining_formatter_group(
430    _: &std::process::Child,
431    _: &str,
432    cleanup: &mut FormatterCleanup,
433) -> Result<(), String> {
434    drop(cleanup.job.take());
435    Ok(())
436}
437
438fn terminate_timed_out_formatter(
439    child: &mut std::process::Child,
440    bin: &str,
441    cleanup: &mut FormatterCleanup,
442) -> Result<(), String> {
443    #[cfg(unix)]
444    {
445        match stop_remaining_formatter_group(child, bin, cleanup) {
446            Ok(()) => return Ok(()),
447            Err(group_error) => {
448                child.kill().map_err(|error| {
449                    format!("{group_error}; failed to stop direct formatter child '{bin}': {error}")
450                })?;
451                return Err(group_error);
452            }
453        }
454    }
455    #[cfg(windows)]
456    {
457        stop_remaining_formatter_group(child, bin, cleanup)?;
458        return Ok(());
459    }
460
461    #[allow(unreachable_code)]
462    child
463        .kill()
464        .map_err(|e| format!("failed to stop timed-out formatter '{bin}': {e}"))
465}
466
467/// Hex BLAKE3 of the file content, for honest before/after change detection.
468pub fn blake3_of(abs_path: &str) -> Result<String, String> {
469    let bytes = std::fs::read(abs_path).map_err(|e| format!("FILE_NOT_FOUND: {abs_path}: {e}"))?;
470    Ok(crate::core::hasher::hash_hex(&bytes))
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476
477    fn wait_for_path(path: &std::path::Path, timeout: std::time::Duration) -> bool {
478        let deadline = std::time::Instant::now() + timeout;
479        while !path.exists() && std::time::Instant::now() < deadline {
480            std::thread::sleep(std::time::Duration::from_millis(5));
481        }
482        path.exists()
483    }
484
485    fn assert_descendant_stopped(release: &std::path::Path, survived: &std::path::Path) {
486        std::fs::write(release, "release").unwrap();
487        assert!(
488            !wait_for_path(survived, std::time::Duration::from_secs(2)),
489            "formatter descendant performed work after cleanup"
490        );
491    }
492
493    #[test]
494    fn rs_defaults_to_rustfmt() {
495        let f = resolve_formatter("/x/a.rs");
496        assert!(matches!(f, Formatter::Command(ref t) if t == "rustfmt {file}"));
497    }
498
499    #[test]
500    fn md_and_unknown_and_no_ext_default_to_jetbrains() {
501        assert!(matches!(resolve_formatter("/x/a.md"), Formatter::Jetbrains));
502        assert!(matches!(
503            resolve_formatter("/x/a.txt"),
504            Formatter::Jetbrains
505        ));
506        assert!(matches!(
507            resolve_formatter("/x/README"),
508            Formatter::Jetbrains
509        ));
510    }
511
512    #[test]
513    fn extension_is_case_insensitive() {
514        assert!(matches!(
515            resolve_formatter("/x/A.RS"),
516            Formatter::Command(_)
517        ));
518    }
519
520    #[test]
521    fn command_label_is_first_token() {
522        assert_eq!(command_label("rustfmt {file}"), "rustfmt");
523        assert_eq!(command_label("ruff format {file}"), "ruff");
524        assert_eq!(command_label(""), "formatter");
525    }
526
527    #[test]
528    fn argv_substitutes_placeholder() {
529        assert_eq!(
530            build_argv("rustfmt {file}", "/x/a.rs"),
531            vec!["rustfmt".to_string(), "/x/a.rs".to_string()]
532        );
533        assert_eq!(
534            build_argv("ruff format {file}", "/x/a.py"),
535            vec![
536                "ruff".to_string(),
537                "format".to_string(),
538                "/x/a.py".to_string()
539            ]
540        );
541    }
542
543    #[test]
544    fn argv_appends_path_when_no_placeholder() {
545        assert_eq!(
546            build_argv("gofmt -w", "/x/a.go"),
547            vec!["gofmt".to_string(), "-w".to_string(), "/x/a.go".to_string()]
548        );
549    }
550
551    #[test]
552    fn argv_path_with_spaces_stays_one_arg() {
553        let argv = build_argv("rustfmt {file}", "/x/my dir/a.rs");
554        assert_eq!(
555            argv,
556            vec!["rustfmt".to_string(), "/x/my dir/a.rs".to_string()]
557        );
558    }
559
560    #[test]
561    fn blake3_detects_change() {
562        let dir = tempfile::tempdir().unwrap();
563        let f = dir.path().join("a.txt");
564        std::fs::write(&f, "one").unwrap();
565        let p = f.to_str().unwrap();
566        let h1 = blake3_of(p).unwrap();
567        let h2 = blake3_of(p).unwrap();
568        assert_eq!(h1, h2, "same content → same hash");
569        std::fs::write(&f, "two").unwrap();
570        assert_ne!(
571            h1,
572            blake3_of(p).unwrap(),
573            "changed content → different hash"
574        );
575    }
576
577    #[test]
578    fn blake3_missing_file_errors() {
579        assert!(blake3_of("/no/such/file.xyz").is_err());
580    }
581
582    #[test]
583    fn run_command_missing_binary_errors() {
584        let dir = tempfile::tempdir().unwrap();
585        let f = dir.path().join("a.rs");
586        std::fs::write(&f, "fn x(){}\n").unwrap();
587        let err = run_command_formatter(
588            "definitely-not-a-formatter-binary {file}",
589            f.to_str().unwrap(),
590            dir.path().to_str().unwrap(),
591        )
592        .unwrap_err();
593        assert!(err.contains("not found"), "got: {err}");
594    }
595
596    #[test]
597    fn run_command_nonzero_exit_errors() {
598        let dir = tempfile::tempdir().unwrap();
599        #[cfg(unix)]
600        let (template, formatter) = {
601            let formatter = dir.path().join("fail-formatter");
602            std::fs::write(&formatter, "#!/bin/sh\nexit 7\n").unwrap();
603            ("sh {file}", formatter)
604        };
605        #[cfg(windows)]
606        let (template, formatter) = {
607            let formatter = dir.path().join("fail-formatter.cmd");
608            std::fs::write(&formatter, "@echo off\r\nexit /B 7\r\n").unwrap();
609            ("cmd.exe /D /S /C {file}", formatter)
610        };
611        let err = run_command_formatter(
612            template,
613            formatter.to_str().unwrap(),
614            dir.path().to_str().unwrap(),
615        )
616        .unwrap_err();
617        assert!(err.contains("exited"), "got: {err}");
618    }
619
620    #[cfg(windows)]
621    #[test]
622    fn command_formatter_timeout_closes_descendant_pipes() {
623        use std::time::Duration;
624
625        let dir = tempfile::tempdir().unwrap();
626        let formatter = dir.path().join("stall-formatter.ps1");
627        let descendant = dir.path().join("descendant.ps1");
628        let ready = dir.path().join("descendant.ready");
629        let release = dir.path().join("descendant.release");
630        let survived = dir.path().join("descendant.survived");
631        let ps_quote = |path: &std::path::Path| path.display().to_string().replace('\'', "''");
632        std::fs::write(
633            &descendant,
634            format!(
635                "$ErrorActionPreference = 'Stop'\r\nSet-Content -LiteralPath '{}' -Value ready\r\nwhile (-not (Test-Path -LiteralPath '{}')) {{ Start-Sleep -Milliseconds 10 }}\r\nSet-Content -LiteralPath '{}' -Value survived\r\n",
636                ps_quote(&ready),
637                ps_quote(&release),
638                ps_quote(&survived)
639            ),
640        )
641        .unwrap();
642        std::fs::write(
643            &formatter,
644            format!(
645                "$ErrorActionPreference = 'Stop'\r\nStart-Process powershell.exe -NoNewWindow -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-File','{}')\r\nwhile ($true) {{ Start-Sleep -Seconds 1 }}\r\n",
646                ps_quote(&descendant)
647            ),
648        )
649        .unwrap();
650        let process = spawn_command_formatter(
651            "powershell.exe -NoProfile -ExecutionPolicy Bypass -File {file}",
652            formatter.to_str().unwrap(),
653            dir.path().to_str().unwrap(),
654        )
655        .expect("formatter process must spawn");
656        assert!(
657            wait_for_path(&ready, Duration::from_secs(5)),
658            "formatter descendant must start"
659        );
660        let error = wait_for_command_formatter(process, Duration::from_millis(250))
661            .expect_err("stalled formatter tree must fail closed");
662
663        assert!(error.contains("timed out"), "got: {error}");
664        assert_descendant_stopped(&release, &survived);
665    }
666
667    #[cfg(unix)]
668    #[test]
669    fn command_formatter_times_out_and_reaps_a_stalled_child() {
670        use std::os::unix::fs::PermissionsExt;
671        use std::time::Duration;
672
673        let dir = tempfile::tempdir().unwrap();
674        let formatter = dir.path().join("stall-formatter");
675        std::fs::write(
676            &formatter,
677            "#!/bin/sh\n(printf ready > \"${0}.ready\"; while [ ! -e \"${0}.release\" ]; do sleep 0.01; done; printf survived > \"${0}.survived\") &\nwait\n",
678        )
679        .unwrap();
680        let mut permissions = std::fs::metadata(&formatter).unwrap().permissions();
681        permissions.set_mode(0o755);
682        std::fs::set_permissions(&formatter, permissions).unwrap();
683        let source = dir.path().join("a.rs");
684        std::fs::write(&source, "fn x() {}\n").unwrap();
685        let ready = formatter.with_file_name("stall-formatter.ready");
686        let release = formatter.with_file_name("stall-formatter.release");
687        let survived = formatter.with_file_name("stall-formatter.survived");
688        let template = format!("{} {{file}}", formatter.display());
689        let source_path = source.to_str().unwrap().to_owned();
690        let project_root = dir.path().to_str().unwrap().to_owned();
691        let process = spawn_command_formatter(&template, &source_path, &project_root)
692            .expect("formatter process must spawn");
693
694        assert!(
695            wait_for_path(&ready, Duration::from_secs(2)),
696            "formatter descendant must start"
697        );
698        let error = wait_for_command_formatter(process, Duration::from_millis(250))
699            .expect_err("stalled formatter must fail closed");
700
701        assert!(error.contains("timed out"), "unexpected error: {error}");
702        assert_descendant_stopped(&release, &survived);
703    }
704
705    #[cfg(unix)]
706    #[test]
707    fn command_formatter_cleans_descendant_after_parent_exits() {
708        use std::os::unix::fs::PermissionsExt;
709        use std::time::Duration;
710
711        let dir = tempfile::tempdir().unwrap();
712        let formatter = dir.path().join("background-formatter");
713        std::fs::write(
714            &formatter,
715            "#!/bin/sh\n(printf ready > \"${0}.ready\"; while [ ! -e \"${0}.release\" ]; do sleep 0.01; done; printf survived > \"${0}.survived\") &\nexit 0\n",
716        )
717        .unwrap();
718        let mut permissions = std::fs::metadata(&formatter).unwrap().permissions();
719        permissions.set_mode(0o755);
720        std::fs::set_permissions(&formatter, permissions).unwrap();
721        let source = dir.path().join("a.rs");
722        std::fs::write(&source, "fn x() {}\n").unwrap();
723
724        let process = spawn_command_formatter(
725            &format!("{} {{file}}", formatter.display()),
726            source.to_str().unwrap(),
727            dir.path().to_str().unwrap(),
728        )
729        .expect("formatter process must spawn");
730        let ready = formatter.with_file_name("background-formatter.ready");
731        let release = formatter.with_file_name("background-formatter.release");
732        let survived = formatter.with_file_name("background-formatter.survived");
733        assert!(
734            wait_for_path(&ready, Duration::from_secs(2)),
735            "formatter descendant must start"
736        );
737
738        wait_for_command_formatter(process, Duration::from_secs(1))
739            .expect("successful formatter must clean up its background process");
740        assert_descendant_stopped(&release, &survived);
741    }
742
743    #[test]
744    fn run_rustfmt_formats_and_reports_change() {
745        // Gated: only runs when rustfmt is installed.
746        if std::process::Command::new("rustfmt")
747            .arg("--version")
748            .output()
749            .is_err()
750        {
751            eprintln!("SKIP: rustfmt not in PATH");
752            return;
753        }
754        let dir = tempfile::tempdir().unwrap();
755        let f = dir.path().join("a.rs");
756        std::fs::write(&f, "fn   x( ){let y=1;}\n").unwrap(); // deliberate drift
757        let p = f.to_str().unwrap();
758        let before = blake3_of(p).unwrap();
759        run_command_formatter("rustfmt {file}", p, dir.path().to_str().unwrap()).unwrap();
760        let after = blake3_of(p).unwrap();
761        assert_ne!(
762            before, after,
763            "rustfmt should have changed the drifted file"
764        );
765
766        // A second run is a no-op (already conformant).
767        let before2 = blake3_of(p).unwrap();
768        run_command_formatter("rustfmt {file}", p, dir.path().to_str().unwrap()).unwrap();
769        assert_eq!(
770            before2,
771            blake3_of(p).unwrap(),
772            "second run should be unchanged"
773        );
774    }
775}