1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//! Suite configuration and its builder API.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
/// Configuration shared by all tests in one Lit suite.
///
/// Create this value with [`LitConfig::new()`]. Builder methods replace scalar
/// settings and add values to collection settings. The configuration inherits
/// the process environment when it is created. Relative roots and tool paths
/// are anchored to the process working directory when each method is called.
#[derive(Debug, Clone)]
pub struct LitConfig {
pub(crate) name: String,
pub(crate) root: PathBuf,
pub(crate) tools: HashMap<String, RegisteredTool>,
pub(crate) suffixes: HashSet<String>,
pub(crate) exclusions: HashSet<String>,
pub(crate) substitutions: Vec<(String, String)>,
pub(crate) environment: HashMap<String, String>,
pub(crate) available_features: HashSet<String>,
pub(crate) pipefail: bool,
pub(crate) recursive_expansion_limit: Option<usize>,
pub(crate) limit_to_features: HashSet<String>,
pub(crate) max_individual_test_time_seconds: Option<u64>,
pub(crate) no_execute: bool,
pub(crate) normalize_slashes: bool,
pub(crate) test_source_root: Option<PathBuf>,
pub(crate) test_exec_root: Option<PathBuf>,
pub(crate) default_substitutions: Vec<(String, String)>,
pub(crate) test_retry_attempts: usize,
}
#[derive(Debug, Clone)]
pub(crate) struct RegisteredTool {
path: PathBuf,
#[cfg(test)]
utf8: Option<String>,
}
impl LitConfig {
/// Creates configuration for tests below `root`.
///
/// The initial environment contains every Unicode variable from the current
/// process. Tests inherit this snapshot unless [`Self::env()`] replaces a
/// value. A relative root is anchored when this method is called.
///
/// # Panics
///
/// Panics if `root` is relative and the process working directory is not
/// available.
pub fn new(root: impl Into<PathBuf>) -> Self {
let root = anchor_path(root.into());
Self {
name: "litnik".into(),
root,
tools: HashMap::new(),
suffixes: HashSet::new(),
exclusions: HashSet::new(),
substitutions: Vec::new(),
environment: std::env::vars().collect(),
available_features: HashSet::new(),
pipefail: true,
recursive_expansion_limit: None,
limit_to_features: HashSet::new(),
max_individual_test_time_seconds: None,
no_execute: false,
normalize_slashes: false,
test_source_root: None,
test_exec_root: None,
default_substitutions: Vec::new(),
test_retry_attempts: 0,
}
}
/// Replaces the name shown before each test path.
pub fn suite_name(mut self, value: impl Into<String>) -> Self {
self.name = value.into();
self
}
/// Registers an executable for a command name used in `RUN:` directives.
///
/// Registration replaces an earlier path for the same name. The runner
/// invokes the path directly and does not require it to be on `PATH`. A
/// relative path is anchored when this method is called.
///
/// # Panics
///
/// Panics if `path` is relative and the process working directory is not
/// available.
pub fn tool(mut self, name: impl Into<String>, path: impl Into<PathBuf>) -> Self {
let name = name.into();
let path = anchor_path(path.into());
#[cfg(test)]
let utf8 = path.to_str().map(ToOwned::to_owned);
self.tools.insert(
name,
RegisteredTool {
path,
#[cfg(test)]
utf8,
},
);
self
}
/// Adds one test-file suffix.
///
/// A missing leading dot is added. An empty suffix is ignored.
pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
let suffix = suffix.into();
if !suffix.is_empty() {
self.suffixes.insert(if suffix.starts_with('.') {
suffix
} else {
format!(".{suffix}")
});
}
self
}
/// Adds test-file suffixes.
///
/// This method applies the same normalization as [`Self::suffix()`] to each
/// value.
pub fn suffixes<I, S>(mut self, values: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
for value in values {
self = self.suffix(value);
}
self
}
/// Excludes a file or directory whose base name equals `value`.
pub fn exclude(mut self, value: impl Into<String>) -> Self {
self.exclusions.insert(value.into());
self
}
/// Adds excluded file or directory base names.
pub fn excludes<I, S>(mut self, values: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.exclusions.extend(values.into_iter().map(Into::into));
self
}
/// Adds a regular-expression substitution for `RUN:` directives.
///
/// Substitutions run in insertion order before Lit's built-in substitutions.
/// The replacement is inserted as literal text; `$` has no special meaning.
pub fn substitution(mut self, pattern: impl Into<String>, value: impl Into<String>) -> Self {
self.substitutions.push((pattern.into(), value.into()));
self
}
/// Adds regular-expression substitutions in iteration order.
pub fn substitutions<I, K, V>(mut self, values: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<String>,
{
self.substitutions
.extend(values.into_iter().map(|(k, v)| (k.into(), v.into())));
self
}
/// Adds a default substitution before Lit's built-in substitutions.
///
/// Use [`Self::substitution()`] for suite-specific substitutions. This
/// method exists for integrations that assemble a base configuration.
pub fn default_substitution(
mut self,
pattern: impl Into<String>,
value: impl Into<String>,
) -> Self {
self.default_substitutions
.push((pattern.into(), value.into()));
self
}
/// Adds default substitutions in iteration order.
pub fn default_substitutions<I, K, V>(mut self, values: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<String>,
{
self.default_substitutions
.extend(values.into_iter().map(|(k, v)| (k.into(), v.into())));
self
}
/// Makes one feature available to boolean test directives.
pub fn feature(mut self, value: impl Into<String>) -> Self {
self.available_features.insert(value.into());
self
}
/// Makes each supplied feature available to boolean test directives.
pub fn features<I, S>(mut self, values: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.available_features
.extend(values.into_iter().map(Into::into));
self
}
/// Replaces one environment variable in the test environment snapshot.
pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.environment.insert(key.into(), value.into());
self
}
/// Replaces the source root used for discovery and `%s` paths.
///
/// A relative root is anchored when this method is called.
///
/// # Panics
///
/// Panics if the root is relative and the process working directory is not
/// available.
pub fn source_root(mut self, value: impl Into<PathBuf>) -> Self {
self.test_source_root = Some(anchor_path(value.into()));
self
}
/// Replaces the root used for test working directories and temporary files.
///
/// The directory is created when a test runs. The source tree is used when
/// no execution root is set. A relative root is anchored when this method
/// is called.
///
/// # Panics
///
/// Panics if the root is relative and the process working directory is not
/// available.
pub fn exec_root(mut self, value: impl Into<PathBuf>) -> Self {
self.test_exec_root = Some(anchor_path(value.into()));
self
}
/// Sets the maximum number of recursive substitution passes.
///
/// `None` applies one pass. `Some(limit)` requires expansion to stabilize
/// within `limit` additional passes.
pub fn recursive_expansion_limit(mut self, value: Option<usize>) -> Self {
self.recursive_expansion_limit = value;
self
}
/// Sets the time limit for one test attempt, in seconds.
///
/// A value of zero disables the limit. The runner stops child processes at
/// the limit. It cannot preempt an embedded command while it runs.
pub fn max_individual_test_time(mut self, secs: u64) -> Self {
self.max_individual_test_time_seconds = (secs != 0).then_some(secs);
self
}
/// Selects validation without command execution.
///
/// The runner still reads the test, parses directives, applies
/// substitutions, and evaluates feature conditions.
pub fn no_execute(mut self, value: bool) -> Self {
self.no_execute = value;
self
}
/// Controls whether a failed pipeline stage fails the complete pipeline.
pub fn with_pipefail(mut self, value: bool) -> Self {
self.pipefail = value;
self
}
/// Controls slash normalization in path substitutions.
pub fn normalize_slashes(mut self, value: bool) -> Self {
self.normalize_slashes = value;
self
}
/// Restricts execution to tests that require at least one listed feature.
pub fn limit_to_features<I, S>(mut self, values: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.limit_to_features = values.into_iter().map(Into::into).collect();
self
}
/// Sets the number of retries after an initial failed attempt.
///
/// A test-level `ALLOW_RETRIES:` directive replaces this value.
pub fn test_retry_attempts(mut self, attempts: usize) -> Self {
self.test_retry_attempts = attempts;
self
}
#[cfg(test)]
pub(crate) fn tool_path(&self, name: &str) -> Option<&String> {
self.tools.get(name)?.utf8.as_ref()
}
/// Returns the registered executable for `name`.
pub fn registered_tool(&self, name: &str) -> Option<&Path> {
self.tools.get(name).map(|tool| tool.path.as_path())
}
pub(crate) fn to_test_config(&self) -> crate::test::TestConfig {
crate::test::TestConfig {
name: self.name.clone(),
suffixes: self.suffixes.clone(),
exclusions: self.exclusions.clone(),
substitutions: self.substitutions.clone(),
default_substitutions: self.default_substitutions.clone(),
available_features: self.available_features.clone(),
normalize_slashes: self.normalize_slashes,
pipefail: self.pipefail,
recursive_expansion_limit: self.recursive_expansion_limit,
limit_to_features: self.limit_to_features.clone(),
max_individual_test_time: self
.max_individual_test_time_seconds
.map(std::time::Duration::from_secs),
environment: self.environment.clone(),
test_retry_attempts: self.test_retry_attempts,
tools: self
.tools
.iter()
.map(|(name, tool)| (name.clone(), tool.path.clone()))
.collect(),
}
}
#[cfg(test)]
pub(crate) fn use_external_shell(self, _value: bool) -> Self {
self
}
}
pub(crate) fn anchor_path(path: PathBuf) -> PathBuf {
if path.is_absolute() {
path
} else {
std::env::current_dir()
.expect("cannot anchor a relative path without a process working directory")
.join(path)
}
}
impl Default for LitConfig {
fn default() -> Self {
Self::new(".")
}
}
#[cfg(test)]
mod tests {
use super::LitConfig;
#[test]
fn builder_roundtrip() {
let cfg = LitConfig::new("/tmp/root")
.suite_name("x")
.suffix(".mlir")
.exclude("Inputs")
.tool("clang", "/bin/clang")
.feature("linux");
assert_eq!(cfg.name, "x");
assert!(cfg.suffixes.contains(".mlir"));
assert!(cfg.exclusions.contains("Inputs"));
assert_eq!(cfg.tool_path("clang"), Some(&"/bin/clang".to_string()));
assert!(cfg.available_features.contains("linux"));
}
}