Skip to main content

kizz_core/
targets.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! Target names, target expressions, and task selection.
6//!
7//! A target expression is one target, or a union of targets joined with `+`, such as
8//! `ci+check`. It selects every task tagged with any of its targets, and a task that
9//! matches several of them is selected once.
10
11use std::{fmt, str::FromStr};
12
13use thiserror::Error;
14
15use crate::tasks::Task;
16
17/// The rule every target name follows, as error messages state it.
18pub const TARGET_NAME_RULE: &str = "target names use only letters, digits, `_`, `.` and `-`";
19
20/// Whether `name` is a valid target name: one or more ASCII letters, digits, `_`,
21/// `.` and `-`.
22#[must_use]
23pub fn is_valid_target(name: &str) -> bool {
24    !name.is_empty()
25        && name
26            .chars()
27            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
28}
29
30/// Why a target expression is malformed.
31#[derive(Debug, Clone, PartialEq, Eq, Error)]
32pub enum TargetExprError {
33    /// The expression, or one of the parts joined with `+`, is empty.
34    #[error(
35        "invalid target expression `{expression}`: a target is missing; join targets with `+`, \
36         such as `ci+check`"
37    )]
38    MissingTarget {
39        /// The whole expression.
40        expression: String,
41    },
42    /// A target in the expression is not a valid target name.
43    #[error(
44        "invalid target expression `{expression}`: invalid target name `{target}`: {}",
45        TARGET_NAME_RULE
46    )]
47    InvalidTarget {
48        /// The whole expression.
49        expression: String,
50        /// The invalid target.
51        target: String,
52    },
53}
54
55/// A parsed target expression: one or more distinct target names, in the order
56/// written.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct TargetExpr {
59    /// The distinct targets, in the order written.
60    targets: Vec<String>,
61}
62
63impl TargetExpr {
64    /// The distinct targets of the expression, in the order written.
65    #[must_use]
66    pub fn targets(&self) -> &[String] {
67        &self.targets
68    }
69
70    /// The tasks the expression selects, in the order of `tasks`, each once, with the
71    /// requested targets that selected it.
72    #[must_use]
73    pub fn select<'tasks>(
74        &self,
75        tasks: &'tasks [Task],
76    ) -> Vec<Selected<'tasks>> {
77        tasks
78            .iter()
79            .filter_map(|task| {
80                let selected: Vec<String> = self
81                    .targets
82                    .iter()
83                    .filter(|target| task.targets.contains(target))
84                    .cloned()
85                    .collect();
86                (!selected.is_empty()).then_some(Selected { task, selected })
87            })
88            .collect()
89    }
90}
91
92impl FromStr for TargetExpr {
93    type Err = TargetExprError;
94
95    fn from_str(expression: &str) -> Result<Self, Self::Err> {
96        let mut targets: Vec<String> = Vec::new();
97        for target in expression.split('+') {
98            if target.is_empty() {
99                return Err(TargetExprError::MissingTarget {
100                    expression: expression.to_owned(),
101                });
102            }
103            if !is_valid_target(target) {
104                return Err(TargetExprError::InvalidTarget {
105                    expression: expression.to_owned(),
106                    target: target.to_owned(),
107                });
108            }
109            if !targets.iter().any(|known| known == target) {
110                targets.push(target.to_owned());
111            }
112        }
113        Ok(Self { targets })
114    }
115}
116
117impl fmt::Display for TargetExpr {
118    fn fmt(
119        &self,
120        f: &mut fmt::Formatter<'_>,
121    ) -> fmt::Result {
122        f.write_str(&self.targets.join("+"))
123    }
124}
125
126/// A task that a target expression selected.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct Selected<'tasks> {
129    /// The task.
130    pub task: &'tasks Task,
131    /// The requested targets that selected the task, in the order of the expression.
132    pub selected: Vec<String>,
133}
134
135/// Unit tests for target names, expressions, and selection.
136#[cfg(test)]
137#[allow(
138    clippy::disallowed_macros,
139    clippy::disallowed_methods,
140    reason = "test code: the tests assert and lock"
141)]
142mod tests {
143    use std::path::PathBuf;
144
145    use kizz_store::TaskId;
146
147    use super::{TargetExpr, TargetExprError, is_valid_target};
148    use crate::tasks::{Task, TaskOptions};
149
150    /// A task in `kizz.md` at `index`, tagged with `targets`.
151    fn task(
152        index: u32,
153        targets: &[&str],
154    ) -> Task {
155        Task {
156            id: TaskId {
157                file: PathBuf::from("/work/kizz.md"),
158                index,
159            },
160            relative_file: PathBuf::from("kizz.md"),
161            line: 1,
162            heading: None,
163            targets: targets.iter().map(|&target| target.to_owned()).collect(),
164            options: TaskOptions::default(),
165            source: String::new(),
166        }
167    }
168
169    /// Target names use letters, digits, `_`, `.` and `-`, and nothing else.
170    #[test]
171    fn target_names_use_letters_digits_and_three_marks() {
172        for name in [
173            "ci",
174            "check",
175            "CI",
176            "v1.2",
177            "lint_all",
178            "pre-commit",
179            "0",
180            "a.b-c_D9",
181        ] {
182            assert!(is_valid_target(name), "{name}");
183        }
184        for name in ["", "ci!", "a b", "a+b", "a/b", "é", "a:b", "*", "a\tb"] {
185            assert!(!is_valid_target(name), "{name:?}");
186        }
187    }
188
189    /// One target and unions parse, keep their order, and drop repeated targets.
190    #[test]
191    fn expressions_parse_targets_and_unions() {
192        let one: TargetExpr = "ci".parse().unwrap();
193        assert_eq!(one.targets(), ["ci"]);
194        let union: TargetExpr = "ci+check+lint".parse().unwrap();
195        assert_eq!(union.targets(), ["ci", "check", "lint"]);
196        assert_eq!(union.to_string(), "ci+check+lint");
197        let repeated: TargetExpr = "ci+check+ci".parse().unwrap();
198        assert_eq!(repeated.targets(), ["ci", "check"]);
199    }
200
201    /// Malformed expressions, such as `ci+`, `+`, and `ci!`, are errors that name the
202    /// expression.
203    #[test]
204    fn malformed_expressions_are_errors() {
205        for expression in ["", "+", "ci+", "+ci", "ci++check"] {
206            assert_eq!(
207                expression.parse::<TargetExpr>(),
208                Err(TargetExprError::MissingTarget {
209                    expression: expression.to_owned()
210                }),
211                "{expression:?}"
212            );
213        }
214        for (expression, target) in [("ci!", "ci!"), ("ci+a b", "a b"), ("ci+check/x", "check/x")] {
215            let error = expression.parse::<TargetExpr>().unwrap_err();
216            assert_eq!(error, TargetExprError::InvalidTarget {
217                expression: expression.to_owned(),
218                target: target.to_owned()
219            });
220            assert!(error.to_string().contains(target), "{error}");
221        }
222    }
223
224    /// A union selects every task of any of its targets, in task order, and a task
225    /// with several selected targets is selected once, with all of them.
226    #[test]
227    fn a_union_selects_each_matching_task_once() {
228        let tasks = [
229            task(0, &["ci", "check"]),
230            task(1, &["lint"]),
231            task(2, &["check"]),
232            task(3, &["docs", "ci"]),
233        ];
234
235        let union: TargetExpr = "check+ci".parse().unwrap();
236        let selected = union.select(&tasks);
237        let indexes: Vec<u32> = selected.iter().map(|s| s.task.id.index).collect();
238        assert_eq!(indexes, [0, 2, 3]);
239        assert_eq!(selected[0].selected, ["check", "ci"]);
240        assert_eq!(selected[1].selected, ["check"]);
241        assert_eq!(selected[2].selected, ["ci"]);
242
243        let one: TargetExpr = "lint".parse().unwrap();
244        let indexes: Vec<u32> = one.select(&tasks).iter().map(|s| s.task.id.index).collect();
245        assert_eq!(indexes, [1]);
246
247        let none: TargetExpr = "release".parse().unwrap();
248        assert_eq!(none.select(&tasks), Vec::new());
249    }
250}