Skip to main content

qk_executor/
lib.rs

1//! Prepare finite tasks, then execute shell commands in managed process groups.
2
3mod capture;
4pub mod dotenv;
5mod env_flags;
6mod interpolate;
7mod process;
8#[cfg(unix)]
9mod pty;
10pub mod readiness;
11pub mod ready_signal;
12pub mod report;
13pub mod tokens;
14
15use std::collections::BTreeMap;
16use std::ffi::OsString;
17use std::path::{Path, PathBuf};
18
19use anyhow::{Context, Result, bail};
20use qk_config::Workspace;
21use qk_taskgraph::Task;
22use serde_json::{Map, Value};
23
24pub use capture::{
25    Capture, Decoration, Display, MAX_LOG_BYTES, OutputStyle, RecordedLog, Shown, collapsed,
26    printable, read_capture, replay,
27};
28pub use env_flags::{force_colour, is_ci, is_ci_with};
29pub use process::{Outcome, execute, execute_captured, shell};
30
31#[derive(Debug)]
32struct NodeRuntime {
33    root: PathBuf,
34    env: BTreeMap<OsString, OsString>,
35    paths: Vec<PathBuf>,
36    directory: std::sync::OnceLock<Option<PathBuf>>,
37}
38
39/// The runner's Node selection, resolved only when a command starts.
40#[derive(Clone, Debug)]
41pub struct NodePath {
42    runtime: std::sync::Arc<NodeRuntime>,
43    local_entries: usize,
44}
45
46impl NodePath {
47    fn new(root: &Path, env: &BTreeMap<OsString, OsString>, local_entries: usize) -> Self {
48        type Key = (PathBuf, BTreeMap<OsString, OsString>);
49        static RUNTIMES: std::sync::OnceLock<
50            std::sync::Mutex<BTreeMap<Key, std::sync::Arc<NodeRuntime>>>,
51        > = std::sync::OnceLock::new();
52        let mut runtimes = RUNTIMES.get_or_init(Default::default).lock().unwrap();
53        let runtime = runtimes
54            .entry((root.to_owned(), env.clone()))
55            .or_insert_with(|| {
56                let paths = env
57                    .get(&path_key(env))
58                    .map(|path| std::env::split_paths(path).collect())
59                    .unwrap_or_default();
60                std::sync::Arc::new(NodeRuntime {
61                    root: root.to_owned(),
62                    env: env.clone(),
63                    paths,
64                    directory: Default::default(),
65                })
66            })
67            .clone();
68        Self {
69            runtime,
70            local_entries,
71        }
72    }
73
74    fn path(&self, env: &BTreeMap<OsString, OsString>) -> Result<Option<(OsString, OsString)>> {
75        // Select before task overrides, like process.execPath in Nx. Cache hits
76        // never call this, and concurrent commands share the same proxy probe.
77        let Some(directory) = self.runtime.directory.get_or_init(|| {
78            node_directory(&self.runtime.root, &self.runtime.paths, &self.runtime.env)
79        }) else {
80            return Ok(None);
81        };
82        let key = path_key(env);
83        let mut paths: Vec<_> = env
84            .get(&key)
85            .map(|path| std::env::split_paths(path).collect())
86            .unwrap_or_default();
87        paths.insert(self.local_entries.min(paths.len()), directory.clone());
88        Ok(Some((
89            key,
90            std::env::join_paths(paths).context("cannot construct task PATH")?,
91        )))
92    }
93}
94
95fn path_key(env: &BTreeMap<OsString, OsString>) -> OsString {
96    if cfg!(windows) {
97        env.keys()
98            .find(|key| key.to_string_lossy().eq_ignore_ascii_case("PATH"))
99            .cloned()
100            .unwrap_or_else(|| "PATH".into())
101    } else {
102        "PATH".into()
103    }
104}
105
106fn environment_key(env: &BTreeMap<OsString, OsString>, name: OsString) -> OsString {
107    if cfg!(windows) && name.to_string_lossy().eq_ignore_ascii_case("PATH") {
108        path_key(env)
109    } else {
110        name
111    }
112}
113
114fn node_directory(
115    cwd: &Path,
116    paths: &[PathBuf],
117    env: &BTreeMap<OsString, OsString>,
118) -> Option<PathBuf> {
119    let name = if cfg!(windows) { "node.exe" } else { "node" };
120    for directory in paths {
121        let candidate = cwd.join(directory).join(name);
122        let Ok(metadata) = candidate.metadata() else {
123            continue;
124        };
125        if !metadata.is_file() {
126            continue;
127        }
128        #[cfg(unix)]
129        {
130            use std::os::unix::fs::PermissionsExt;
131            if metadata.permissions().mode() & 0o111 == 0 {
132                continue;
133            }
134        }
135        // The first executable PATH match is authoritative, even if discovery fails.
136        let actual = candidate.canonicalize().ok()?;
137        if actual.file_name()? == name {
138            use std::io::Read;
139            let mut header = [0; 2];
140            let script = std::fs::File::open(&actual)
141                .and_then(|mut file| file.read_exact(&mut header))
142                .is_ok()
143                && header == *b"#!";
144            if !script {
145                return actual.parent().map(Path::to_owned);
146            }
147        }
148        return probe_node(&candidate, cwd, env);
149    }
150    None
151}
152
153fn probe_node(candidate: &Path, cwd: &Path, env: &BTreeMap<OsString, OsString>) -> Option<PathBuf> {
154    use std::io::{Read, Seek};
155    use std::process::{Command, Stdio};
156    use std::time::{Duration, Instant};
157    let mut output = tempfile::tempfile().ok()?;
158    let mut child = Command::new(candidate)
159        .args(["-p", "process.execPath"])
160        .current_dir(cwd)
161        .env_clear()
162        .envs(env)
163        .stdout(Stdio::from(output.try_clone().ok()?))
164        .stderr(Stdio::null())
165        .spawn()
166        .ok()?;
167    let started = Instant::now();
168    loop {
169        match child.try_wait() {
170            Ok(Some(status)) => {
171                if !status.success() {
172                    return None;
173                }
174                let mut bytes = Vec::new();
175                output.rewind().ok()?;
176                output.take(4096).read_to_end(&mut bytes).ok()?;
177                let path = PathBuf::from(std::str::from_utf8(&bytes).ok()?.trim());
178                return (path.is_absolute() && path.is_file())
179                    .then(|| path.parent().unwrap().to_owned());
180            }
181            Ok(None) if started.elapsed() < Duration::from_secs(2) => {
182                std::thread::sleep(Duration::from_millis(5))
183            }
184            _ => {
185                let _ = child.kill();
186                let _ = child.wait();
187                return None;
188            }
189        }
190    }
191}
192
193/// Reports a `qk:` warning to the installed sink; by default it is written to
194/// stderr in one write, so task processes sharing stderr cannot split it.
195#[macro_export]
196macro_rules! status {
197    ($($arg:tt)*) => {{
198        $crate::report::warning(&::std::format!($($arg)*));
199    }};
200}
201
202/// How a sandboxed task's commands are held to what it declares.
203#[derive(Clone, Debug)]
204pub enum Confinement {
205    /// macOS: a Seatbelt profile, through `sandbox-exec`.
206    Seatbelt(PathBuf),
207    /// Linux: a Landlock rule set's descriptor, which each command restricts
208    /// itself to before it starts. It stays open while the run lasts.
209    Landlock(i32),
210}
211
212/// An external syscall recorder wrapping each command, with separate trace files.
213#[derive(Clone, Debug)]
214pub struct Recording {
215    /// The recorder's program: strace, or qk itself, whose helper loads the
216    /// eBPF recorder.
217    pub program: PathBuf,
218    pub directory: PathBuf,
219    /// Whether strace filters the traced calls in the kernel, with seccomp,
220    /// so untraced calls run at full speed. strace 5.3 and later can.
221    pub seccomp: bool,
222    /// The eBPF recorder, and the recordings of this task's commands it has
223    /// begun; `None` when strace records.
224    #[cfg(target_os = "linux")]
225    ebpf: Option<Ebpf>,
226}
227
228#[cfg(target_os = "linux")]
229#[derive(Clone, Debug)]
230struct Ebpf {
231    recorder: std::sync::Arc<qk_trace::Recorder>,
232    sessions: std::sync::Arc<std::sync::Mutex<Vec<qk_trace::Session>>>,
233    /// Whether an opened file's path is recorded with what its links lead
234    /// to, as strace records it, which costs a lookup an open.
235    resolve: bool,
236}
237
238/// The eBPF recorder, its helper started once a process: as qk itself when
239/// qk runs as root, else through `sudo -n`, so that it is never asked for a
240/// password.
241#[cfg(target_os = "linux")]
242fn ebpf_recorder() -> Result<std::sync::Arc<qk_trace::Recorder>, String> {
243    static RECORDER: std::sync::OnceLock<Result<std::sync::Arc<qk_trace::Recorder>, String>> =
244        std::sync::OnceLock::new();
245    RECORDER
246        .get_or_init(|| {
247            let qk = std::env::current_exe().map_err(|error| error.to_string())?;
248            // SAFETY: geteuid has no preconditions.
249            let helper = if unsafe { libc::geteuid() } == 0 {
250                let mut helper = std::process::Command::new(qk);
251                helper.arg("__trace-helper");
252                helper
253            } else {
254                let mut helper = std::process::Command::new("sudo");
255                helper.args(["-n", "--"]).arg(qk).arg("__trace-helper");
256                helper
257            };
258            qk_trace::Recorder::start(helper).map_err(|error| format!("{error:#}"))
259        })
260        .clone()
261}
262
263impl Recording {
264    /// The recorder `QK_RECORDER` picks: by default eBPF, where its helper
265    /// can load it, else strace on `PATH`, checked to record child
266    /// processes, with seccomp filtering where it supports it. Its trial
267    /// traces go in `directory`.
268    pub fn probe(directory: &Path) -> anyhow::Result<Self> {
269        let choice = std::env::var("QK_RECORDER").unwrap_or_default();
270        match choice.as_str() {
271            "" | "auto" | "ebpf" =>
272            {
273                #[cfg(target_os = "linux")]
274                match ebpf_recorder() {
275                    Ok(recorder) => {
276                        return Ok(Self {
277                            program: std::env::current_exe()?,
278                            directory: directory.to_owned(),
279                            seccomp: false,
280                            ebpf: Some(Ebpf {
281                                recorder,
282                                sessions: Default::default(),
283                                resolve: false,
284                            }),
285                        });
286                    }
287                    Err(error) if choice == "ebpf" => {
288                        anyhow::bail!("cannot record with eBPF: {error}")
289                    }
290                    Err(_) => {}
291                }
292            }
293            "strace" => {}
294            other => anyhow::bail!("unknown QK_RECORDER {other:?}; use auto, ebpf or strace"),
295        }
296        let path = std::env::var_os("PATH").context("recording needs strace on PATH")?;
297        let program = std::env::split_paths(&path)
298            .map(|directory| directory.join("strace"))
299            .find(|candidate| candidate.is_file())
300            .context("recording needs strace on PATH; install strace and retry")?
301            .canonicalize()?;
302        let mut failure = String::new();
303        for seccomp in [true, false] {
304            let recording = Self {
305                program: program.clone(),
306                directory: directory.to_owned(),
307                seccomp,
308                #[cfg(target_os = "linux")]
309                ebpf: None,
310            };
311            let probe = recording
312                .command(0, "exec /bin/true", Path::new("/"))
313                .output()
314                .context("cannot probe strace")?;
315            if probe.status.success() {
316                return Ok(recording);
317            }
318            failure = String::from_utf8_lossy(&probe.stderr).into_owned();
319        }
320        anyhow::bail!("strace cannot record child processes: {failure}")
321    }
322
323    /// The same settings, with traces in `directory`.
324    /// The recorder's name, as reports give it: `ebpf` or `strace`.
325    pub fn backend(&self) -> &'static str {
326        #[cfg(target_os = "linux")]
327        if self.ebpf.is_some() {
328            return "ebpf";
329        }
330        "strace"
331    }
332
333    pub fn in_directory(&self, directory: PathBuf) -> Self {
334        Self {
335            directory,
336            #[cfg(target_os = "linux")]
337            ebpf: self.ebpf.as_ref().map(|ebpf| Ebpf {
338                recorder: ebpf.recorder.clone(),
339                sessions: Default::default(),
340                resolve: ebpf.resolve,
341            }),
342            ..self.clone()
343        }
344    }
345
346    /// The same, recording an opened file's path with what its links lead
347    /// to, as a report of what a task read shows it. strace always does.
348    pub fn resolving(self) -> Self {
349        #[cfg(target_os = "linux")]
350        {
351            let mut recording = self;
352            if let Some(ebpf) = &mut recording.ebpf {
353                ebpf.resolve = true;
354            }
355            recording
356        }
357        #[cfg(not(target_os = "linux"))]
358        self
359    }
360
361    /// Ends the recordings of the commands that have run, once they have
362    /// finished, so that their traces are whole. strace's are as soon as it
363    /// exits; the eBPF recorder's once its helper has sent every event.
364    pub fn settle(&self) -> anyhow::Result<()> {
365        #[cfg(target_os = "linux")]
366        if let Some(ebpf) = &self.ebpf {
367            let sessions = std::mem::take(&mut *ebpf.sessions.lock().unwrap());
368            let mut sessions = sessions.into_iter();
369            while let Some(session) = sessions.next() {
370                if let Err(error) = ebpf.recorder.finish(session) {
371                    // The rest without waiting again: a helper that did not
372                    // answer once will not now.
373                    sessions
374                        .by_ref()
375                        .for_each(|rest| ebpf.recorder.abandon(rest));
376                    return Err(error);
377                }
378            }
379        }
380        Ok(())
381    }
382
383    /// The same invocation is used by preflight and actual task commands,
384    /// which start in `cwd`.
385    pub fn command(&self, index: usize, text: &str, cwd: &Path) -> std::process::Command {
386        #[cfg(target_os = "linux")]
387        if let Some(ebpf) = &self.ebpf {
388            use std::os::unix::process::CommandExt;
389            let session = ebpf.recorder.begin(
390                &self.directory,
391                &format!("command-{index}"),
392                cwd,
393                ebpf.resolve,
394            );
395            ebpf.sessions.lock().unwrap().push(session);
396            let mut command = crate::process::shell(text);
397            // SAFETY: the hook makes one system call.
398            unsafe { command.pre_exec(ebpf.recorder.join(session)) };
399            return command;
400        }
401        let _ = cwd;
402        let mut command = std::process::Command::new(&self.program);
403        // No read/write buffers or exec argument/environment arrays.
404        if self.seccomp {
405            command.arg("--seccomp-bpf");
406        }
407        command
408            .args([
409                "-ff",
410                "-ttt",
411                "-yy",
412                "-qq",
413                "-s",
414                "4096",
415                "-e",
416                "trace=%file,%process,getdents64,fchdir,close,dup,dup2,dup3,getcwd",
417                "-e",
418                "raw=execve,execveat",
419                "-o",
420            ])
421            .arg(self.directory.join(format!("command-{index}")))
422            .args(["--", "/bin/sh", "-c", text]);
423        command
424    }
425}
426
427#[derive(Clone, Debug)]
428pub struct PreparedTask {
429    pub id: String,
430    pub commands: Vec<String>,
431    pub parallel: bool,
432    pub cwd: PathBuf,
433    pub env: BTreeMap<OsString, OsString>,
434    /// Dotenv, explicit settings and local binary lookup without task metadata.
435    pub runtime_env: BTreeMap<OsString, OsString>,
436    pub node_path: Option<NodePath>,
437    /// Variables set for the process after `env` that are not part of what
438    /// the task is: nothing reads them to key it, such as a thread count.
439    pub execution: BTreeMap<OsString, OsString>,
440    /// Nx's `readyWhen`: text whose appearance in the output, every piece of
441    /// it, makes the task ready while its commands keep running.
442    pub ready_when: Vec<String>,
443    /// Set once all of `ready_when` has appeared.
444    pub ready: std::sync::Arc<std::sync::atomic::AtomicBool>,
445    /// A continuous target's own `readyWhen`, which tasks depending on it
446    /// with `waitFor: "ready"` wait for, or why it is invalid. Prepared, it is
447    /// resolved without `NX_READY_URL`; see [`PreparedTask::resolve_ready_check`].
448    pub ready_check: Option<std::result::Result<readiness::ReadyCheck, String>>,
449    /// What `ready_check` is resolved from, to resolve it again once the
450    /// servers the task waits for have reported their address.
451    pub ready_inputs: Option<std::sync::Arc<ReadyInputs>>,
452    /// What `ready_check` concluded.
453    pub verdict: std::sync::Arc<readiness::Verdict>,
454    /// The process ids of its commands while they run, from which the runner
455    /// measures the memory the task uses.
456    pub processes: std::sync::Arc<std::sync::Mutex<std::collections::BTreeSet<u32>>>,
457    /// Each command's prefix and colours, by position; empty without any.
458    pub decorations: Vec<Decoration>,
459    /// Whether the task reads qk's stdin, and has the terminal while it runs.
460    /// The runner sets it for the one task a run is for, when that task has a
461    /// single command whose output goes straight to the terminal.
462    pub interactive: bool,
463    /// Whether captured commands may run under a pseudo-terminal, which they
464    /// do when qk's output is a terminal: Nx's `usePty`. Commands whose
465    /// output is hashed set it to false, so keys never depend on a terminal.
466    pub pseudo_terminal: bool,
467    /// Nx's `tty`: whether qk's terminal is in raw input mode while the
468    /// interactive task reads it through a pseudo-terminal.
469    pub tty: bool,
470    /// What the commands run under, for `--sandbox`.
471    pub sandbox: Option<Confinement>,
472    pub recording: Option<Recording>,
473    /// How the task's output is shown; the runner sets it per output style.
474    pub display: Display,
475}
476
477/// The dotenv files Nx loads for a task, most specific first: in the
478/// project root, then the workspace root, for the target and configuration
479/// (`.env.<target>.<configuration>`, `.env.<configuration>`, `.env.<target>`),
480/// then `.env.local`, `.local.env` and `.env`, each also in its `.local` and
481/// `.<name>.env` spellings. An atomized target also reads the files of the
482/// target it was split from, after its own of the same kind.
483fn dotenv_files(
484    project_root: &str,
485    target: &str,
486    configuration: Option<&str>,
487    non_atomized: Option<&str>,
488) -> Vec<String> {
489    let mut identifiers = Vec::new();
490    if let Some(configuration) = configuration {
491        identifiers.push(format!("{target}.{configuration}"));
492        if let Some(non_atomized) = non_atomized {
493            identifiers.push(format!("{non_atomized}.{configuration}"));
494        }
495        identifiers.push(configuration.to_owned());
496    }
497    identifiers.push(target.to_owned());
498    if let Some(non_atomized) = non_atomized {
499        identifiers.push(non_atomized.to_owned());
500    }
501    identifiers.push(String::new());
502    let variants = |identifier: &str, root: &str| -> Vec<String> {
503        let prefix = if root.is_empty() || root == "." {
504            String::new()
505        } else {
506            format!("{root}/")
507        };
508        if identifier.is_empty() {
509            [".env.local", ".local.env", ".env"]
510                .map(|name| format!("{prefix}{name}"))
511                .to_vec()
512        } else {
513            [
514                format!(".env.{identifier}.local"),
515                format!(".env.{identifier}"),
516                format!(".{identifier}.local.env"),
517                format!(".{identifier}.env"),
518            ]
519            .map(|name| format!("{prefix}{name}"))
520            .to_vec()
521        }
522    };
523    let mut files = Vec::new();
524    for root in [project_root, ""] {
525        for identifier in &identifiers {
526            // Colons in target names cannot name regular dotenv files on Windows.
527            #[cfg(windows)]
528            if identifier.contains(':') {
529                continue;
530            }
531            for file in variants(identifier, root) {
532                if !files.contains(&file) {
533                    files.push(file);
534                }
535            }
536        }
537    }
538    files
539}
540
541/// The target whose dotenv files a task reads, and the target it was
542/// atomized from, as Nx's getOwnerTargetForTask finds them: through the
543/// project's `metadata.targetGroups`, a target of the task's group that
544/// names a `metadata.nonAtomizedTarget`. Unlike Nx, a task that names one
545/// itself is its own owner, so each atomized target reads its own files
546/// rather than the first of its group's.
547fn owner_target<'a>(
548    project: &'a qk_config::Project,
549    target: &'a str,
550) -> (&'a str, Option<&'a str>) {
551    let non_atomized = |definition: &'a qk_config::Target| {
552        definition
553            .extra
554            .get("metadata")
555            .and_then(|metadata| metadata.get("nonAtomizedTarget"))
556            .and_then(Value::as_str)
557    };
558    if let Some((name, definition)) = project.targets.get_key_value(target)
559        && let Some(non_atomized) = non_atomized(definition)
560    {
561        return (name, Some(non_atomized));
562    }
563    let groups = project
564        .extra
565        .get("metadata")
566        .and_then(|metadata| metadata.get("targetGroups"))
567        .and_then(Value::as_object);
568    for group in groups.into_iter().flat_map(|groups| groups.values()) {
569        let members: Vec<&str> = group
570            .as_array()
571            .into_iter()
572            .flatten()
573            .filter_map(Value::as_str)
574            .collect();
575        if !members.contains(&target) {
576            continue;
577        }
578        for member in members {
579            if let Some((name, definition)) = project.targets.get_key_value(member)
580                && let Some(non_atomized) = non_atomized(definition)
581            {
582                return (name, Some(non_atomized));
583            }
584        }
585    }
586    (target, None)
587}
588
589/// The variable naming the tasks a task runs inside, one invocation a line.
590pub const INVOCATIONS: &str = "QK_TASK_INVOCATIONS";
591
592/// A task as an invocation: its id and arguments, which a task running inside
593/// it repeats only by recursing, as Nx's task invocation tracker tells it.
594pub fn invocation(task: &Task) -> String {
595    let mut text = task.id.clone();
596    for arg in &task.args {
597        text.push('\u{1f}');
598        text.push_str(arg);
599    }
600    text.replace('\n', " ")
601}
602
603/// The tasks this process runs inside, from [`INVOCATIONS`].
604pub fn enclosing_invocations() -> Vec<String> {
605    std::env::var(INVOCATIONS)
606        .map(|chain| chain.lines().map(str::to_owned).collect())
607        .unwrap_or_default()
608}
609
610/// The root dotenv files Nx loads into its own process at startup, in the
611/// order they take precedence.
612pub const ROOT_DOTENV_FILES: [&str; 3] = [".local.env", ".env.local", ".env"];
613
614/// A task's environment as Nx builds it: the process environment, without
615/// what the root dotenv files set in it at startup, then the task's dotenv
616/// files, loaded and expanded together, then the variables Nx sets for
617/// every task. A target's `env` applies on top.
618fn task_environment(
619    workspace: &Workspace,
620    task: &Task,
621    base_env: &BTreeMap<OsString, OsString>,
622) -> Result<(BTreeMap<OsString, OsString>, BTreeMap<OsString, OsString>)> {
623    let mut env = base_env.clone();
624    let project = &workspace.projects[&task.project];
625    if loads_dotenv(base_env) {
626        // As Nx's unloadDotEnvFiles: a variable whose value is a root file's
627        // goes, so the task's own files decide it. Nx unloads them even when
628        // it did not load them; qk keeps what the shell set then.
629        for file in [".env", ".local.env", ".env.local"] {
630            for (name, value) in dotenv::read_alone(&workspace.root.join(file))? {
631                if env.get(&name) == Some(&value) {
632                    env.remove(&name);
633                }
634            }
635        }
636        let (target, non_atomized) = owner_target(project, &task.target);
637        let files: Vec<PathBuf> = dotenv_files(
638            &project.root,
639            target,
640            task.configuration.as_deref(),
641            non_atomized,
642        )
643        .into_iter()
644        .map(|file| workspace.root.join(file))
645        .collect();
646        dotenv::load(&files, &mut env)?;
647    }
648    let runtime_env = env.clone();
649    // Nx's own variables from an enclosing run, which describe that run.
650    for name in [
651        "NX_SET_CLI",
652        "NX_ORIGINAL_FORCE_COLOR",
653        "NX_TERMINAL_OUTPUT_PATH",
654        "NX_STREAM_OUTPUT",
655        "NX_PREFIX_OUTPUT",
656        // A task of an enclosing run's signal socket and reported address:
657        // a task here neither signals for that task nor reads its address.
658        ready_signal::SOCKET_ENV,
659        ready_signal::TASK_ENV,
660        ready_signal::URL_ENV,
661    ] {
662        env.remove(std::ffi::OsStr::new(name));
663    }
664    let mut set = |name: &str, value: OsString| {
665        env.insert(name.into(), value);
666    };
667    set("NX_WORKSPACE_ROOT", workspace.root.clone().into_os_string());
668    set("NX_TASK_TARGET_PROJECT", task.project.clone().into());
669    set("NX_TASK_TARGET_TARGET", task.target.clone().into());
670    set("LERNA_PACKAGE_NAME", task.project.clone().into());
671    set("NX_TUI", "false".into());
672    // The qk and Nx processes this task runs inside, outermost first.
673    let ancestors = match base_env.get(std::ffi::OsStr::new("NX_INVOCATION_ANCESTOR_PIDS")) {
674        Some(inherited) if !inherited.is_empty() => {
675            format!("{},{}", inherited.to_string_lossy(), std::process::id())
676        }
677        _ => std::process::id().to_string(),
678    };
679    set("NX_INVOCATION_ANCESTOR_PIDS", ancestors.into());
680    // The tasks this one runs inside, outermost first, so a run it starts can
681    // tell when it would run one of them again.
682    let mut chain = base_env
683        .get(std::ffi::OsStr::new(INVOCATIONS))
684        .map(|chain| chain.to_string_lossy().into_owned())
685        .unwrap_or_default();
686    if !chain.is_empty() {
687        chain.push('\n');
688    }
689    chain.push_str(&invocation(task));
690    set(INVOCATIONS, chain.into());
691    if task.target == "test" {
692        set("NX_TERMINAL_CAPTURE_STDERR", "true".into());
693    }
694    match &task.configuration {
695        Some(configuration) => set("NX_TASK_TARGET_CONFIGURATION", configuration.clone().into()),
696        None => {
697            env.remove(std::ffi::OsStr::new("NX_TASK_TARGET_CONFIGURATION"));
698        }
699    }
700    Ok((env, runtime_env))
701}
702
703/// Whether dotenv files load: as in Nx, `NX_LOAD_DOT_ENV_FILES=false` turns
704/// them all off.
705fn loads_dotenv(env: &BTreeMap<OsString, OsString>) -> bool {
706    env.get(std::ffi::OsStr::new("NX_LOAD_DOT_ENV_FILES"))
707        .is_none_or(|value| value != "false")
708}
709
710/// The process environment with the root dotenv files loaded into it, as
711/// Nx loads them into its own process at startup, unless
712/// `NX_LOAD_DOT_ENV_FILES=false`. Variables already set win.
713pub fn environment(workspace: &Path) -> Result<BTreeMap<OsString, OsString>> {
714    let mut values: BTreeMap<OsString, OsString> = std::env::vars_os().collect();
715    if loads_dotenv(&values) {
716        let files: Vec<PathBuf> = ROOT_DOTENV_FILES
717            .iter()
718            .map(|file| workspace.join(file))
719            .collect();
720        dotenv::load(&files, &mut values)?;
721    }
722    Ok(values)
723}
724
725pub fn prepare(
726    workspace: &Workspace,
727    task: &Task,
728    base_env: &BTreeMap<OsString, OsString>,
729) -> Result<PreparedTask> {
730    let definition = &task.definition;
731    let executor = definition
732        .executor
733        .as_deref()
734        .context("target has no executor or command")?;
735    let project = &workspace.projects[&task.project];
736    let run_commands = executor == "nx:run-commands";
737    if !matches!(executor, "nx:run-commands" | "nx:run-script" | "nx:noop") {
738        bail!("unsupported executor {executor:?}");
739    }
740    // As in Nx, run-script reads only `script`, and noop nothing.
741    let options = if run_commands {
742        run_commands_overrides(&definition.options, &task.args, project)?
743    } else {
744        definition.options.clone()
745    };
746    let options = &options;
747    let empty = Map::new();
748    let mut interpolation = if run_commands {
749        interpolate::Interpolation::new(&task.args, options)?
750    } else {
751        interpolate::Interpolation::new(&[], &empty)?
752    };
753    let (mut env, mut runtime_env) = task_environment(workspace, task, base_env)?;
754    // As in Nx 24, `envFile` sets what the task's environment, dotenv files
755    // included, leaves unset or empty, beneath `env`; and the task's
756    // environment says whether it loads.
757    if let Some(file) = options.get("envFile").filter(|_| run_commands) {
758        let file = file.as_str().context("envFile must be a string")?;
759        let path = workspace.root.join(file);
760        if loads_dotenv(&runtime_env) {
761            if !path.is_file() {
762                bail!("envFile {file} does not exist");
763            }
764            dotenv::load(std::slice::from_ref(&path), &mut runtime_env)?;
765            dotenv::load(std::slice::from_ref(&path), &mut env)?;
766        }
767    }
768    // A target-level `env` is a qk extension, for every executor.
769    let option_env = options.get("env").filter(|_| run_commands);
770    for values in [definition.extra.get("env"), option_env]
771        .into_iter()
772        .flatten()
773    {
774        for (name, value) in values.as_object().context("env must be an object")? {
775            if name.is_empty() || name.contains(['=', '\0']) {
776                bail!("invalid environment variable name");
777            }
778            let value: OsString = value
779                .as_str()
780                .context("environment values must be strings")?
781                .into();
782            let name = environment_key(&env, name.into());
783            runtime_env.insert(name.clone(), value.clone());
784            env.insert(name, value);
785        }
786    }
787    interpolation.set_env(&env);
788    let mut execution = BTreeMap::new();
789    execution.insert(
790        "FORCE_COLOR".into(),
791        env.get(std::ffi::OsStr::new("FORCE_COLOR"))
792            .cloned()
793            .unwrap_or_else(|| "true".into()),
794    );
795    if run_commands && boolean(options.get("color"), false, "color")? {
796        execution.insert("FORCE_COLOR".into(), "true".into());
797    }
798    // run-commands runs where `cwd` says, the workspace root by default, and
799    // run-script in the project root.
800    let cwd = match options.get("cwd").filter(|_| run_commands) {
801        Some(cwd) => cwd.as_str().context("cwd must be a string")?,
802        None if run_commands => ".",
803        None => &project.root,
804    };
805    let cwd = workspace.root.join(cwd);
806    let mut resolved = PathBuf::new();
807    for part in cwd.components() {
808        match part {
809            std::path::Component::ParentDir => {
810                resolved.pop();
811            }
812            std::path::Component::CurDir => {}
813            _ => resolved.push(part.as_os_str()),
814        }
815    }
816    // Expose local binaries even for plain run-commands targets.
817    let mut paths = Vec::new();
818    for directory in resolved.ancestors() {
819        paths.push(directory.join("node_modules/.bin"));
820    }
821    let node_path = NodePath::new(&workspace.root, base_env, paths.len());
822    let path_key = path_key(&env);
823    if let Some(path) = env.get(&path_key) {
824        paths.extend(std::env::split_paths(path));
825    }
826    let path = std::env::join_paths(paths).context("cannot construct task PATH")?;
827    env.insert(path_key.clone(), path.clone());
828    runtime_env.insert(path_key, path);
829    let ready_when: Vec<String> = match options.get("readyWhen").filter(|_| run_commands) {
830        None | Some(Value::Null) => Vec::new(),
831        Some(Value::String(text)) => vec![text.clone()],
832        Some(value) => serde_json::from_value(value.clone())
833            .context("readyWhen must be a string or an array of strings")?,
834    };
835    // As in Nx, a single `command` runs in parallel exactly when it has
836    // `readyWhen`, whatever `parallel` says.
837    let parallel = if run_commands && options.get("command").is_some_and(merge_truthy) {
838        !ready_when.is_empty()
839    } else if run_commands {
840        boolean(options.get("parallel"), true, "parallel")?
841    } else {
842        true
843    };
844    let (mut pseudo_terminal, tty) = if run_commands {
845        (
846            boolean(options.get("usePty"), true, "usePty")?
847                && base_env
848                    .get(std::ffi::OsStr::new("NX_NATIVE_COMMAND_RUNNER"))
849                    .is_none_or(|value| value != "false"),
850            boolean(options.get("tty"), true, "tty")?,
851        )
852    } else {
853        (true, true)
854    };
855    let mut decorations = Vec::new();
856    if !ready_when.is_empty() && !parallel {
857        bail!("readyWhen can only be used when parallel is true");
858    }
859    let mut commands = Vec::new();
860    match executor {
861        "nx:noop" => {}
862        "nx:run-script" => {
863            let script = options
864                .get("script")
865                .and_then(Value::as_str)
866                .context("run-script requires options.script")?;
867            let package = workspace
868                .packages
869                .get(&task.project)
870                .context("run-script requires a package.json")?;
871            if !package.scripts.contains_key(script) {
872                bail!("package.json has no script {script:?}");
873            }
874            let manager = package_manager(workspace)?;
875            // Nx joins the arguments as they are; qk quotes each, so that
876            // one with a space or a shell character stays one argument.
877            let args = interpolate::quoted_arguments(&task.args)?;
878            let script = interpolate::quote(script)?;
879            // Nx's `run` for each: npm and bun need `--` before arguments,
880            // and yarn runs a script by name.
881            let mut command = match manager {
882                "yarn" => format!("yarn {script}"),
883                manager => format!("{manager} run {script}"),
884            };
885            if !args.is_empty() {
886                if matches!(manager, "npm" | "bun") {
887                    command.push_str(" --");
888                }
889                command.push(' ');
890                command.push_str(&args);
891            }
892            commands.push(command);
893        }
894        "nx:run-commands" => {
895            let forward = boolean(options.get("forwardAllArgs"), true, "forwardAllArgs")?;
896            // As in Nx, `command` wins over `commands`.
897            if let Some(command) = options
898                .get("command")
899                .filter(|command| merge_truthy(command))
900            {
901                // Nx also takes an array, joined with spaces.
902                let command = match command {
903                    Value::String(command) => command.clone(),
904                    Value::Array(words) => words
905                        .iter()
906                        .map(|word| word.as_str().context("command words must be strings"))
907                        .collect::<Result<Vec<_>>>()?
908                        .join(" "),
909                    _ => bail!("command must be a string or an array of strings"),
910                };
911                commands.push(interpolation.command(&command, forward)?);
912            } else if let Some(values) = options.get("commands") {
913                for value in values.as_array().context("commands must be an array")? {
914                    let (command, forward) = if let Some(command) = value.as_str() {
915                        (command, forward)
916                    } else {
917                        let value = value
918                            .as_object()
919                            .context("commands entries must be strings or objects")?;
920                        for key in value.keys() {
921                            if !matches!(
922                                key.as_str(),
923                                "command"
924                                    | "forwardAllArgs"
925                                    | "prefix"
926                                    | "prefixColor"
927                                    | "color"
928                                    | "bgColor"
929                                    | "description"
930                            ) {
931                                bail!("unsupported command entry field {key:?}");
932                            }
933                        }
934                        let field =
935                            |name: &str, background: Option<bool>| -> Result<Option<String>> {
936                                let Some(value) = value.get(name) else {
937                                    return Ok(None);
938                                };
939                                let text = value.as_str().with_context(|| {
940                                    format!("command entry {name} must be a string")
941                                })?;
942                                if let Some(background) = background
943                                    && !Decoration::valid(text, background)
944                                {
945                                    bail!("command entry {name} {text:?} is not a colour");
946                                }
947                                Ok(Some(text.to_owned()))
948                            };
949                        let decoration = Decoration {
950                            prefix: field("prefix", None)?,
951                            prefix_color: field("prefixColor", Some(false))?,
952                            color: field("color", Some(false))?,
953                            bg_color: field("bgColor", Some(true))?,
954                        };
955                        if !decoration.is_empty() && !parallel {
956                            bail!(
957                                "prefix, prefixColor, color and bgColor can only be set when parallel is true"
958                            );
959                        }
960                        decorations.resize(commands.len(), Decoration::default());
961                        decorations.push(decoration);
962                        (
963                            value
964                                .get("command")
965                                .and_then(Value::as_str)
966                                .context("command entry requires a command string")?,
967                            boolean(value.get("forwardAllArgs"), forward, "forwardAllArgs")?,
968                        )
969                    };
970                    commands.push(interpolation.command(command, forward)?);
971                }
972            } else {
973                bail!("run-commands requires command or commands");
974            }
975            // An empty `commands` succeeds without running anything, as in Nx.
976            if commands.iter().any(|command| command.trim().is_empty()) {
977                bail!("run-commands requires nonempty commands");
978            }
979        }
980        _ => bail!("unsupported executor {executor:?}"),
981    }
982    // As in Nx, commands run side by side share qk's output through pipes.
983    pseudo_terminal &= commands.len() == 1 || !parallel;
984    let ready_inputs = ready_inputs(workspace, task, options)?.map(std::sync::Arc::new);
985    let mut prepared = PreparedTask {
986        id: task.id.clone(),
987        commands,
988        parallel,
989        cwd,
990        env,
991        runtime_env,
992        node_path: Some(node_path),
993        execution,
994        ready_when,
995        ready: Default::default(),
996        ready_check: None,
997        ready_inputs,
998        verdict: Default::default(),
999        processes: Default::default(),
1000        decorations,
1001        interactive: false,
1002        pseudo_terminal,
1003        tty,
1004        sandbox: None,
1005        recording: None,
1006        display: Display::default(),
1007    };
1008    prepared.ready_check = prepared.resolve_ready_check(None);
1009    Ok(prepared)
1010}
1011
1012/// A continuous target's `readyWhen` and what its placeholders read but the
1013/// environment: the options the task runs with, its arguments applied.
1014#[derive(Debug)]
1015pub struct ReadyInputs {
1016    config: Value,
1017    workspace_root: String,
1018    project_root: String,
1019    project_name: String,
1020    options: Map<String, Value>,
1021    /// `options` as a command check reads them, in `NX_TASK_OPTIONS`.
1022    options_json: String,
1023}
1024
1025/// A continuous target's `readyWhen`, as Nx 24 reads it. `null` turns off one
1026/// a target default sets. A target that is not continuous has none.
1027fn ready_inputs(
1028    workspace: &Workspace,
1029    task: &Task,
1030    options: &Map<String, Value>,
1031) -> Result<Option<ReadyInputs>> {
1032    let Some(ready_when) = task
1033        .definition
1034        .extra
1035        .get("readyWhen")
1036        .filter(|value| !value.is_null() && task.definition.continuous == Some(true))
1037    else {
1038        return Ok(None);
1039    };
1040    let mut options = options.clone();
1041    let project = &workspace.projects[&task.project];
1042    for (key, value) in interpolate::yargs(&task.args, false, false) {
1043        if key == "_" {
1044            continue;
1045        }
1046        // As in Nx, an argument's tokens resolve for the task's project.
1047        let value = match value {
1048            Value::String(text) => Value::String(qk_config::interpolate_override(&text, project)?),
1049            value => value,
1050        };
1051        if key.contains('-') {
1052            options.insert(interpolate::camel_case(&key), value.clone());
1053        }
1054        options.insert(key, value);
1055    }
1056    Ok(Some(ReadyInputs {
1057        config: ready_when.clone(),
1058        workspace_root: workspace
1059            .root
1060            .to_str()
1061            .context("workspace path must be UTF-8")?
1062            .to_owned(),
1063        project_root: project.root.clone(),
1064        project_name: task.project.clone(),
1065        options_json: serde_json::to_string(&options)?,
1066        options,
1067    }))
1068}
1069
1070impl PreparedTask {
1071    /// The task's own `readyWhen`, resolved against its options and the
1072    /// environment it runs with, with `url` as `NX_READY_URL`. As in Nx
1073    /// 24.0.1, a task waiting for a server that reports its address resolves
1074    /// it once that server is ready, so its placeholders and a command check
1075    /// read the address.
1076    pub fn resolve_ready_check(
1077        &self,
1078        url: Option<&str>,
1079    ) -> Option<std::result::Result<readiness::ReadyCheck, String>> {
1080        let inputs = self.ready_inputs.as_deref()?;
1081        let mut full_env = self.env.clone();
1082        if let Some(url) = url {
1083            full_env.insert(ready_signal::URL_ENV.into(), url.into());
1084        }
1085        let env: BTreeMap<String, String> = full_env
1086            .iter()
1087            .filter_map(|(name, value)| {
1088                Some((name.to_str()?.to_owned(), value.to_str()?.to_owned()))
1089            })
1090            .collect();
1091        let scope = readiness::Scope {
1092            workspace_root: &inputs.workspace_root,
1093            project_root: &inputs.project_root,
1094            project_name: &inputs.project_name,
1095            options: &inputs.options,
1096            env: &env,
1097        };
1098        let mut check = readiness::resolve(&self.id, &inputs.config, &scope);
1099        // As in Nx 24, a command check runs as the task's commands do, and
1100        // reads the options they run with.
1101        if let Ok(Some(readiness::ReadyCheck {
1102            probe: readiness::Probe::Command { env: probe_env, .. },
1103            ..
1104        })) = &mut check
1105        {
1106            *probe_env = full_env;
1107            probe_env.insert("NX_TASK_OPTIONS".into(), inputs.options_json.clone().into());
1108        }
1109        check.map_err(|error| format!("{error:#}")).transpose()
1110    }
1111}
1112
1113/// The run-commands options Nx reads, which a task's arguments may set too.
1114const OPTION_FLAGS: &[&str] = &[
1115    "command",
1116    "commands",
1117    "color",
1118    "parallel",
1119    "readyWhen",
1120    "cwd",
1121    "args",
1122    "envFile",
1123    "__unparsed__",
1124    "env",
1125    "usePty",
1126    "streamOutput",
1127    "verbose",
1128    "forwardAllArgs",
1129    "tty",
1130];
1131
1132/// The target's options with the task's arguments that name a run-commands
1133/// option applied. As in Nx, `--cwd=dir`, `--no-parallel` or
1134/// `--env.NAME=value` set the option rather than reaching the command.
1135fn run_commands_overrides(
1136    options: &serde_json::Map<String, Value>,
1137    args: &[String],
1138    project: &qk_config::Project,
1139) -> Result<serde_json::Map<String, Value>> {
1140    const BOOLEAN: &[&str] = &[
1141        "color",
1142        "parallel",
1143        "usePty",
1144        "streamOutput",
1145        "verbose",
1146        "forwardAllArgs",
1147        "tty",
1148    ];
1149    let mut options = options.clone();
1150    let mut ready = Vec::new();
1151    let mut args = args.iter().peekable();
1152    while let Some(arg) = args.next() {
1153        let Some(flag) = arg.strip_prefix("--") else {
1154            continue;
1155        };
1156        let (key, value) = match flag.split_once('=') {
1157            Some((key, value)) => (key, Some(value.to_owned())),
1158            None => (flag, None),
1159        };
1160        let (key, negated) = match key.strip_prefix("no-") {
1161            Some(key) if OPTION_FLAGS.contains(&key) => (key, true),
1162            _ => (key, false),
1163        };
1164        let (base, field) = match key.split_once('.') {
1165            Some((base, field)) => (base, Some(field)),
1166            None => (key, None),
1167        };
1168        if !OPTION_FLAGS.contains(&base) {
1169            continue;
1170        }
1171        let boolean = BOOLEAN.contains(&base);
1172        let value = match value {
1173            Some(value) => value,
1174            None if negated => "false".into(),
1175            None if !boolean && args.peek().is_some_and(|next| !next.starts_with('-')) => {
1176                args.next().unwrap().clone()
1177            }
1178            None => "true".into(),
1179        };
1180        let value = if boolean {
1181            Value::Bool(value != "false")
1182        } else {
1183            // As in Nx, an argument's tokens resolve for the task's project.
1184            Value::String(qk_config::interpolate_override(&value, project)?)
1185        };
1186        match (base, field) {
1187            ("env", Some(name)) => {
1188                let env = options
1189                    .entry("env")
1190                    .or_insert_with(|| Value::Object(Default::default()));
1191                if let Value::Object(env) = env {
1192                    env.insert(name.to_owned(), value);
1193                }
1194            }
1195            ("readyWhen", None) => ready.push(value),
1196            // Nx sets these itself, and a list cannot come from a flag.
1197            ("__unparsed__" | "commands", _) | (_, Some(_)) => {}
1198            (base, None) => {
1199                options.insert(base.to_owned(), value);
1200            }
1201        }
1202    }
1203    if !ready.is_empty() {
1204        let ready = if ready.len() == 1 {
1205            ready.pop().unwrap()
1206        } else {
1207            Value::Array(ready)
1208        };
1209        options.insert("readyWhen".into(), ready);
1210    }
1211    Ok(options)
1212}
1213
1214/// JavaScript truthiness, which decides what Nx reads as set.
1215fn merge_truthy(value: &Value) -> bool {
1216    match value {
1217        Value::Null => false,
1218        Value::Bool(flag) => *flag,
1219        Value::Number(number) => number.as_f64().is_some_and(|number| number != 0.0),
1220        Value::String(text) => !text.is_empty(),
1221        Value::Array(_) | Value::Object(_) => true,
1222    }
1223}
1224
1225fn boolean(value: Option<&Value>, default: bool, name: &str) -> Result<bool> {
1226    value
1227        .map(|value| {
1228            value
1229                .as_bool()
1230                .with_context(|| format!("{name} must be boolean"))
1231        })
1232        .transpose()
1233        .map(|value| value.unwrap_or(default))
1234}
1235
1236fn package_manager(workspace: &Workspace) -> Result<&'static str> {
1237    workspace.package_manager_name()
1238}
1239
1240#[cfg(all(test, windows))]
1241mod dotenv_tests {
1242    #[test]
1243    fn colon_targets_keep_configuration_and_generic_dotenv_files() {
1244        let files = super::dotenv_files("app", "test:unit:watch", Some("ci"), None);
1245        assert!(files.iter().all(|file| !file.contains(':')));
1246        assert!(files.contains(&"app/.env.ci".to_owned()));
1247        assert!(files.contains(&"app/.env".to_owned()));
1248        assert!(files.contains(&".env.ci".to_owned()));
1249        assert!(files.contains(&".env".to_owned()));
1250    }
1251}