Skip to main content

kizz_core/
run.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! Running one task by its name, for `kizz run` ("Running one task with
6//! `kizz run`").
7//!
8//! [`select_by_name`] finds the task named by `kizz run <name>` among the tasks
9//! discovered under the current directory: the task whose `kizz.md` is the fewest
10//! directory levels below the current directory wins ([`task_level`]), two tasks of
11//! that name at the same level are an error that lists each with its path, and a
12//! name that no task has is an error that lists the task names under the current
13//! directory. A task's level is counted along the path that discovery reports its
14//! `kizz.md` under, the first path of a file reached through several.
15//!
16//! [`run`] runs the selected task once, with its arguments in `task.args` and an
17//! empty `task.selected` ([`TaskInfo::for_run`]): no other task runs, and no pass
18//! follows, even when its program changes a file. It uses and updates the cache as
19//! a build does, and stores what a build of that one task in one pass stores. The
20//! engine options say whether every command runs (`--no-cache`, see
21//! [`Engine::with_no_cache`]) and echoes its output live
22//! ([`Engine::with_echo_every_step`]), and the [`StepEvents`] follow each step as it
23//! starts or comes from the cache.
24//!
25//! With [`Engine::with_report`] (`kizz run --output`), the run also keeps what its
26//! observation report needs ([`RunObservations`]): the command of each step that
27//! the run reached, in order, a step that ran with its process tree and a cache hit
28//! as cached, and the task program's own file accesses, its module reads included,
29//! with their outcomes, which the tracer's error-name query names.
30//! [`RunReport::observation_report`] builds the report from them, each command the
31//! root of its own process tree and the task program an entry of its own. Without
32//! the option, nothing more is kept.
33
34use std::{collections::BTreeMap, path::Component};
35
36use kizz_store::{StoreError, Verdict};
37use kizz_trace::Observations;
38use thiserror::Error;
39
40use crate::{
41    build::{TaskResult, UncheckedStep, run_task_once},
42    engine::{Engine, StepEvents},
43    report::{CommandInput, Report, TaskProgramInput},
44    runtime::{PrintSink, TaskInfo},
45    targets::is_valid_target,
46    tasks::{TASK_NAME_RULE, Task},
47};
48
49/// Why `kizz run <name>` selects no task.
50#[derive(Debug, Clone, PartialEq, Eq, Error)]
51pub enum NameError {
52    /// The name is not a valid task name.
53    #[error("invalid task name `{name}`: {}", TASK_NAME_RULE)]
54    Invalid {
55        /// The name as given.
56        name: String,
57    },
58    /// No task under the current directory has the name.
59    #[error("no task named `{name}` under `.`; {}", names_clause(.names))]
60    Unknown {
61        /// The name as given.
62        name: String,
63        /// The task names under the current directory, sorted and without repeats.
64        names: Vec<String>,
65    },
66    /// Several tasks of the name are the fewest directory levels below the current
67    /// directory.
68    #[error(
69        "{} tasks named `{name}` are {} below `.`, so kizz cannot choose one: {}",
70        .tasks.len(),
71        levels(*.level),
72        .tasks.join(", ")
73    )]
74    Tie {
75        /// The name as given.
76        name: String,
77        /// The number of directory levels between the current directory and their
78        /// `kizz.md` files.
79        level: usize,
80        /// Each task, as `path/kizz.md:LINE (Heading)`, in the default order.
81        tasks: Vec<String>,
82    },
83}
84
85/// `level` directory levels, as messages say it.
86fn levels(level: usize) -> String {
87    if level == 1 {
88        "1 directory level".to_owned()
89    } else {
90        format!("{level} directory levels")
91    }
92}
93
94/// The clause of [`NameError::Unknown`] that lists the task names `names`.
95fn names_clause(names: &[String]) -> String {
96    if names.is_empty() {
97        "there is no named task under `.`".to_owned()
98    } else {
99        format!("the task names under `.` are: {}", names.join(", "))
100    }
101}
102
103/// The number of directory levels between the directory discovery started in and
104/// the `kizz.md` of `task`: 0 for a `kizz.md` in that directory, 1 for one in a
105/// subdirectory, and so on, counted along the path that discovery reports it under.
106#[must_use]
107pub fn task_level(task: &Task) -> usize {
108    task.relative_file.parent().map_or(0, |dir| {
109        dir.components()
110            .filter(|component| matches!(component, Component::Normal(_)))
111            .count()
112    })
113}
114
115/// The task of `tasks`, the tasks discovered under one directory in the default
116/// order, that `kizz run <name>` runs: the task named `name` whose `kizz.md` is the
117/// fewest directory levels below that directory.
118///
119/// # Errors
120///
121/// A [`NameError`] when `name` is not a valid task name, when no task has it, or
122/// when several tasks have it at the fewest levels.
123pub fn select_by_name<'t>(
124    tasks: &'t [Task],
125    name: &str,
126) -> Result<&'t Task, NameError> {
127    if !is_valid_target(name) {
128        return Err(NameError::Invalid {
129            name: name.to_owned(),
130        });
131    }
132    let matching: Vec<&Task> = tasks
133        .iter()
134        .filter(|task| task.options.name.as_deref() == Some(name))
135        .collect();
136    let Some(level) = matching.iter().map(|task| task_level(task)).min() else {
137        let mut names: Vec<String> = tasks
138            .iter()
139            .filter_map(|task| task.options.name.clone())
140            .collect();
141        names.sort();
142        names.dedup();
143        return Err(NameError::Unknown {
144            name: name.to_owned(),
145            names,
146        });
147    };
148    let nearest: Vec<&Task> = matching
149        .into_iter()
150        .filter(|task| task_level(task) == level)
151        .collect();
152    match nearest.as_slice() {
153        [task] => Ok(*task),
154        _ => {
155            Err(NameError::Tie {
156                name: name.to_owned(),
157                level,
158                tasks: nearest.iter().map(|task| task.location()).collect(),
159            })
160        },
161    }
162}
163
164/// What one `kizz run` observed for its observation report, which it keeps only
165/// when the engine writes one ([`Engine::with_report`]).
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct RunObservations {
168    /// The command of each step that the run reached, in order: a step that ran,
169    /// or whose program kizz did not find, with its outcome, its process tree and
170    /// the lookup's observations, and a cache hit as cached.
171    pub commands: Vec<CommandInput>,
172    /// The task program's own file accesses, its module reads and its `fs` and
173    /// `env.load_file` accesses, each with its outcomes.
174    pub task_program: Observations,
175}
176
177/// What one `kizz run` did.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct RunReport {
180    /// The one run of the task.
181    pub result: TaskResult,
182    /// Whether cancellation was requested, so the run started nothing new.
183    pub interrupted: bool,
184    /// What the run observed for its observation report, when the engine writes
185    /// one, and otherwise `None`.
186    pub observed: Option<RunObservations>,
187}
188
189impl RunReport {
190    /// Whether the run succeeded: it was not interrupted, and the task did not
191    /// fail.
192    #[must_use]
193    pub const fn succeeded(&self) -> bool {
194        !self.interrupted && self.result.result.is_ok()
195    }
196
197    /// The steps that the run left unchecked, which warn once the run ends; none
198    /// when it was interrupted, as for a build.
199    #[must_use]
200    pub fn unchecked(&self) -> Vec<UncheckedStep> {
201        if self.interrupted {
202            Vec::new()
203        } else {
204            self.result.unchecked.clone()
205        }
206    }
207
208    /// The number of commands that ran, and the number that came from the cache.
209    #[must_use]
210    pub fn command_counts(&self) -> (usize, usize) {
211        let ran = self
212            .result
213            .decisions
214            .iter()
215            .filter(|decision| matches!(decision.verdict, Verdict::Ran(_)))
216            .count();
217        (ran, self.result.decisions.len().saturating_sub(ran))
218    }
219
220    /// The observation report of the run, whose task program is named `task`, as
221    /// output names the task, such as `kizz.md:3 (Build)`: one command for each
222    /// step that the run reached, in order, each that ran the root of its own
223    /// process tree and each cache hit cached, without observations, and the task
224    /// program's own accesses as an entry of their own. `None` when the engine
225    /// wrote no report.
226    #[must_use]
227    pub fn observation_report(
228        &self,
229        task: &str,
230    ) -> Option<Report> {
231        self.observed.as_ref().map(|observed| {
232            Report::new(
233                observed.commands.clone(),
234                Some(TaskProgramInput {
235                    task: task.to_owned(),
236                    observations: observed.task_program.clone(),
237                }),
238            )
239        })
240    }
241}
242
243/// Run `task`, made with [`TaskInfo::for_run`], once with `engine`, as `kizz run`
244/// does; `caller` is the caller environment, the lines its program prints go to
245/// `print`, and `events` follows each step as it starts or comes from the cache.
246///
247/// # Errors
248///
249/// A [`StoreError`] when a record cannot be read or written.
250pub fn run(
251    engine: &Engine<'_>,
252    task: &TaskInfo,
253    caller: &BTreeMap<String, String>,
254    print: &dyn PrintSink,
255    events: &dyn StepEvents,
256) -> Result<RunReport, StoreError> {
257    let (result, observed) = run_task_once(engine, task, caller, print, events)?;
258    Ok(RunReport {
259        result,
260        interrupted: engine.is_cancelled(),
261        observed,
262    })
263}
264
265/// Unit tests for the levels of tasks and the messages of selection.
266#[cfg(test)]
267#[allow(
268    clippy::disallowed_macros,
269    clippy::disallowed_methods,
270    reason = "test code: the tests assert and lock"
271)]
272mod tests {
273    use std::path::PathBuf;
274
275    use kizz_store::TaskId;
276
277    use super::{NameError, select_by_name, task_level};
278    use crate::tasks::{Task, TaskOptions};
279
280    /// A task named `name` in the `kizz.md` at `relative`, the `index`th of the
281    /// project.
282    fn task(
283        relative: &str,
284        index: u32,
285        name: Option<&str>,
286    ) -> Task {
287        Task {
288            id: TaskId {
289                file: PathBuf::from("/work").join(relative),
290                index,
291            },
292            relative_file: PathBuf::from(relative),
293            line: 3,
294            heading: Some("Heading".to_owned()),
295            targets: Vec::new(),
296            options: TaskOptions {
297                name: name.map(str::to_owned),
298                cache_never: false,
299            },
300            source: String::new(),
301        }
302    }
303
304    /// A `kizz.md` in the directory is at level 0, and each directory below adds
305    /// one.
306    #[test]
307    fn levels_count_the_directories_below() {
308        assert_eq!(task_level(&task("kizz.md", 0, None)), 0);
309        assert_eq!(task_level(&task("a/kizz.md", 0, None)), 1);
310        assert_eq!(task_level(&task("a/b/c/kizz.md", 0, None)), 3);
311    }
312
313    /// The nearest task wins, a tie names both tasks with their paths, and an
314    /// unknown or invalid name says so.
315    #[test]
316    fn the_nearest_task_wins_and_ties_and_unknown_names_fail() {
317        let tasks = [
318            task("kizz.md", 0, Some("other")),
319            task("a/kizz.md", 0, Some("lint")),
320            task("b/kizz.md", 0, Some("lint")),
321            task("c/d/kizz.md", 0, Some("deep")),
322            task("e/kizz.md", 0, Some("deep")),
323        ];
324        let deep = select_by_name(&tasks, "deep").unwrap();
325        assert_eq!(deep.relative_file, PathBuf::from("e/kizz.md"));
326        let tie = select_by_name(&tasks, "lint").unwrap_err();
327        assert_eq!(tie, NameError::Tie {
328            name: "lint".to_owned(),
329            level: 1,
330            tasks: vec![
331                "a/kizz.md:3 (Heading)".to_owned(),
332                "b/kizz.md:3 (Heading)".to_owned()
333            ],
334        });
335        assert_eq!(
336            tie.to_string(),
337            "2 tasks named `lint` are 1 directory level below `.`, so kizz cannot choose one: \
338             a/kizz.md:3 (Heading), b/kizz.md:3 (Heading)"
339        );
340        let unknown = select_by_name(&tasks, "build").unwrap_err();
341        assert_eq!(
342            unknown.to_string(),
343            "no task named `build` under `.`; the task names under `.` are: deep, lint, other"
344        );
345        let none = select_by_name(&[task("kizz.md", 0, None)], "build").unwrap_err();
346        assert_eq!(
347            none.to_string(),
348            "no task named `build` under `.`; there is no named task under `.`"
349        );
350        let invalid = select_by_name(&tasks, "a b").unwrap_err();
351        assert_eq!(
352            invalid.to_string(),
353            "invalid task name `a b`: task names use only letters, digits, `_`, `.` and `-`"
354        );
355    }
356}