only-engine 0.5.1

Execution planning and runtime engine for only tasks.
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
use std::collections::HashMap;
use std::io::Read;
use std::path::Path;
use std::rc::Rc;
use std::sync::mpsc::Sender;
use std::time::Duration;

use only_semantic::{ShellKind, ShellOperator, ShellSelection};

use crate::EngineError;

#[cfg(unix)]
mod unix;
#[cfg(windows)]
mod windows;

use crate::path_lookup::command_exists_in_path;
use crate::process::{
    CommandStatus, OutputChunk, StdinAccess, TerminalContext, build_command_env,
    join_output_reader, run_with_system_shell, run_with_system_shell_inherit, spawn_output_reader,
};
#[cfg(unix)]
use unix as platform;
#[cfg(windows)]
use windows as platform;

pub(crate) fn run_command(
    command: &str,
    working_dir: &Path,
    shell: &ShellSelection,
    output: Sender<OutputChunk>,
    terminal: &TerminalContext,
) -> Result<CommandStatus, EngineError> {
    let resolved_shell = resolve_shell(shell)?;
    match resolved_shell {
        ShellKind::Deno => platform::run_deno(command, working_dir, output, terminal),
        ShellKind::Sh => run_with_system_shell("sh", "-c", command, working_dir, output, terminal),
        ShellKind::Bash => {
            run_with_system_shell("bash", "-c", command, working_dir, output, terminal)
        }
        ShellKind::Powershell => run_with_system_shell(
            platform::power_shell_command(),
            "-Command",
            command,
            working_dir,
            output,
            terminal,
        ),
        ShellKind::Pwsh => {
            run_with_system_shell("pwsh", "-Command", command, working_dir, output, terminal)
        }
        ShellKind::Unknown(name) => Err(EngineError::UnsupportedShell(name.to_string())),
    }
}

pub(crate) fn run_command_inherit(
    command: &str,
    working_dir: &Path,
    shell: &ShellSelection,
    terminal: &TerminalContext,
    stdin: StdinAccess,
) -> Result<CommandStatus, EngineError> {
    let resolved_shell = resolve_shell(shell)?;
    match resolved_shell {
        ShellKind::Deno => run_with_deno_task_shell_inherit(command, working_dir, terminal, stdin),
        ShellKind::Sh => {
            run_with_system_shell_inherit("sh", "-c", command, working_dir, terminal, stdin)
        }
        ShellKind::Bash => {
            run_with_system_shell_inherit("bash", "-c", command, working_dir, terminal, stdin)
        }
        ShellKind::Powershell => run_with_system_shell_inherit(
            platform::power_shell_command(),
            "-Command",
            command,
            working_dir,
            terminal,
            stdin,
        ),
        ShellKind::Pwsh => {
            run_with_system_shell_inherit("pwsh", "-Command", command, working_dir, terminal, stdin)
        }
        ShellKind::Unknown(name) => Err(EngineError::UnsupportedShell(name.to_string())),
    }
}

fn resolve_shell(shell: &ShellSelection) -> Result<ShellKind, EngineError> {
    match &shell.kind {
        ShellKind::Pwsh => {
            if command_exists_in_path("pwsh") {
                return Ok(ShellKind::Pwsh);
            }
            if shell.operator == ShellOperator::Fallback
                && command_exists_in_path(platform::power_shell_command())
            {
                return Ok(ShellKind::Powershell);
            }
            Err(EngineError::ShellNotFound(
                "pwsh was not found\nhelp: install PowerShell 7+, or use `shell~=pwsh`".to_string(),
            ))
        }
        ShellKind::Bash => {
            if command_exists_in_path("bash") {
                return Ok(ShellKind::Bash);
            }
            if shell.operator == ShellOperator::Fallback && command_exists_in_path("sh") {
                return Ok(ShellKind::Sh);
            }
            Err(EngineError::ShellNotFound(
                "bash was not found\nhelp: install bash, or use `shell~=bash`".to_string(),
            ))
        }
        ShellKind::Powershell => {
            if command_exists_in_path(platform::power_shell_command()) {
                return Ok(ShellKind::Powershell);
            }
            Err(EngineError::ShellNotFound(
                "powershell was not found\nhelp: install Windows PowerShell".to_string(),
            ))
        }
        ShellKind::Sh => {
            if command_exists_in_path("sh") {
                return Ok(ShellKind::Sh);
            }
            Err(EngineError::ShellNotFound(
                "sh was not found\nhelp: install a POSIX shell".to_string(),
            ))
        }
        ShellKind::Deno => Ok(ShellKind::Deno),
        ShellKind::Unknown(name) => Err(EngineError::UnsupportedShell(name.to_string())),
    }
}

fn run_with_deno_task_shell_pipe(
    command: &str,
    working_dir: &Path,
    output: Sender<OutputChunk>,
    terminal: &TerminalContext,
) -> Result<CommandStatus, EngineError> {
    let parsed = deno_task_shell::parser::parse(command).map_err(|error| {
        EngineError::Runtime(format!("failed to parse command `{command}`: {error}"))
    })?;
    let env_vars = build_command_env(terminal);
    let kill_signal = deno_task_shell::KillSignal::default();
    let state = deno_task_shell::ShellState::new(
        env_vars,
        working_dir.to_path_buf(),
        HashMap::<String, Rc<dyn deno_task_shell::ShellCommand>>::new(),
        kill_signal.clone(),
    );
    let (stdout_reader, stdout_writer) = deno_task_shell::pipe();
    let (stderr_writer, output_handles) =
        if terminal.backend == crate::process::TerminalBackend::MergedPipe {
            let handle = spawn_output_reader(
                ShellPipeReaderAdapter(stdout_reader),
                crate::process::OutputStream::Stdout,
                output,
            );
            (stdout_writer.clone(), vec![handle])
        } else {
            let (stderr_reader, stderr_writer) = deno_task_shell::pipe();
            let stdout_handle = spawn_output_reader(
                ShellPipeReaderAdapter(stdout_reader),
                crate::process::OutputStream::Stdout,
                output.clone(),
            );
            let stderr_handle = spawn_output_reader(
                ShellPipeReaderAdapter(stderr_reader),
                crate::process::OutputStream::Stderr,
                output,
            );
            (stderr_writer, vec![stdout_handle, stderr_handle])
        };
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|error| EngineError::Runtime(format!("failed to start task runtime: {error}")))?;
    let local = tokio::task::LocalSet::new();
    let status = local.block_on(&runtime, async {
        let execution = deno_task_shell::execute_with_pipes(
            parsed,
            state,
            closed_stdin(),
            stdout_writer,
            stderr_writer,
        );
        let mut execution = Box::pin(execution);
        loop {
            match tokio::time::timeout(Duration::from_millis(20), &mut execution).await {
                Ok(status) => break status,
                Err(_) if terminal.is_cancelled() => {
                    kill_signal.send(deno_task_shell::SignalKind::SIGINT);
                }
                Err(_) => {}
            }
        }
    });
    for handle in output_handles {
        join_output_reader(handle)?;
    }

    Ok(CommandStatus::from_code(status))
}

#[cfg(unix)]
fn run_with_deno_task_shell_pty(
    command: &str,
    working_dir: &Path,
    output: Sender<OutputChunk>,
    terminal: &TerminalContext,
) -> Result<Option<CommandStatus>, EngineError> {
    let parsed = deno_task_shell::parser::parse(command).map_err(|error| {
        EngineError::Runtime(format!("failed to parse command `{command}`: {error}"))
    })?;
    let pty_system = portable_pty::native_pty_system();
    let pair = match pty_system.openpty(terminal.size.into()) {
        Ok(pair) => pair,
        Err(_) => return Ok(None),
    };
    let reader = match pair.master.try_clone_reader() {
        Ok(reader) => reader,
        Err(_) => return Ok(None),
    };
    let Some(tty_name) = pair.master.tty_name() else {
        return Ok(None);
    };
    let stdout_file = match std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(&tty_name)
    {
        Ok(file) => file,
        Err(_) => return Ok(None),
    };
    let stderr_file = match stdout_file.try_clone() {
        Ok(file) => file,
        Err(_) => return Ok(None),
    };

    let kill_signal = deno_task_shell::KillSignal::default();
    let state = deno_task_shell::ShellState::new(
        build_command_env(terminal),
        working_dir.to_path_buf(),
        HashMap::<String, Rc<dyn deno_task_shell::ShellCommand>>::new(),
        kill_signal.clone(),
    );
    let reader_handle =
        crate::process::spawn_output_reader(reader, crate::process::OutputStream::Stdout, output);
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|error| EngineError::Runtime(format!("failed to start task runtime: {error}")))?;
    let local = tokio::task::LocalSet::new();
    let status = local.block_on(&runtime, async {
        let execution = deno_task_shell::execute_with_pipes(
            parsed,
            state,
            closed_stdin(),
            deno_task_shell::ShellPipeWriter::from_std(stdout_file),
            deno_task_shell::ShellPipeWriter::from_std(stderr_file),
        );
        let mut execution = Box::pin(execution);
        loop {
            match tokio::time::timeout(Duration::from_millis(20), &mut execution).await {
                Ok(status) => break status,
                Err(_) if terminal.is_cancelled() => {
                    kill_signal.send(deno_task_shell::SignalKind::SIGINT);
                }
                Err(_) => {}
            }
        }
    });
    drop(pair.slave);
    join_output_reader(reader_handle)?;

    Ok(Some(CommandStatus::from_code(status)))
}

fn run_with_deno_task_shell_inherit(
    command: &str,
    working_dir: &Path,
    terminal: &TerminalContext,
    stdin: StdinAccess,
) -> Result<CommandStatus, EngineError> {
    let parsed = deno_task_shell::parser::parse(command).map_err(|error| {
        EngineError::Runtime(format!("failed to parse command `{command}`: {error}"))
    })?;
    let kill_signal = deno_task_shell::KillSignal::default();
    let state = deno_task_shell::ShellState::new(
        build_command_env(terminal),
        working_dir.to_path_buf(),
        HashMap::<String, Rc<dyn deno_task_shell::ShellCommand>>::new(),
        kill_signal.clone(),
    );
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|error| EngineError::Runtime(format!("failed to start task runtime: {error}")))?;
    let local = tokio::task::LocalSet::new();
    let status = local.block_on(&runtime, async {
        let execution = deno_task_shell::execute_with_pipes(
            parsed,
            state,
            match stdin {
                StdinAccess::Owned => deno_task_shell::ShellPipeReader::stdin(),
                StdinAccess::Closed => closed_stdin(),
            },
            deno_task_shell::ShellPipeWriter::stdout(),
            deno_task_shell::ShellPipeWriter::stderr(),
        );
        let mut execution = Box::pin(execution);
        loop {
            match tokio::time::timeout(Duration::from_millis(20), &mut execution).await {
                Ok(status) => break status,
                Err(_) if terminal.is_cancelled() => {
                    kill_signal.send(deno_task_shell::SignalKind::SIGINT);
                }
                Err(_) => {}
            }
        }
    });

    Ok(CommandStatus::from_code(status))
}

struct ShellPipeReaderAdapter(deno_task_shell::ShellPipeReader);

fn closed_stdin() -> deno_task_shell::ShellPipeReader {
    let path = if cfg!(windows) { "NUL" } else { "/dev/null" };
    deno_task_shell::ShellPipeReader::from_std(
        std::fs::File::open(path).expect("the platform null device should be available"),
    )
}

impl Read for ShellPipeReaderAdapter {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.0
            .read(buf)
            .map_err(|error| std::io::Error::other(error.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use std::sync::mpsc;
    use std::time::{Duration, Instant};

    use super::platform;
    use crate::process::TerminalContext;

    #[test]
    fn cancels_deno_shell() {
        let context = TerminalContext::pipe();
        let execution_context = context.clone();
        let (output_tx, _output_rx) = mpsc::channel();
        let working_dir = std::env::current_dir().expect("current directory should be available");
        let started = Instant::now();
        let command = std::thread::spawn(move || {
            platform::run_deno("sleep 30", &working_dir, output_tx, &execution_context)
        });

        std::thread::sleep(Duration::from_millis(50));
        context.cancel();
        let status = command
            .join()
            .expect("command thread should finish")
            .expect("cancelled command should be reaped");

        assert!(status.failure_reason().is_some());
        assert!(started.elapsed() < Duration::from_secs(2));
    }

    #[cfg(unix)]
    #[test]
    fn deno_pty_exposes_terminal() {
        let (output_tx, output_rx) = mpsc::channel();
        let working_dir = std::env::current_dir().expect("current directory should be available");
        let status = platform::run_deno(
            "sh -c 'test -t 1 && printf tty || printf pipe'",
            &working_dir,
            output_tx,
            &TerminalContext::pty(),
        )
        .expect("Deno PTY command should run");
        let output = output_rx
            .into_iter()
            .flat_map(|chunk| chunk.bytes)
            .collect::<Vec<_>>();

        assert_eq!(status, crate::process::CommandStatus::Success);
        assert_eq!(output, b"tty");
    }

    #[cfg(unix)]
    #[test]
    fn deno_merged_preserves_order() {
        let (output_tx, output_rx) = mpsc::channel();
        let working_dir = std::env::current_dir().expect("current directory should be available");
        let terminal = TerminalContext::pty().for_captured_output();
        let status = platform::run_deno(
            "printf first; printf second >&2; printf third",
            &working_dir,
            output_tx,
            &terminal,
        )
        .expect("Deno merged pipe command should run");
        let output = output_rx
            .into_iter()
            .flat_map(|chunk| chunk.bytes)
            .collect::<Vec<_>>();

        assert_eq!(status, crate::process::CommandStatus::Success);
        assert_eq!(output, b"firstsecondthird");
    }

    #[cfg(unix)]
    #[test]
    fn deno_merged_preserves_large_output() {
        let (output_tx, output_rx) = mpsc::channel();
        let working_dir = std::env::current_dir().expect("current directory should be available");
        let terminal = TerminalContext::pty().for_captured_output();
        let status = platform::run_deno(
            "sh -c 'i=1; while test $i -le 2000; do printf \"line-%04d\\n\" $i >&2; i=$((i + 1)); done'",
            &working_dir,
            output_tx,
            &terminal,
        )
        .expect("Deno merged pipe command should run");
        let output = String::from_utf8(
            output_rx
                .into_iter()
                .flat_map(|chunk| chunk.bytes)
                .collect::<Vec<_>>(),
        )
        .expect("command output should be UTF-8");
        let expected = (1..=2000)
            .map(|index| format!("line-{index:04}\n"))
            .collect::<String>();

        assert_eq!(status, crate::process::CommandStatus::Success);
        assert_eq!(output, expected);
    }
}