capulus 0.6.11

Shared support for Rust command-line tools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use std::ffi::OsStr;
use std::io::{self, IsTerminal, Write};
use std::process::{Command, ExitStatus, Output, Stdio};

use anyhow::{Context, Result, bail};
use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::shell::shell_quote;

#[derive(Debug)]
pub struct CommandOutput {
    pub status: ExitStatus,
    pub stdout: String,
    pub stderr: String,
}

#[derive(Clone, Debug)]
pub struct CaptureOptions {
    pub timeout: std::time::Duration,
    pub max_output_bytes: u64,
    pub cancellation: crate::Cancellation,
}

impl Default for CaptureOptions {
    fn default() -> Self {
        Self {
            timeout: std::time::Duration::from_secs(60),
            max_output_bytes: 16 * 1024 * 1024,
            cancellation: crate::Cancellation::passive(),
        }
    }
}

pub struct CaptureConfig(CaptureOptions);

impl CaptureOptions {
    pub fn validate(self) -> Result<CaptureConfig> {
        anyhow::ensure!(!self.timeout.is_zero(), "command timeout must be positive");
        anyhow::ensure!(
            self.max_output_bytes > 0,
            "command output limit must be positive"
        );
        Ok(CaptureConfig(self))
    }
}

impl CaptureConfig {
    /// Capture a child and its descendants with bounded output and a deadline.
    pub fn run(&self, command: &mut Command, input: Option<&[u8]>) -> Result<CommandOutput> {
        self.execute(command, input, false)
    }

    /// Mirror both child output streams to stderr while retaining bounded diagnostics.
    /// The caller must suspend any interactive renderer before calling this method.
    pub fn run_streaming(
        &self,
        command: &mut Command,
        input: Option<&[u8]>,
    ) -> Result<CommandOutput> {
        self.execute(command, input, true)
    }

    fn execute(
        &self,
        command: &mut Command,
        input: Option<&[u8]>,
        streaming: bool,
    ) -> Result<CommandOutput> {
        use std::io::{Read, Seek};
        use std::os::unix::process::CommandExt;
        use std::time::{Duration, Instant};

        self.0.cancellation.check()?;
        let mut stdin = tempfile::tempfile()?;
        stdin.write_all(input.unwrap_or_default())?;
        stdin.rewind()?;
        let mut stdout = tempfile::tempfile()?;
        let mut stderr = tempfile::tempfile()?;
        command
            .process_group(0)
            .stdin(stdin)
            .stdout(stdout.try_clone()?)
            .stderr(stderr.try_clone()?);
        let mut child = CapturedChild(command.spawn().context("failed to start subprocess")?);
        let started = Instant::now();
        let mut positions = [0, 0];
        let status = loop {
            if streaming {
                mirror_output([&stdout, &stderr], &mut positions)?;
            }
            self.0.cancellation.check()?;
            anyhow::ensure!(
                started.elapsed() < self.0.timeout,
                "subprocess deadline exceeded after {:?}",
                self.0.timeout
            );
            anyhow::ensure!(
                stdout.metadata()?.len() <= self.0.max_output_bytes
                    && stderr.metadata()?.len() <= self.0.max_output_bytes,
                "subprocess output limit exceeded"
            );
            if let Some(status) = child.0.try_wait()? {
                break status;
            }
            self.0.cancellation.sleep(Duration::from_millis(50))?;
        };
        // Descendants must not outlive the captured command or continue writing its output.
        drop(child);
        if streaming {
            while positions[0] < stdout.metadata()?.len() || positions[1] < stderr.metadata()?.len()
            {
                self.0.cancellation.check()?;
                mirror_output([&stdout, &stderr], &mut positions)?;
            }
        }
        stdout.rewind()?;
        stderr.rewind()?;
        let mut out = String::new();
        let mut err = String::new();
        stdout
            .take(self.0.max_output_bytes + 1)
            .read_to_string(&mut out)?;
        stderr
            .take(self.0.max_output_bytes + 1)
            .read_to_string(&mut err)?;
        anyhow::ensure!(
            out.len() as u64 <= self.0.max_output_bytes
                && err.len() as u64 <= self.0.max_output_bytes,
            "subprocess output limit exceeded"
        );
        Ok(CommandOutput {
            status,
            stdout: out,
            stderr: err,
        })
    }
}

fn mirror_output(files: [&std::fs::File; 2], positions: &mut [u64; 2]) -> Result<()> {
    use std::os::unix::fs::FileExt;
    let mut buffer = [0; 8192];
    let mut output = io::stderr().lock();
    for (file, position) in files.into_iter().zip(positions) {
        // Limit work per tick so a continuously writing child cannot postpone cancellation.
        for _ in 0..16 {
            let count = file.read_at(&mut buffer, *position)?;
            if count == 0 {
                break;
            }
            output.write_all(&buffer[..count])?;
            *position += count as u64;
        }
    }
    output.flush()?;
    Ok(())
}

struct CapturedChild(std::process::Child);

impl Drop for CapturedChild {
    fn drop(&mut self) {
        if let Ok(pid) = i32::try_from(self.0.id()) {
            // The child creates its own process group before exec; a negative PID targets that group.
            unsafe {
                libc::kill(-pid, libc::SIGKILL);
            }
        }
        let _ = self.0.wait();
    }
}

pub fn ensure_command_available(program: &str) -> Result<()> {
    let output = Command::new(program)
        .arg("--version")
        .output()
        .with_context(|| format!("`{program}` is required but was not found in PATH"))?;
    if output.status.success() {
        Ok(())
    } else {
        bail!(
            "`{program} --version` exited with status {}",
            output.status.code().unwrap_or(1)
        )
    }
}

pub fn render_command(command: &Command) -> String {
    let program = command.get_program().to_string_lossy();
    let args = command
        .get_args()
        .map(os_to_display)
        .collect::<Vec<_>>()
        .join(" ");
    if args.is_empty() {
        program.into_owned()
    } else {
        format!("{program} {args}")
    }
}

pub fn run_capture(command: &mut Command) -> Result<CommandOutput> {
    let rendered = render_command(command);
    let output = command
        .output()
        .with_context(|| format!("failed to run `{rendered}`"))?;
    Ok(CommandOutput {
        status: output.status,
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    })
}

pub fn run_output(command: &mut Command, action: &str) -> Result<Output> {
    let rendered = render_command(command);
    let output = command
        .output()
        .with_context(|| format!("failed to run `{rendered}`"))?;
    if output.status.success() {
        Ok(output)
    } else {
        let detail = failure_detail_from_output(&output);
        bail!("Failed to {action} while running `{rendered}`: {detail}")
    }
}

pub fn run_with_input(command: &mut Command, input: &[u8]) -> Result<CommandOutput> {
    let rendered = render_command(command);
    command.stdin(Stdio::piped());
    command.stdout(Stdio::piped());
    command.stderr(Stdio::piped());
    let mut child = command
        .spawn()
        .with_context(|| format!("failed to run `{rendered}`"))?;

    if let Some(stdin) = child.stdin.as_mut() {
        stdin
            .write_all(input)
            .with_context(|| format!("failed to pipe stdin into `{rendered}`"))?;
    }

    let output = child
        .wait_with_output()
        .with_context(|| format!("failed waiting for `{rendered}`"))?;
    Ok(CommandOutput {
        status: output.status,
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    })
}

pub fn require_success(action: &str, command: &mut Command) -> Result<CommandOutput> {
    let rendered = render_command(command);
    let output = run_capture(command)?;
    if output.status.success() {
        return Ok(output);
    }
    bail!(
        "Failed to {action} while running `{rendered}`: {}",
        failure_detail(&output)
    )
}

pub fn require_success_with_input(
    action: &str,
    command: &mut Command,
    input: &[u8],
) -> Result<CommandOutput> {
    let rendered = render_command(command);
    let output = run_with_input(command, input)?;
    if output.status.success() {
        return Ok(output);
    }
    bail!(
        "Failed to {action} while running `{rendered}`: {}",
        failure_detail(&output)
    )
}

pub fn run_status(command: &mut Command, action: &str) -> Result<()> {
    require_success(action, command).map(|_| ())
}

pub fn run_status_streaming(command: &mut Command, action: &str) -> Result<()> {
    if !(io::stdout().is_terminal() || io::stderr().is_terminal()) {
        return run_status(command, action);
    }

    let rendered = render_command(command);
    command.stdin(Stdio::inherit());
    command.stdout(Stdio::inherit());
    command.stderr(Stdio::inherit());
    let status = command
        .status()
        .with_context(|| format!("failed to run `{rendered}`"))?;
    if status.success() {
        Ok(())
    } else {
        bail!(
            "Failed to {action} while running `{rendered}`: exit status {}",
            status.code().unwrap_or(1)
        )
    }
}

pub fn run_status_with_input(command: &mut Command, action: &str, input: &[u8]) -> Result<()> {
    require_success_with_input(action, command, input).map(|_| ())
}

pub fn run_text(command: &mut Command, action: &str) -> Result<String> {
    Ok(require_success(action, command)?.stdout.trim().to_owned())
}

pub fn run_json_value(command: &mut Command, action: &str) -> Result<Value> {
    run_json(command, action)
}

pub fn run_json<T: DeserializeOwned>(command: &mut Command, action: &str) -> Result<T> {
    let output = require_success(action, command)?;
    serde_json::from_str::<T>(&output.stdout).with_context(|| {
        format!(
            "Failed to parse JSON while trying to {action}: {}",
            truncate_ellipsis(output.stdout.trim(), 280)
        )
    })
}

pub fn run_status_code(command: &mut Command) -> Result<i32> {
    let rendered = render_command(command);
    let status = command
        .status()
        .with_context(|| format!("failed to run `{rendered}`"))?;
    Ok(status.code().unwrap_or(1))
}

fn failure_detail(output: &CommandOutput) -> String {
    let stderr = output.stderr.trim();
    let stdout = output.stdout.trim();
    if !stderr.is_empty() {
        stderr.to_owned()
    } else if !stdout.is_empty() {
        stdout.to_owned()
    } else {
        format!("exit status {}", output.status.code().unwrap_or(1))
    }
}

fn failure_detail_from_output(output: &Output) -> String {
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stderr = stderr.trim();
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stdout = stdout.trim();
    if !stderr.is_empty() {
        stderr.to_owned()
    } else if !stdout.is_empty() {
        stdout.to_owned()
    } else {
        format!("exit status {}", output.status.code().unwrap_or(1))
    }
}

fn os_to_display(value: &OsStr) -> String {
    shell_quote(&value.to_string_lossy())
}

fn truncate_ellipsis(value: &str, max_chars: usize) -> String {
    if value.chars().count() <= max_chars {
        return value.to_owned();
    }
    if max_chars <= 1 {
        return "…".to_owned();
    }
    let mut output = value
        .chars()
        .take(max_chars.saturating_sub(1))
        .collect::<String>();
    output.push('…');
    output
}

#[cfg(test)]
mod tests {
    use std::process::Command;

    #[test]
    fn bounded_capture_transmits_input_and_preserves_exit_status() {
        let output = super::CaptureOptions::default()
            .validate()
            .unwrap()
            .run(
                Command::new("sh").args(["-c", "cat; printf diagnostic >&2; exit 7"]),
                Some(b"payload\n"),
            )
            .unwrap();
        assert_eq!(output.stdout, "payload\n");
        assert_eq!(output.stderr, "diagnostic");
        assert_eq!(output.status.code(), Some(7));
        let error = super::CaptureOptions {
            max_output_bytes: 32,
            ..Default::default()
        }
        .validate()
        .unwrap()
        .run(Command::new("head").args(["-c", "1024", "/dev/zero"]), None)
        .unwrap_err();
        assert!(error.to_string().contains("output limit"));
    }

    #[test]
    fn capture_deadline_kills_descendants() {
        let directory = tempfile::tempdir().unwrap();
        let marker = directory.path().join("escaped");
        let error = super::CaptureOptions {
            timeout: std::time::Duration::from_millis(100),
            ..Default::default()
        }
        .validate()
        .unwrap()
        .run(
            Command::new("sh")
                .args(["-c", "(sleep 0.4; touch \"$1\") & wait", "test"])
                .arg(&marker),
            None,
        )
        .unwrap_err();
        assert!(error.to_string().contains("deadline"));
        std::thread::sleep(std::time::Duration::from_millis(500));
        assert!(!marker.exists(), "descendant survived its command deadline");
    }

    #[test]
    fn capture_cancellation_remains_typed() {
        if std::env::var_os("CAPULUS_TEST_CAPTURE_SIGNAL").is_some() {
            let cancellation = crate::Cancellation::install().unwrap();
            std::thread::spawn(|| {
                std::thread::sleep(std::time::Duration::from_millis(100));
                unsafe {
                    libc::kill(libc::getpid(), libc::SIGINT);
                }
            });
            let error = super::CaptureOptions {
                cancellation,
                ..Default::default()
            }
            .validate()
            .unwrap()
            .run(Command::new("sleep").arg("30"), None)
            .unwrap_err()
            .context("operation stopped");
            assert!(crate::error_is_cancelled(&error));
            return;
        }
        let result = super::CaptureOptions {
            timeout: std::time::Duration::from_secs(10),
            ..Default::default()
        }
        .validate()
        .unwrap()
        .run(
            Command::new(std::env::current_exe().unwrap())
                .args([
                    "--exact",
                    "process::tests::capture_cancellation_remains_typed",
                    "--nocapture",
                ])
                .env("CAPULUS_TEST_CAPTURE_SIGNAL", "1"),
            None,
        )
        .unwrap();
        assert!(result.status.success(), "{}", result.stderr);
    }

    use super::{render_command, require_success, run_with_input};

    #[test]
    fn render_command_quotes_args_with_whitespace() {
        let mut command = Command::new("ssh");
        command.args(["user@example.com", "echo hello world"]);

        assert_eq!(
            "ssh 'user@example.com' 'echo hello world'",
            render_command(&command)
        );
    }

    #[test]
    fn run_with_input_pipes_stdin_to_child() {
        let mut command = Command::new("cat");
        let output = run_with_input(&mut command, b"abc\n").expect("cat should succeed");

        assert!(output.status.success());
        assert_eq!("abc\n", output.stdout);
    }

    #[test]
    fn require_success_reports_stdout_when_stderr_is_empty() {
        let mut command = Command::new("sh");
        command.args(["-c", "printf 'stdout-only'; exit 2"]);

        let error =
            require_success("run failing command", &mut command).expect_err("command should fail");
        let text = error.to_string();
        assert!(text.contains("stdout-only"));
    }
}