1use 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#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Project {
25 pub root: PathBuf,
27 pub files: Vec<KizzFile>,
29 pub tasks: Vec<Task>,
32 pub warnings: Vec<Warning>,
34}
35
36#[derive(Debug, Error)]
41pub enum ConfigError {
42 Read {
44 file: PathBuf,
46 source: io::Error,
48 },
49 InvalidTarget {
51 file: PathBuf,
53 line: usize,
55 heading: Option<String>,
57 target: String,
59 },
60 TaskOption {
63 file: PathBuf,
65 line: usize,
67 heading: Option<String>,
69 option: String,
71 problem: OptionProblem,
73 },
74 TooManyTasks {
76 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#[derive(Debug, Error)]
123pub enum LoadError {
124 Root {
126 root: PathBuf,
128 source: io::Error,
130 },
131 Config {
133 errors: Vec<ConfigError>,
135 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
163pub 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#[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 fn load(root: &Path) -> Result<super::Project, LoadError> {
234 super::load(root, &WorkerPool::new().unwrap())
235 }
236
237 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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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}