Skip to main content

kizz_core/
project.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! Loading a project: discovering its `kizz.md` files and parsing their tasks.
6
7use std::{
8    fmt, fs, io,
9    path::{Path, PathBuf},
10};
11
12use thiserror::Error;
13
14use crate::{
15    discovery::{Discovery, KizzFile, discover},
16    pool::WorkerPool,
17    targets::TARGET_NAME_RULE,
18    tasks::{OptionProblem, Task, parse_tasks},
19    warning::{Warning, location, shown},
20};
21
22/// The discovered tasks under one directory.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Project {
25    /// The absolute directory discovery started in.
26    pub root: PathBuf,
27    /// The `kizz.md` files, each once, in the default order.
28    pub files: Vec<KizzFile>,
29    /// The tasks: the files in the default order, and each file's tasks in file
30    /// order.
31    pub tasks: Vec<Task>,
32    /// Every warning from discovery, then every warning from parsing, in file order.
33    pub warnings: Vec<Warning>,
34}
35
36/// A configuration error in a `kizz.md`, which kizz reports with the usage-error
37/// status.
38///
39/// Every path is relative to the directory discovery started in.
40#[derive(Debug, Error)]
41pub enum ConfigError {
42    /// A `kizz.md` could not be read, or is not UTF-8.
43    Read {
44        /// The file.
45        file: PathBuf,
46        /// Why it could not be read.
47        source: io::Error,
48    },
49    /// A task block has a target that is not a valid target name.
50    InvalidTarget {
51        /// The `kizz.md` that holds the block.
52        file: PathBuf,
53        /// The line of the block's opening fence, counting from 1.
54        line: usize,
55        /// The nearest heading above the block, if there is one.
56        heading: Option<String>,
57        /// The invalid target.
58        target: String,
59    },
60    /// A task block has a task option that is unknown, repeated, or has a value that
61    /// the option does not accept, or a name that another task of its file has.
62    TaskOption {
63        /// The `kizz.md` that holds the block.
64        file: PathBuf,
65        /// The line of the block's opening fence, counting from 1.
66        line: usize,
67        /// The nearest heading above the block, if there is one.
68        heading: Option<String>,
69        /// The option, as the info string writes it.
70        option: String,
71        /// What is wrong with it.
72        problem: OptionProblem,
73    },
74    /// A `kizz.md` has more task blocks than a task position can number.
75    TooManyTasks {
76        /// The file.
77        file: PathBuf,
78    },
79}
80
81impl fmt::Display for ConfigError {
82    fn fmt(
83        &self,
84        f: &mut fmt::Formatter<'_>,
85    ) -> fmt::Result {
86        match self {
87            Self::Read { file, source } => write!(f, "could not read {}: {source}", shown(file)),
88            Self::InvalidTarget {
89                file,
90                line,
91                heading,
92                target,
93            } => {
94                write!(
95                    f,
96                    "{}: invalid target name `{target}`: {TARGET_NAME_RULE}",
97                    location(file, *line, heading.as_deref())
98                )
99            },
100            Self::TaskOption {
101                file,
102                line,
103                heading,
104                option,
105                problem,
106            } => {
107                write!(
108                    f,
109                    "{}: {}",
110                    location(file, *line, heading.as_deref()),
111                    problem.message(option)
112                )
113            },
114            Self::TooManyTasks { file } => {
115                write!(f, "{}: more task blocks than kizz can number", shown(file))
116            },
117        }
118    }
119}
120
121/// Why a project could not be loaded.
122#[derive(Debug, Error)]
123pub enum LoadError {
124    /// The directory to start discovery in is not a readable directory.
125    Root {
126        /// The directory.
127        root: PathBuf,
128        /// What went wrong.
129        source: io::Error,
130    },
131    /// One or more `kizz.md` files have configuration errors.
132    Config {
133        /// Every configuration error, in file order.
134        errors: Vec<ConfigError>,
135        /// Every warning found while loading, as [`Project::warnings`] would hold
136        /// them, so they can still be reported with the errors.
137        warnings: Vec<Warning>,
138    },
139}
140
141impl fmt::Display for LoadError {
142    fn fmt(
143        &self,
144        f: &mut fmt::Formatter<'_>,
145    ) -> fmt::Result {
146        match self {
147            Self::Root { root, source } => {
148                write!(f, "cannot discover tasks in {}: {source}", root.display())
149            },
150            Self::Config { errors, .. } => {
151                for (position, error) in errors.iter().enumerate() {
152                    if position > 0 {
153                        f.write_str("\n")?;
154                    }
155                    write!(f, "{error}")?;
156                }
157                Ok(())
158            },
159        }
160    }
161}
162
163/// Discover every `kizz.md` under `root`, walking on `pool`, and parse its tasks.
164///
165/// # Errors
166///
167/// [`LoadError::Root`] when `root` is not a readable directory, and
168/// [`LoadError::Config`] with every configuration error found when any `kizz.md`
169/// cannot be read or has an invalid target name or task option, together with every
170/// discovery and parsing warning found.
171pub fn load(
172    root: &Path,
173    pool: &WorkerPool,
174) -> Result<Project, LoadError> {
175    let root_error = |source| {
176        LoadError::Root {
177            root: root.to_path_buf(),
178            source,
179        }
180    };
181    let root = std::path::absolute(root).map_err(root_error)?;
182    if !fs::metadata(&root).map_err(root_error)?.is_dir() {
183        return Err(root_error(io::ErrorKind::NotADirectory.into()));
184    }
185
186    let Discovery {
187        files,
188        mut warnings,
189    } = discover(&root, pool);
190    let mut tasks: Vec<Task> = Vec::new();
191    let mut errors: Vec<ConfigError> = Vec::new();
192    for file in &files {
193        match fs::read_to_string(&file.path) {
194            Ok(source) => {
195                let parsed = parse_tasks(&file.path, &file.relative, &source);
196                tasks.extend(parsed.tasks);
197                warnings.extend(parsed.warnings);
198                errors.extend(parsed.errors);
199            },
200            Err(source) => {
201                errors.push(ConfigError::Read {
202                    file: file.relative.clone(),
203                    source,
204                });
205            },
206        }
207    }
208    if !errors.is_empty() {
209        return Err(LoadError::Config { errors, warnings });
210    }
211    Ok(Project {
212        root,
213        files,
214        tasks,
215        warnings,
216    })
217}
218
219/// Unit tests for loading projects.
220#[cfg(test)]
221#[allow(
222    clippy::disallowed_macros,
223    clippy::disallowed_methods,
224    reason = "test code: the tests assert and lock"
225)]
226mod tests {
227    use std::{fs, io, path::Path};
228
229    use super::{ConfigError, LoadError};
230    use crate::{pool::WorkerPool, tasks::Task, warning::Warning};
231
232    /// Load the project under `root` with a worker pool of its own.
233    fn load(root: &Path) -> Result<super::Project, LoadError> {
234        super::load(root, &WorkerPool::new().unwrap())
235    }
236
237    /// The recursive-link warning that [`link_up`] causes for `dir`.
238    fn recursive_link_warning(dir: &str) -> String {
239        format!(
240            "skipped the symbolic link {dir}/up: it leads back to ., one of its own parent \
241             directories, so following it would recurse"
242        )
243    }
244
245    /// Make `dir/up` under `root` a symbolic link to `..`, the root, which discovery
246    /// must skip with a warning.
247    #[cfg(unix)]
248    fn link_up(
249        root: &Path,
250        dir: &str,
251    ) -> io::Result<()> {
252        std::os::unix::fs::symlink("..", root.join(dir).join("up"))
253    }
254
255    /// Make `dir/up` under `root` a symbolic link to `..`, the root, which discovery
256    /// must skip with a warning.
257    #[cfg(windows)]
258    fn link_up(
259        root: &Path,
260        dir: &str,
261    ) -> io::Result<()> {
262        std::os::windows::fs::symlink_dir("..", root.join(dir).join("up"))
263    }
264
265    /// Write `content` to `path` under `root`, creating its directories.
266    fn write(
267        root: &Path,
268        path: &str,
269        content: &str,
270    ) {
271        let path = root.join(path);
272        fs::create_dir_all(path.parent().unwrap()).unwrap();
273        fs::write(path, content).unwrap();
274    }
275
276    /// Tasks come in the default order of their files, and in file order within
277    /// each; each task is identified by its file's absolute path and its position.
278    #[test]
279    fn loads_tasks_in_the_default_order() {
280        let dir = tempfile::tempdir().unwrap();
281        let root = dir.path();
282        write(root, "a/b/kizz.md", "# Deep\n\n```starlark ci\n```\n");
283        write(
284            root,
285            "a/kizz.md",
286            "# A\n\n```starlark ci\n```\n\n## A2\n\n~~~starlark check\n~~~\n",
287        );
288        write(
289            root,
290            "kizz.md",
291            "# Top\n\n```starlark\n```\n\n```starlark ci\n```\n",
292        );
293        write(root, ".gitignore", "a/\n");
294
295        let project = load(root).unwrap();
296        assert_eq!(project.root, root);
297        let locations: Vec<String> = project.tasks.iter().map(Task::location).collect();
298        assert_eq!(locations, [
299            "kizz.md:6 (Top)",
300            "a/kizz.md:3 (A)",
301            "a/kizz.md:8 (A2)",
302            "a/b/kizz.md:3 (Deep)",
303        ]);
304        let ids: Vec<(&Path, u32)> = project
305            .tasks
306            .iter()
307            .map(|task| (task.id.file.as_path(), task.id.index))
308            .collect();
309        assert_eq!(ids, [
310            (root.join("kizz.md").as_path(), 0),
311            (root.join("a/kizz.md").as_path(), 0),
312            (root.join("a/kizz.md").as_path(), 1),
313            (root.join("a/b/kizz.md").as_path(), 0),
314        ]);
315        assert_eq!(project.warnings, [Warning::UntaggedBlock {
316            file: "kizz.md".into(),
317            line: 3,
318            heading: Some("Top".to_owned()),
319        }]);
320    }
321
322    /// Invalid target names in any file make loading fail with every configuration
323    /// error.
324    #[test]
325    fn invalid_targets_fail_loading() {
326        let dir = tempfile::tempdir().unwrap();
327        write(dir.path(), "kizz.md", "# One\n\n```starlark ok bad!\n```\n");
328        write(dir.path(), "sub/kizz.md", "```starlark a/b\n```\n");
329        let Err(LoadError::Config { errors, .. }) = load(dir.path()) else {
330            panic!("expected configuration errors");
331        };
332        let messages: Vec<String> = errors.iter().map(ToString::to_string).collect();
333        assert_eq!(messages, [
334            "kizz.md:3 (One): invalid target name `bad!`: target names use only letters, \
335             digits, `_`, `.` and `-`",
336            "sub/kizz.md:1: invalid target name `a/b`: target names use only letters, digits, \
337             `_`, `.` and `-`",
338        ]);
339    }
340
341    /// A `kizz.md` that is not UTF-8 is a configuration error that names it.
342    #[test]
343    fn unreadable_files_fail_loading() {
344        let dir = tempfile::tempdir().unwrap();
345        fs::write(dir.path().join("kizz.md"), [0xFF, 0xFE, 0x00]).unwrap();
346        let Err(LoadError::Config { errors, .. }) = load(dir.path()) else {
347            panic!("expected a configuration error");
348        };
349        assert!(
350            matches!(&errors[..], [ConfigError::Read { file, .. }] if file == Path::new("kizz.md")),
351            "{errors:?}"
352        );
353    }
354
355    /// Configuration errors keep every discovery and parsing warning: a recursive
356    /// link and a block without targets, with an invalid target in the same file.
357    #[test]
358    fn invalid_targets_keep_the_warnings() {
359        let dir = tempfile::tempdir().unwrap();
360        let root = dir.path();
361        write(
362            root,
363            "kizz.md",
364            "# Notes\n\n```starlark\n```\n\n```starlark ci bad!\n```\n",
365        );
366        write(root, "a/kizz.md", "# A\n\n```starlark check\n```\n");
367        link_up(root, "a").unwrap();
368        let Err(LoadError::Config { errors, warnings }) = load(root) else {
369            panic!("expected configuration errors");
370        };
371        let errors: Vec<String> = errors.iter().map(ToString::to_string).collect();
372        assert_eq!(errors, [
373            "kizz.md:6 (Notes): invalid target name `bad!`: target names use only letters, \
374             digits, `_`, `.` and `-`",
375        ]);
376        let warnings: Vec<String> = warnings.iter().map(ToString::to_string).collect();
377        assert_eq!(warnings, [
378            recursive_link_warning("a"),
379            "kizz.md:3 (Notes): this starlark block has neither targets nor a name, so it is not \
380             a task"
381                .to_owned(),
382        ]);
383    }
384
385    /// A `kizz.md` that cannot be read keeps every discovery and parsing warning from
386    /// the other files.
387    #[test]
388    fn unreadable_files_keep_the_warnings() {
389        let dir = tempfile::tempdir().unwrap();
390        let root = dir.path();
391        fs::write(root.join("kizz.md"), [0xFF, 0xFE, 0x00]).unwrap();
392        write(root, "sub/kizz.md", "# Sub\n\n```starlark\n```\n");
393        link_up(root, "sub").unwrap();
394        let Err(LoadError::Config { errors, warnings }) = load(root) else {
395            panic!("expected a configuration error");
396        };
397        assert!(
398            matches!(&errors[..], [ConfigError::Read { file, .. }] if file == Path::new("kizz.md")),
399            "{errors:?}"
400        );
401        let warnings: Vec<String> = warnings.iter().map(ToString::to_string).collect();
402        assert_eq!(warnings, [
403            recursive_link_warning("sub"),
404            "sub/kizz.md:3 (Sub): this starlark block has neither targets nor a name, so it is \
405             not a task"
406                .to_owned(),
407        ]);
408    }
409
410    /// A root that is missing or not a directory cannot be loaded.
411    #[test]
412    fn a_missing_root_fails() {
413        let dir = tempfile::tempdir().unwrap();
414        write(dir.path(), "file", "");
415        for root in [dir.path().join("missing"), dir.path().join("file")] {
416            assert!(
417                matches!(load(&root), Err(LoadError::Root { .. })),
418                "{}",
419                root.display()
420            );
421        }
422    }
423}