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
use std::{
env,
path::{Component, PathBuf},
};
use anyhow::{Context, Error};
use glob::glob;
use once_cell::sync::Lazy;
use pmutil::q;
use proc_macro2::Span;
use regex::Regex;
use relative_path::RelativePath;
use syn::{
parse::{Parse, ParseStream},
Ident, ItemFn, Lit, LitStr, Meta, NestedMeta, Token,
};
pub struct Config {
pattern: String,
exclude_patterns: Vec<Regex>,
}
impl Parse for Config {
fn parse(input: ParseStream) -> syn::Result<Self> {
fn update(c: &mut Config, meta: Meta) {
if let Meta::List(list) = &meta {
if list
.path
.get_ident()
.map(|i| *i == "exclude")
.unwrap_or(false)
{
macro_rules! fail {
() => {{
fail!("invalid input to the attribute")
}};
($inner:expr) => {{
panic!(
"{}\nnote: exclude() expects one or more comma-separated regular \
expressions, like exclude(\".*\\\\.d\\\\.ts\") or \
exclude(\".*\\\\.d\\\\.ts\", \".*\\\\.tsx\")",
$inner
)
}};
}
if list.nested.is_empty() {
fail!("empty exclude()")
}
for token in list.nested.iter() {
match token {
NestedMeta::Meta(_) => fail!(),
NestedMeta::Lit(lit) => {
let lit = match lit {
Lit::Str(v) => v.value(),
_ => fail!(),
};
c.exclude_patterns
.push(Regex::new(&lit).unwrap_or_else(|err| {
fail!(format!("failed to parse regex: {}\n{}", lit, err))
}));
}
}
}
return;
}
}
let expected = r#"#[fixture("fixture/**/*.ts", exclude("*\.d\.ts"))]"#;
unimplemented!(
"Expected something like {}\nGot wrong meta tag: {:?}",
expected,
meta,
)
}
let pattern: LitStr = input.parse()?;
let pattern = pattern.value();
let mut config = Self {
pattern,
exclude_patterns: vec![],
};
let comma: Option<Token![,]> = input.parse()?;
if comma.is_some() {
let meta: Meta = input.parse()?;
update(&mut config, meta);
}
Ok(config)
}
}
pub fn expand(callee: &Ident, attr: Config) -> Result<Vec<ItemFn>, Error> {
let base_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect(
"#[fixture] requires CARGO_MANIFEST_DIR because it's relative to cargo manifest directory",
));
let resolved_path = RelativePath::new(&attr.pattern).to_path(&base_dir);
let pattern = resolved_path.to_string_lossy();
let paths =
glob(&pattern).with_context(|| format!("glob failed for whole path: `{}`", pattern))?;
let mut test_fns = vec![];
static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[^A-Za-z0-9_]").unwrap());
'add: for path in paths {
let path = path.with_context(|| "glob failed for file".to_string())?;
let abs_path = path
.canonicalize()
.with_context(|| format!("failed to canonicalize {}", path.display()))?;
let path_for_name = path.strip_prefix(&base_dir).with_context(|| {
format!(
"Failed to strip prefix `{}` from `{}`",
base_dir.display(),
path.display()
)
})?;
let path_str = path.to_string_lossy();
for pattern in &attr.exclude_patterns {
if pattern.is_match(&path_str) {
continue 'add;
}
if cfg!(target_os = "windows") && pattern.is_match(&path_str.replace('\\', "/")) {
continue 'add;
}
}
let ignored = path.components().any(|c| match c {
Component::Normal(s) => s.to_string_lossy().starts_with('.'),
_ => false,
});
let test_name = format!(
"{}_{}",
callee,
RE.replace_all(
path_for_name
.to_string_lossy()
.replace('\\', "__")
.replace('/', "__")
.as_str(),
"_",
)
)
.replace("___", "__");
let test_ident = Ident::new(&test_name, Span::call_site());
let mut f = q!(
Vars {
test_ident,
path_str: &abs_path.to_string_lossy(),
callee
},
{
#[test]
#[inline(never)]
#[ignore]
#[doc(hidden)]
fn test_ident() {
eprintln!("Input: {}", path_str);
callee(::std::path::PathBuf::from(path_str));
}
}
)
.parse::<ItemFn>();
if !ignored {
f.attrs.retain(|attr| {
if let Some(name) = attr.path.get_ident() {
if name == "ignore" {
return false;
}
}
true
});
}
test_fns.push(f);
}
if test_fns.is_empty() {
panic!("No test found")
}
Ok(test_fns)
}