1use std::{fmt, str::FromStr};
12
13use thiserror::Error;
14
15use crate::tasks::Task;
16
17pub const TARGET_NAME_RULE: &str = "target names use only letters, digits, `_`, `.` and `-`";
19
20#[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#[derive(Debug, Clone, PartialEq, Eq, Error)]
32pub enum TargetExprError {
33 #[error(
35 "invalid target expression `{expression}`: a target is missing; join targets with `+`, \
36 such as `ci+check`"
37 )]
38 MissingTarget {
39 expression: String,
41 },
42 #[error(
44 "invalid target expression `{expression}`: invalid target name `{target}`: {}",
45 TARGET_NAME_RULE
46 )]
47 InvalidTarget {
48 expression: String,
50 target: String,
52 },
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct TargetExpr {
59 targets: Vec<String>,
61}
62
63impl TargetExpr {
64 #[must_use]
66 pub fn targets(&self) -> &[String] {
67 &self.targets
68 }
69
70 #[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#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct Selected<'tasks> {
129 pub task: &'tasks Task,
131 pub selected: Vec<String>,
133}
134
135#[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 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 #[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 #[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 #[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 #[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}