Skip to main content

kizz_core/
render.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! How explanations read: the one-line reason that `kizz build` prints for each
6//! command it runs, the full reasons of `--explain` and `kizz why`, and the loud
7//! warning for a step that re-runs in consecutive builds for the same
8//! self-inflicted reason.
9//!
10//! Output is plain text; the command line adds styling. Paths under the base
11//! directory are shown relative to it, paths under the home directory start with
12//! `~/`, and other paths are absolute. Environment values, which can be secrets,
13//! are shown only when the output is verbose, and so is `stdin` text.
14
15use std::path::{Path, PathBuf};
16
17use kizz_store::{
18    AccessBits, Capture, ChangedInput, EnvChange, Explanation, ModuleChange, ModuleChangeKind,
19    NotCachedReason, Reason, SelfInflicted, TaskLabel, Verdict, Writer, changed_reads_text,
20    machine_changes_text,
21};
22
23use crate::{explain::RepeatedWarning, warning::location};
24
25/// The one-line reason of a step that was cached.
26pub const CACHED: &str = "cached: no recorded input changed";
27
28/// How explanations are rendered.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Render {
31    /// Paths under this directory are shown relative to it.
32    pub base: PathBuf,
33    /// Paths under this directory, the caller's home directory, start with `~/`.
34    pub home: Option<PathBuf>,
35    /// Whether environment values and `stdin` text are shown.
36    pub verbose: bool,
37}
38
39/// `text` in backticks.
40fn quoted(text: &str) -> String {
41    format!("`{text}`")
42}
43
44/// A list of patterns, each in backticks, or `none`.
45fn patterns(list: &[String]) -> String {
46    if list.is_empty() {
47        "none".to_owned()
48    } else {
49        list.iter()
50            .map(|pattern| quoted(pattern))
51            .collect::<Vec<_>>()
52            .join(", ")
53    }
54}
55
56/// A capture mode as output names it.
57const fn capture(mode: Capture) -> &'static str {
58    match mode {
59        Capture::Split => "split",
60        Capture::Merged => "merged",
61    }
62}
63
64/// A boolean as a task program writes it: `True` or `False`.
65const fn starlark_bool(value: bool) -> &'static str {
66    if value { "True" } else { "False" }
67}
68
69/// `stdin` text as verbose output shows it, or `/dev/null` for none.
70fn stdin_text(text: Option<&str>) -> String {
71    text.map_or_else(|| "/dev/null".to_owned(), |text| format!("{text:?}"))
72}
73
74/// `number` followed by `singular`, made plural with `s` unless `number` is 1.
75fn count(
76    number: usize,
77    singular: &str,
78) -> String {
79    if number == 1 {
80        format!("1 {singular}")
81    } else {
82        format!("{number} {singular}s")
83    }
84}
85
86/// The access kinds `bits` as output names them, such as `read, probe`.
87#[must_use]
88pub fn access_kinds(bits: AccessBits) -> String {
89    [
90        (AccessBits::READ, "read"),
91        (AccessBits::PROBE, "probe"),
92        (AccessBits::LIST, "list"),
93        (AccessBits::WRITE, "write"),
94        (AccessBits::EXEC, "exec"),
95        (AccessBits::XATTR, "xattr"),
96    ]
97    .into_iter()
98    .filter(|(bit, _)| bits.contains(*bit))
99    .map(|(_, name)| name)
100    .collect::<Vec<_>>()
101    .join(", ")
102}
103
104impl Render {
105    /// A path as output shows it.
106    #[must_use]
107    pub fn path(
108        &self,
109        path: &Path,
110    ) -> String {
111        if let Ok(relative) = path.strip_prefix(&self.base) {
112            return if relative.as_os_str().is_empty() {
113                ".".to_owned()
114            } else {
115                relative.display().to_string()
116            };
117        }
118        if let Some(rest) = self
119            .home
120            .as_ref()
121            .and_then(|home| path.strip_prefix(home).ok())
122        {
123            return format!("~/{}", rest.display());
124        }
125        path.display().to_string()
126    }
127
128    /// A path in backticks.
129    fn quoted_path(
130        &self,
131        path: &Path,
132    ) -> String {
133        quoted(&self.path(path))
134    }
135
136    /// Why a run could not be cached, with the files that changed after the command
137    /// read them shown as other paths are, each with who changed it.
138    #[must_use]
139    pub fn not_cached(
140        &self,
141        why: &NotCachedReason,
142    ) -> String {
143        if let NotCachedReason::ChangedAfterRead { files } = why {
144            changed_reads_text(files, |path| self.quoted_path(path))
145        } else {
146            why.to_string()
147        }
148    }
149
150    /// A task as output names it: `path/kizz.md:LINE (Heading)`, or the path alone
151    /// when the line is unknown.
152    #[must_use]
153    pub fn task(
154        &self,
155        label: &TaskLabel,
156    ) -> String {
157        let file = PathBuf::from(self.path(&label.task.file));
158        if label.line == 0 {
159            return file.display().to_string();
160        }
161        location(
162            &file,
163            usize::try_from(label.line).unwrap_or(usize::MAX),
164            label.heading.as_deref(),
165        )
166    }
167
168    /// A step of a task, such as `step 2 of kizz.md:3 (Build)`.
169    fn step_of(
170        &self,
171        task: &TaskLabel,
172        position: u32,
173    ) -> String {
174        format!("step {} of {}", position.saturating_add(1), self.task(task))
175    }
176
177    /// Who last wrote a changed input.
178    #[must_use]
179    pub fn writer(
180        &self,
181        writer: &Writer,
182    ) -> String {
183        match writer {
184            Writer::ThisCommand => "this command on its previous run".to_owned(),
185            Writer::ThisBuild { task, position } => {
186                format!("{} in this build", self.step_of(task, *position))
187            },
188            Writer::EarlierBuild { task, position } => {
189                format!("{} in an earlier build", self.step_of(task, *position))
190            },
191            Writer::Outside => "something outside kizz".to_owned(),
192            Writer::ProgramThisBuild { task } => {
193                format!("the program of {} in this build", self.task(task))
194            },
195            Writer::ProgramEarlierBuild { task } => {
196                format!("the program of {} in an earlier build", self.task(task))
197            },
198        }
199    }
200
201    /// Why a changed input is self-inflicted.
202    fn self_inflicted(
203        &self,
204        how: &SelfInflicted,
205    ) -> String {
206        match how {
207            SelfInflicted::WritesAndReads => {
208                "this command writes that file and also reads it".to_owned()
209            },
210            SelfInflicted::WrittenEveryBuild { task, position } => {
211                format!(
212                    "{} writes that file on every build",
213                    self.step_of(task, *position)
214                )
215            },
216        }
217    }
218
219    /// The direct explanation of a self-inflicted input, such as "re-ran because
220    /// `out` changed; this command writes that file and also reads it".
221    fn direct(
222        &self,
223        input: &ChangedInput,
224        how: &SelfInflicted,
225    ) -> String {
226        format!(
227            "re-ran because {} changed; {}",
228            self.quoted_path(&input.path),
229            self.self_inflicted(how)
230        )
231    }
232
233    /// One changed input on one line: the path, what changed, and who last wrote
234    /// it.
235    fn input(
236        &self,
237        input: &ChangedInput,
238    ) -> String {
239        format!(
240            "{}: {}; last written by {}",
241            self.quoted_path(&input.path),
242            input.change,
243            self.writer(&input.writer)
244        )
245    }
246
247    /// Changed inputs in short: the first self-inflicted one directly, or else the
248    /// first one, and how many more there are.
249    fn inputs_short(
250        &self,
251        inputs: &[ChangedInput],
252    ) -> String {
253        let first = inputs
254            .iter()
255            .find_map(|input| {
256                input
257                    .self_inflicted
258                    .as_ref()
259                    .map(|how| self.direct(input, how))
260            })
261            .or_else(|| {
262                inputs.first().map(|input| {
263                    format!(
264                        "{} changed ({})",
265                        self.quoted_path(&input.path),
266                        input.change
267                    )
268                })
269            });
270        let Some(first) = first else {
271            return "no input changed".to_owned();
272        };
273        match inputs.len().saturating_sub(1) {
274            0 => first,
275            more => format!("{first}, and {} changed", count(more, "more input")),
276        }
277    }
278
279    /// Changed inputs in full: one line each, and the direct explanation of each
280    /// self-inflicted one.
281    fn inputs_full(
282        &self,
283        inputs: &[ChangedInput],
284    ) -> Vec<String> {
285        let mut lines = Vec::new();
286        for input in inputs {
287            lines.push(format!("  {}", self.input(input)));
288            if let Some(how) = &input.self_inflicted {
289                lines.push(format!("    {}", self.direct(input, how)));
290            }
291        }
292        lines
293    }
294
295    /// A changed program, naming its parts when they are known.
296    fn program(
297        &self,
298        block: bool,
299        modules: &[ModuleChange],
300    ) -> String {
301        let mut parts = Vec::new();
302        if block {
303            parts.push("its block".to_owned());
304        }
305        for module in modules {
306            let path = self.quoted_path(&module.path);
307            parts.push(match module.kind {
308                ModuleChangeKind::Changed => format!("module {path}"),
309                ModuleChangeKind::Added => format!("module {path}, which it now loads"),
310                ModuleChangeKind::Removed => format!("module {path}, which it no longer loads"),
311            });
312        }
313        if parts.is_empty() {
314            "the task program changed".to_owned()
315        } else {
316            format!("the task program changed: {}", parts.join(", "))
317        }
318    }
319
320    /// One changed environment variable, with its values only when verbose.
321    fn env_change(
322        &self,
323        change: &EnvChange,
324    ) -> String {
325        let name = &change.name;
326        match (&change.old, &change.new, self.verbose) {
327            (None, Some(new), true) => format!("added {name}={new}"),
328            (Some(old), None, true) => format!("removed {name}={old}"),
329            (Some(old), Some(new), true) => {
330                format!("changed {name} from {} to {}", quoted(old), quoted(new))
331            },
332            (None, ..) => format!("added {name}"),
333            (Some(_), None, _) => format!("removed {name}"),
334            (Some(_), Some(_), _) => format!("changed {name}"),
335        }
336    }
337
338    /// The arguments, word by word: each word that changed, was added, or was
339    /// removed, counting the program as word 1.
340    fn words(
341        old: &[String],
342        new: &[String],
343    ) -> Vec<String> {
344        let len = old.len().max(new.len());
345        (0..len)
346            .filter_map(|index| {
347                let number = index.saturating_add(1);
348                match (old.get(index), new.get(index)) {
349                    (Some(old), Some(new)) if old == new => None,
350                    (Some(old), Some(new)) => {
351                        Some(format!(
352                            "word {number}: {} became {}",
353                            quoted(old),
354                            quoted(new)
355                        ))
356                    },
357                    (None, Some(new)) => Some(format!("word {number} added: {}", quoted(new))),
358                    (Some(old), None) => Some(format!("word {number} removed: {}", quoted(old))),
359                    (None, None) => None,
360                }
361            })
362            .collect()
363    }
364
365    /// The short form of `stdin` changing.
366    fn stdin(
367        &self,
368        old: Option<&str>,
369        new: Option<&str>,
370    ) -> String {
371        if self.verbose {
372            format!(
373                "`stdin` changed from {} to {}",
374                stdin_text(old),
375                stdin_text(new)
376            )
377        } else {
378            "`stdin` changed".to_owned()
379        }
380    }
381
382    /// One reason on one line.
383    #[must_use]
384    pub fn reason_line(
385        &self,
386        reason: &Reason,
387    ) -> String {
388        match reason {
389            Reason::NeverRun => "never run: there is no record for this step".to_owned(),
390            Reason::ProgramChanged { block, modules } => self.program(*block, modules),
391            Reason::ArgumentsChanged { old, new } => {
392                let words = Self::words(old, new);
393                format!("the arguments changed: {}", words.join(", "))
394            },
395            Reason::EnvironmentChanged { changes } => {
396                let changes: Vec<String> = changes
397                    .iter()
398                    .map(|change| self.env_change(change))
399                    .collect();
400                format!("the environment changed: {}", changes.join(", "))
401            },
402            Reason::WorkingDirectoryChanged { old, new } => {
403                format!(
404                    "the working directory changed from {} to {}",
405                    self.quoted_path(old),
406                    self.quoted_path(new)
407                )
408            },
409            Reason::StdinChanged { old, new } => self.stdin(old.as_deref(), new.as_deref()),
410            Reason::CaptureChanged { old, new } => {
411                format!(
412                    "the capture mode changed from {} to {}",
413                    capture(*old),
414                    capture(*new)
415                )
416            },
417            Reason::IgnoreChanged { old, new } => {
418                format!(
419                    "the ignore patterns changed from {} to {}",
420                    patterns(old),
421                    patterns(new)
422                )
423            },
424            Reason::TrackChanged { old, new } => {
425                format!(
426                    "the `track` patterns changed from {} to {}",
427                    patterns(old),
428                    patterns(new)
429                )
430            },
431            Reason::TimestampsChanged { old, new } => {
432                format!(
433                    "the `timestamps` option changed from {} to {}",
434                    starlark_bool(*old),
435                    starlark_bool(*new)
436                )
437            },
438            Reason::MachineNamesChanged { old, new } => {
439                format!(
440                    "the `machine` names changed from {} to {}",
441                    patterns(old),
442                    patterns(new)
443                )
444            },
445            Reason::InputsChanged { inputs } => self.inputs_short(inputs),
446            Reason::MachineChanged { changes } => {
447                format!(
448                    "the machine state changed: {}",
449                    machine_changes_text(changes)
450                )
451            },
452            Reason::Always => "marked `always`".to_owned(),
453            Reason::TaskCacheNever => "its task is marked `cache=never`".to_owned(),
454            Reason::Untraced => "dependency tracing is disabled; runs on every build".to_owned(),
455            Reason::TracingChanged { old, new } => {
456                format!(
457                    "the `untraced` option changed from {} to {}",
458                    starlark_bool(*old),
459                    starlark_bool(*new)
460                )
461            },
462            Reason::RunNoCache => "`kizz run --no-cache` was given".to_owned(),
463            Reason::NotCached { why, inputs } => {
464                let why = self.not_cached(why);
465                if inputs.is_empty() {
466                    format!("the previous run could not be cached: {why}")
467                } else {
468                    format!(
469                        "the previous run could not be cached: {why}; {}",
470                        self.inputs_short(inputs)
471                    )
472                }
473            },
474        }
475    }
476
477    /// One reason in full, on one or more lines.
478    #[must_use]
479    pub fn reason_full(
480        &self,
481        reason: &Reason,
482    ) -> Vec<String> {
483        match reason {
484            Reason::ArgumentsChanged { old, new } => {
485                let mut lines = vec![
486                    "the arguments changed:".to_owned(),
487                    format!("  old: {}", old.join(" ")),
488                    format!("  new: {}", new.join(" ")),
489                ];
490                lines.extend(
491                    Self::words(old, new)
492                        .into_iter()
493                        .map(|word| format!("  {word}")),
494                );
495                lines
496            },
497            Reason::EnvironmentChanged { changes } => {
498                let mut lines = vec!["the environment changed:".to_owned()];
499                lines.extend(
500                    changes
501                        .iter()
502                        .map(|change| format!("  {}", self.env_change(change))),
503                );
504                lines
505            },
506            Reason::InputsChanged { inputs } => {
507                let mut lines = vec![format!("{} changed:", count(inputs.len(), "input"))];
508                lines.extend(self.inputs_full(inputs));
509                lines
510            },
511            Reason::MachineChanged { changes } => {
512                let mut lines = vec!["the machine state changed:".to_owned()];
513                lines.extend(changes.iter().map(|change| format!("  {change}")));
514                lines
515            },
516            Reason::NotCached { why, inputs } => {
517                let mut lines = vec![format!(
518                    "the previous run could not be cached: {}",
519                    self.not_cached(why)
520                )];
521                if !inputs.is_empty() {
522                    lines.push(format!("{} changed since:", count(inputs.len(), "input")));
523                    lines.extend(self.inputs_full(inputs));
524                }
525                lines
526            },
527            Reason::NeverRun
528            | Reason::ProgramChanged { .. }
529            | Reason::WorkingDirectoryChanged { .. }
530            | Reason::StdinChanged { .. }
531            | Reason::CaptureChanged { .. }
532            | Reason::IgnoreChanged { .. }
533            | Reason::TrackChanged { .. }
534            | Reason::TimestampsChanged { .. }
535            | Reason::MachineNamesChanged { .. }
536            | Reason::Always
537            | Reason::TaskCacheNever
538            | Reason::Untraced
539            | Reason::TracingChanged { .. }
540            | Reason::RunNoCache => vec![self.reason_line(reason)],
541        }
542    }
543
544    /// The warning line of an explanation whose self-inflicted inputs also made the
545    /// step run in its task's previous build.
546    fn repeated_line(
547        &self,
548        paths: &[PathBuf],
549    ) -> String {
550        let shown: Vec<String> = paths.iter().map(|path| self.quoted_path(path)).collect();
551        format!(
552            "warning: re-ran in consecutive builds for the same self-inflicted reason: {} \
553             changed, and the build itself changes it every time; add an ignore pattern if \
554             it is not a real input",
555            shown.join(", ")
556        )
557    }
558
559    /// The one-line reason of a verdict, as `kizz build` prints it for each command.
560    #[must_use]
561    pub fn one_line(
562        &self,
563        verdict: &Verdict,
564    ) -> String {
565        match verdict {
566            Verdict::Cached => CACHED.to_owned(),
567            Verdict::Ran(explanation) => {
568                let reasons: Vec<String> = explanation
569                    .reasons
570                    .iter()
571                    .map(|reason| self.reason_line(reason))
572                    .collect();
573                reasons.join("; ")
574            },
575        }
576    }
577
578    /// The full reasons of a verdict, as `--explain` and `kizz why` print them:
579    /// `ran because:` and every reason in full, or the cached line, then the
580    /// warning for consecutive builds when it applies.
581    #[must_use]
582    pub fn full(
583        &self,
584        verdict: &Verdict,
585    ) -> Vec<String> {
586        match verdict {
587            Verdict::Cached => vec![CACHED.to_owned()],
588            Verdict::Ran(explanation) => self.explanation(explanation),
589        }
590    }
591
592    /// The full reasons of an explanation.
593    fn explanation(
594        &self,
595        explanation: &Explanation,
596    ) -> Vec<String> {
597        let mut lines = vec!["ran because:".to_owned()];
598        for reason in &explanation.reasons {
599            lines.extend(
600                self.reason_full(reason)
601                    .into_iter()
602                    .map(|line| format!("  {line}")),
603            );
604        }
605        if !explanation.repeated.is_empty() {
606            lines.push(self.repeated_line(&explanation.repeated));
607        }
608        lines
609    }
610
611    /// The loud warning for a step that re-ran in consecutive builds for the same
612    /// self-inflicted reason, as the build summary and `kizz why` show it.
613    #[must_use]
614    pub fn repeated(
615        &self,
616        warning: &RepeatedWarning,
617    ) -> String {
618        let step = match &warning.task {
619            Some(task) => self.step_of(task, warning.position),
620            None => format!("step {}", warning.position.saturating_add(1)),
621        };
622        let shown: Vec<String> = warning
623            .paths
624            .iter()
625            .map(|path| self.quoted_path(path))
626            .collect();
627        format!(
628            "{step} ({}) re-ran in consecutive builds for the same self-inflicted reason: {} \
629             changed, and the build itself changes it every time; add an ignore pattern if \
630             it is not a real input",
631            quoted(&warning.command),
632            shown.join(", ")
633        )
634    }
635}
636
637/// Unit tests for the rendering of the parts of explanations.
638#[cfg(test)]
639#[allow(
640    clippy::disallowed_macros,
641    clippy::disallowed_methods,
642    reason = "test code: the tests assert and lock"
643)]
644mod tests {
645    use kizz_store::TaskId;
646
647    use super::*;
648
649    /// A renderer with base `/w` and home `/home/u`.
650    fn render(verbose: bool) -> Render {
651        Render {
652            base: PathBuf::from("/w"),
653            home: Some(PathBuf::from("/home/u")),
654            verbose,
655        }
656    }
657
658    #[test]
659    fn paths_are_relative_to_the_base_or_the_home_directory() {
660        let render = render(false);
661        assert_eq!(render.path(Path::new("/w")), ".");
662        assert_eq!(render.path(Path::new("/w/a/b")), "a/b");
663        assert_eq!(render.path(Path::new("/home/u/.cache/x")), "~/.cache/x");
664        assert_eq!(render.path(Path::new("/etc/hosts")), "/etc/hosts");
665    }
666
667    #[test]
668    fn tasks_and_access_kinds_read_as_output_shows_them() {
669        let render = render(false);
670        let mut label = TaskLabel {
671            task: TaskId {
672                file: PathBuf::from("/w/a/kizz.md"),
673                index: 0,
674            },
675            line: 3,
676            heading: Some("Build".to_owned()),
677        };
678        assert_eq!(render.task(&label), "a/kizz.md:3 (Build)");
679        label.heading = None;
680        assert_eq!(render.task(&label), "a/kizz.md:3");
681        label.line = 0;
682        assert_eq!(render.task(&label), "a/kizz.md");
683        assert_eq!(
684            access_kinds(AccessBits(AccessBits::READ | AccessBits::LIST)),
685            "read, list"
686        );
687        assert_eq!(
688            access_kinds(AccessBits(AccessBits::EXEC | AccessBits::XATTR)),
689            "exec, xattr"
690        );
691    }
692
693    #[test]
694    fn words_compare_the_arguments_one_by_one() {
695        let old = ["cc", "-O2", "a.c"].map(str::to_owned);
696        let new = ["cc", "-O0", "a.c", "-g"].map(str::to_owned);
697        assert_eq!(Render::words(&old, &new), [
698            "word 2: `-O2` became `-O0`",
699            "word 4 added: `-g`"
700        ]);
701        assert_eq!(Render::words(&new, &old), [
702            "word 2: `-O0` became `-O2`",
703            "word 4 removed: `-g`"
704        ]);
705    }
706}