| 1 |
use std::{env, path::PathBuf}; |
| 2 |
|
| 3 |
use crate::{ |
| 4 |
error::ErrorsVec, |
| 5 |
parse::{ |
| 6 |
extract_argument_attrs, |
| 7 |
vlist::{Value, ValueList}, |
| 8 |
}, |
| 9 |
refident::{IntoPat, MaybeIdent}, |
| 10 |
utils::attr_is, |
| 11 |
}; |
| 12 |
use glob::glob; |
| 13 |
use quote::ToTokens; |
| 14 |
use regex::Regex; |
| 15 |
use relative_path::{PathExt, RelativePath}; |
| 16 |
use syn::{ |
| 17 |
parse::Parse, parse_quote, visit_mut::VisitMut, Attribute, Expr, FnArg, Ident, ItemFn, LitStr, |
| 18 |
MetaNameValue, |
| 19 |
}; |
| 20 |
|
| 21 |
#[derive(Debug, Clone, PartialEq)] |
| 22 |
pub(crate) struct FilesGlobReferences { |
| 23 |
base_dir: Option<LitStrAttr>, |
| 24 |
glob: Vec<LitStrAttr>, |
| 25 |
exclude: Vec<Exclude>, |
| 26 |
ignore_directories: bool, |
| 27 |
ignore_dot_files: bool, |
| 28 |
ignore_missing_env_vars: bool, |
| 29 |
files_mode: FilesMode, |
| 30 |
} |
| 31 |
|
| 32 |
impl FilesGlobReferences { |
| 33 |
/// Replace environment variables in a string. |
| 34 |
fn replace_env_vars( |
| 35 |
&self, |
| 36 |
attr: &LitStrAttr, |
| 37 |
env: impl EnvironmentResolver, |
| 38 |
) -> Result<String, syn::Error> { |
| 39 |
let re = Regex::new(r"\$([a-zA-Z_][a-zA-Z0-9_]+)|\$\{([^}]+)}") |
| 40 |
.expect("Could not build the regex"); |
| 41 |
|
| 42 |
let ignore_missing = self.ignore_missing_env_vars; |
| 43 |
|
| 44 |
let path = attr.value(); |
| 45 |
let haystack = path.as_str(); |
| 46 |
let mut result = String::with_capacity(attr.value().len()); |
| 47 |
let mut last_match = 0; |
| 48 |
|
| 49 |
for caps in re.captures_iter(haystack) { |
| 50 |
let match_all = caps.get(0).expect("The regex should have matched"); |
| 51 |
|
| 52 |
// Match the name of the variable and its default value (if any). |
| 53 |
let (var_name, default) = if let Some(m) = caps.get(1) { |
| 54 |
// In the first case ($VAR), the default value is None. |
| 55 |
(m.as_str(), None) |
| 56 |
} else { |
| 57 |
// In the second case we have to split the variable name and the default value |
| 58 |
// if there's a `:-` separator. |
| 59 |
let m = caps.get(2).expect("The regex should have matched"); |
| 60 |
|
| 61 |
let (var_name, default) = |
| 62 |
if let Some((var_name, default)) = m.as_str().split_once(":-") { |
| 63 |
(var_name, Some(default)) |
| 64 |
} else { |
| 65 |
(m.as_str(), None) |
| 66 |
}; |
| 67 |
|
| 68 |
var_name |
| 69 |
.chars() |
| 70 |
.all(|c| c.is_alphanumeric() || c == '_') |
| 71 |
.then_some((var_name, default)) |
| 72 |
.ok_or_else(|| { |
| 73 |
attr.error(&format!( |
| 74 |
"The variable \"{}\" name does not match [a-zA-Z0-9_]+", |
| 75 |
m.as_str() |
| 76 |
)) |
| 77 |
})? |
| 78 |
}; |
| 79 |
|
| 80 |
let v = env.get(var_name); |
| 81 |
let replacement = match (v.as_deref(), default) { |
| 82 |
(Some(""), Some(default)) => default.to_string(), |
| 83 |
(Some(val), _) => val.to_string(), |
| 84 |
(None, Some(default)) => default.to_string(), |
| 85 |
(None, _) if ignore_missing => String::new(), |
| 86 |
(None, _) => { |
| 87 |
return Err(attr.error(&format!( |
| 88 |
"Could not find the environment variable {var_name:?}" |
| 89 |
))) |
| 90 |
} |
| 91 |
}; |
| 92 |
|
| 93 |
result.push_str(&haystack[last_match..match_all.start()]); |
| 94 |
result.push_str(&replacement); |
| 95 |
last_match = match_all.end(); |
| 96 |
} |
| 97 |
|
| 98 |
result.push_str(&haystack[last_match..]); |
| 99 |
|
| 100 |
Ok(result) |
| 101 |
} |
| 102 |
|
| 103 |
/// Return the base_dir attribute if set, with variables replaced. |
| 104 |
fn base_dir(&self) -> Result<Option<PathBuf>, syn::Error> { |
| 105 |
self.base_dir |
| 106 |
.as_ref() |
| 107 |
.map(|attr| { |
| 108 |
self.replace_env_vars(attr, StdEnvironmentResolver) |
| 109 |
.map(PathBuf::from) |
| 110 |
}) |
| 111 |
.transpose() |
| 112 |
} |
| 113 |
|
| 114 |
/// Return the tuples attribute, path string if they are valid relative paths |
| 115 |
fn paths(&self, base_dir: &PathBuf) -> Result<Vec<(&LitStrAttr, String)>, syn::Error> { |
| 116 |
self.glob |
| 117 |
.iter() |
| 118 |
.map(|attr| { |
| 119 |
let path = self.replace_env_vars(attr, StdEnvironmentResolver)?; |
| 120 |
RelativePath::from_path(&path) |
| 121 |
.map_err(|e| attr.error(&format!("Invalid glob path: {e}"))) |
| 122 |
.map(|p| p.to_logical_path(base_dir)) |
| 123 |
.map(|p| (attr, p.to_string_lossy().into_owned())) |
| 124 |
}) |
| 125 |
.collect::<Result<Vec<_>, _>>() |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] |
| 130 |
pub(crate) enum FilesMode { |
| 131 |
#[default] |
| 132 |
Path, |
| 133 |
IncludeStr, |
| 134 |
IncludeBytes, |
| 135 |
} |
| 136 |
|
| 137 |
pub(crate) mod files_mode_keywords { |
| 138 |
syn::custom_keyword!(path); |
| 139 |
syn::custom_keyword!(str); |
| 140 |
syn::custom_keyword!(bytes); |
| 141 |
} |
| 142 |
|
| 143 |
impl Parse for FilesMode { |
| 144 |
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { |
| 145 |
if Option::<files_mode_keywords::path>::parse(input)?.is_some() { |
| 146 |
Ok(Self::Path) |
| 147 |
} else if Option::<files_mode_keywords::str>::parse(input)?.is_some() { |
| 148 |
Ok(Self::IncludeStr) |
| 149 |
} else if Option::<files_mode_keywords::bytes>::parse(input)?.is_some() { |
| 150 |
Ok(Self::IncludeBytes) |
| 151 |
} else { |
| 152 |
Err(input.error("Expected one of the following keywords: path, str or bytes")) |
| 153 |
} |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
trait RaiseError: ToTokens { |
| 158 |
fn error(&self, msg: &str) -> syn::Error { |
| 159 |
syn::Error::new_spanned(self, msg) |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
impl RaiseError for Attribute {} |
| 164 |
impl RaiseError for LitStrAttr {} |
| 165 |
impl ToTokens for LitStrAttr { |
| 166 |
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { |
| 167 |
self.attr.to_tokens(tokens) |
| 168 |
} |
| 169 |
} |
| 170 |
|
| 171 |
impl FilesGlobReferences { |
| 172 |
fn new( |
| 173 |
glob: Vec<LitStrAttr>, |
| 174 |
exclude: Vec<Exclude>, |
| 175 |
ignore_directories: bool, |
| 176 |
ignore_dot_files: bool, |
| 177 |
ignore_missing_env_vars: bool, |
| 178 |
files_mode: FilesMode, |
| 179 |
) -> Self { |
| 180 |
Self { |
| 181 |
glob, |
| 182 |
base_dir: None, |
| 183 |
exclude, |
| 184 |
ignore_directories, |
| 185 |
ignore_dot_files, |
| 186 |
ignore_missing_env_vars, |
| 187 |
files_mode, |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
fn with_base_dir_opt(mut self, base_dir: Option<LitStrAttr>) -> Self { |
| 192 |
self.base_dir = base_dir; |
| 193 |
self |
| 194 |
} |
| 195 |
|
| 196 |
fn is_valid(&self, p: &RelativePath) -> bool { |
| 197 |
if self.ignore_dot_files |
| 198 |
&& p.components() |
| 199 |
.any(|c| matches!(c, relative_path::Component::Normal(c) if c.starts_with('.'))) |
| 200 |
{ |
| 201 |
return false; |
| 202 |
} |
| 203 |
!self.exclude.iter().any(|e| e.r.is_match(p.as_ref())) |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
/// An attribute in the form `#[name("some string")]` |
| 208 |
#[derive(Debug, Clone, PartialEq)] |
| 209 |
struct LitStrAttr { |
| 210 |
attr: Attribute, |
| 211 |
value: LitStr, |
| 212 |
} |
| 213 |
|
| 214 |
impl LitStrAttr { |
| 215 |
fn parse_meta_name_value(attr: &Attribute) -> Result<Self, syn::Error> { |
| 216 |
let meta = attr.meta.require_name_value()?; |
| 217 |
if let syn::Expr::Lit(expr) = &meta.value { |
| 218 |
if let syn::Lit::Str(value) = expr.lit.clone() { |
| 219 |
return Ok(Self { |
| 220 |
attr: attr.clone(), |
| 221 |
value, |
| 222 |
}); |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
Err(syn::Error::new_spanned( |
| 227 |
attr, |
| 228 |
"expected a string literal value", |
| 229 |
)) |
| 230 |
} |
| 231 |
|
| 232 |
fn value(&self) -> String { |
| 233 |
self.value.value() |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
impl TryFrom<Attribute> for LitStrAttr { |
| 238 |
type Error = syn::Error; |
| 239 |
|
| 240 |
fn try_from(attr: Attribute) -> Result<Self, Self::Error> { |
| 241 |
let value = attr.parse_args::<LitStr>()?; |
| 242 |
Ok(Self { attr, value }) |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
/// The `#[exclude("regex")]` attribute |
| 247 |
#[derive(Debug, Clone)] |
| 248 |
struct Exclude { |
| 249 |
attr: LitStrAttr, |
| 250 |
r: Regex, |
| 251 |
} |
| 252 |
|
| 253 |
impl PartialEq for Exclude { |
| 254 |
fn eq(&self, other: &Self) -> bool { |
| 255 |
self.attr.value == other.attr.value |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
impl TryFrom<Attribute> for Exclude { |
| 260 |
type Error = syn::Error; |
| 261 |
|
| 262 |
fn try_from(attr: Attribute) -> Result<Self, Self::Error> { |
| 263 |
let attr: LitStrAttr = attr.try_into()?; |
| 264 |
let r = Regex::new(&attr.value()).map_err(|e| { |
| 265 |
syn::Error::new_spanned( |
| 266 |
&attr, |
| 267 |
format!(r#""{}" Should be a valid regex: {e}"#, attr.value()), |
| 268 |
) |
| 269 |
})?; |
| 270 |
Ok(Self { attr, r }) |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
impl From<Vec<LitStrAttr>> for FilesGlobReferences { |
| 275 |
fn from(value: Vec<LitStrAttr>) -> Self { |
| 276 |
Self::new(value, Default::default(), true, true, false, Default::default()) |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
/// Entry point function to extract files attributes |
| 281 |
pub(crate) fn extract_files( |
| 282 |
item_fn: &mut ItemFn, |
| 283 |
) -> Result<Vec<(Ident, FilesGlobReferences)>, ErrorsVec> { |
| 284 |
let mut extractor = ValueFilesExtractor::default(); |
| 285 |
extractor.visit_item_fn_mut(item_fn); |
| 286 |
extractor.take() |
| 287 |
} |
| 288 |
|
| 289 |
/// Simple struct used to visit function attributes and extract future args to |
| 290 |
/// implement the boilerplate. |
| 291 |
#[derive(Default)] |
| 292 |
struct ValueFilesExtractor { |
| 293 |
files: Vec<(Ident, FilesGlobReferences)>, |
| 294 |
errors: Vec<syn::Error>, |
| 295 |
} |
| 296 |
|
| 297 |
impl ValueFilesExtractor { |
| 298 |
pub(crate) fn take(self) -> Result<Vec<(Ident, FilesGlobReferences)>, ErrorsVec> { |
| 299 |
if self.errors.is_empty() { |
| 300 |
Ok(self.files) |
| 301 |
} else { |
| 302 |
Err(self.errors.into()) |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
fn collect_errors<T: Default>(&mut self, result: Result<T, syn::Error>) -> T { |
| 307 |
match result { |
| 308 |
Ok(v) => v, |
| 309 |
Err(e) => { |
| 310 |
self.errors.push(e); |
| 311 |
T::default() |
| 312 |
} |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
fn extract_argument_attrs<'a, B: 'a + std::fmt::Debug>( |
| 317 |
&mut self, |
| 318 |
node: &mut FnArg, |
| 319 |
is_valid_attr: fn(&syn::Attribute) -> bool, |
| 320 |
build: impl Fn(syn::Attribute) -> syn::Result<B> + 'a, |
| 321 |
) -> Vec<B> { |
| 322 |
self.collect_errors( |
| 323 |
extract_argument_attrs(node, is_valid_attr, build).collect::<Result<Vec<_>, _>>(), |
| 324 |
) |
| 325 |
} |
| 326 |
|
| 327 |
fn extract_files(&mut self, node: &mut FnArg) -> Vec<LitStrAttr> { |
| 328 |
self.extract_argument_attrs(node, |a| attr_is(a, "files"), |attr| attr.try_into()) |
| 329 |
} |
| 330 |
|
| 331 |
fn extract_exclude(&mut self, node: &mut FnArg) -> Vec<Exclude> { |
| 332 |
self.extract_argument_attrs(node, |a| attr_is(a, "exclude"), Exclude::try_from) |
| 333 |
} |
| 334 |
|
| 335 |
fn extract_include_dot_files(&mut self, node: &mut FnArg) -> Vec<Attribute> { |
| 336 |
self.extract_argument_attrs( |
| 337 |
node, |
| 338 |
|a| attr_is(a, "include_dot_files"), |
| 339 |
|attr| { |
| 340 |
attr.meta |
| 341 |
.require_path_only() |
| 342 |
.map_err(|_| attr.error("Use #[include_dot_files] to include dot files"))?; |
| 343 |
Ok(attr) |
| 344 |
}, |
| 345 |
) |
| 346 |
} |
| 347 |
|
| 348 |
fn extract_ignore_missing_env_vars(&mut self, node: &mut FnArg) -> Vec<Attribute> { |
| 349 |
self.extract_argument_attrs( |
| 350 |
node, |
| 351 |
|a| attr_is(a, "ignore_missing_env_vars"), |
| 352 |
|attr| { |
| 353 |
attr.meta.require_path_only().map_err(|_| { |
| 354 |
attr.error( |
| 355 |
"Use #[ignore_missing_env_vars] to ignore missing environment variables", |
| 356 |
) |
| 357 |
})?; |
| 358 |
Ok(attr) |
| 359 |
}, |
| 360 |
) |
| 361 |
} |
| 362 |
|
| 363 |
fn extract_dirs(&mut self, node: &mut FnArg) -> Vec<Attribute> { |
| 364 |
self.extract_argument_attrs( |
| 365 |
node, |
| 366 |
|a| attr_is(a, "dirs"), |
| 367 |
|attr| { |
| 368 |
attr.meta.require_path_only().map_err(|_| { |
| 369 |
attr.error( |
| 370 |
"Use #[dirs] to include matched directories", |
| 371 |
) |
| 372 |
})?; |
| 373 |
Ok(attr) |
| 374 |
}, |
| 375 |
) |
| 376 |
} |
| 377 |
|
| 378 |
fn extract_base_dir(&mut self, node: &mut FnArg) -> Vec<LitStrAttr> { |
| 379 |
self.extract_argument_attrs( |
| 380 |
node, |
| 381 |
|a| attr_is(a, "base_dir"), |
| 382 |
|attr| { |
| 383 |
LitStrAttr::parse_meta_name_value(&attr).map_err(|_| { |
| 384 |
attr.error( |
| 385 |
"Use #[base_dir = \"...\"] to define the base directory for the glob path", |
| 386 |
) |
| 387 |
}) |
| 388 |
}, |
| 389 |
) |
| 390 |
} |
| 391 |
|
| 392 |
fn extract_mode(&mut self, node: &mut FnArg) -> Vec<(MetaNameValue, FilesMode)> { |
| 393 |
self.extract_argument_attrs( |
| 394 |
node, |
| 395 |
|a| attr_is(a, "mode"), |
| 396 |
|attr| { |
| 397 |
attr.meta |
| 398 |
.require_name_value() |
| 399 |
.map_err(|_| { |
| 400 |
attr.error("Use #[mode = ...] to define the argument of the file input") |
| 401 |
}) |
| 402 |
.and_then(|attr| { |
| 403 |
syn::parse2(attr.value.to_token_stream()) |
| 404 |
.map(|file_mode| (attr.clone(), file_mode)) |
| 405 |
}) |
| 406 |
}, |
| 407 |
) |
| 408 |
} |
| 409 |
} |
| 410 |
|
| 411 |
impl VisitMut for ValueFilesExtractor { |
| 412 |
fn visit_fn_arg_mut(&mut self, node: &mut FnArg) { |
| 413 |
let name = node.maybe_ident().cloned(); |
| 414 |
if matches!(node, FnArg::Receiver(_)) || name.is_none() { |
| 415 |
return; |
| 416 |
} |
| 417 |
let name = name.unwrap(); |
| 418 |
let files = self.extract_files(node); |
| 419 |
let excludes = self.extract_exclude(node); |
| 420 |
let include_dot_files = self.extract_include_dot_files(node); |
| 421 |
let ignore_missing_env_vars = self.extract_ignore_missing_env_vars(node); |
| 422 |
let ignore_directories = self.extract_dirs(node); |
| 423 |
|
| 424 |
if !include_dot_files.is_empty() { |
| 425 |
include_dot_files.iter().skip(1).for_each(|attr| { |
| 426 |
self.errors |
| 427 |
.push(attr.error("Cannot use #[include_dot_files] more than once")) |
| 428 |
}) |
| 429 |
} |
| 430 |
if !ignore_missing_env_vars.is_empty() { |
| 431 |
ignore_missing_env_vars.iter().skip(1).for_each(|attr| { |
| 432 |
self.errors |
| 433 |
.push(attr.error("Cannot use #[ignore_missing_env_vars] more than once")) |
| 434 |
}) |
| 435 |
} |
| 436 |
if !ignore_directories.is_empty() { |
| 437 |
ignore_directories.iter().skip(1).for_each(|attr| { |
| 438 |
self.errors |
| 439 |
.push(attr.error("Cannot use #[dirs] more than once")) |
| 440 |
}) |
| 441 |
} |
| 442 |
|
| 443 |
let base_dir = self.extract_base_dir(node); |
| 444 |
if base_dir.len() > 1 { |
| 445 |
base_dir.iter().skip(1).for_each(|attr| { |
| 446 |
self.errors |
| 447 |
.push(attr.error(r#"Cannot use #[base_dir = "..."] more than once"#)) |
| 448 |
}) |
| 449 |
} |
| 450 |
let mode_attr = self.extract_mode(node); |
| 451 |
let mode = if let Some(value) = mode_attr.first() { |
| 452 |
mode_attr.iter().skip(1).for_each(|attr| { |
| 453 |
self.errors.push(syn::Error::new_spanned( |
| 454 |
&attr.0, |
| 455 |
r#"Cannot use #[mode = ...] more than once"#, |
| 456 |
)) |
| 457 |
}); |
| 458 |
value.1 |
| 459 |
} else { |
| 460 |
Default::default() |
| 461 |
}; |
| 462 |
if !files.is_empty() { |
| 463 |
self.files.push(( |
| 464 |
name, |
| 465 |
FilesGlobReferences::new( |
| 466 |
files, |
| 467 |
excludes, |
| 468 |
ignore_directories.is_empty(), |
| 469 |
include_dot_files.is_empty(), |
| 470 |
!ignore_missing_env_vars.is_empty(), |
| 471 |
mode, |
| 472 |
) |
| 473 |
.with_base_dir_opt(base_dir.into_iter().next()), |
| 474 |
)) |
| 475 |
} else { |
| 476 |
excludes.into_iter().for_each(|e| { |
| 477 |
self.errors.push( |
| 478 |
e.attr |
| 479 |
.error("You cannot use #[exclude(...)] without #[files(...)]"), |
| 480 |
) |
| 481 |
}); |
| 482 |
include_dot_files.into_iter().for_each(|attr| { |
| 483 |
self.errors |
| 484 |
.push(attr.error("You cannot use #[include_dot_files] without #[files(...)]")) |
| 485 |
}); |
| 486 |
ignore_missing_env_vars.into_iter().for_each(|attr| { |
| 487 |
self.errors.push( |
| 488 |
attr.error("You cannot use #[ignore_missing_env_vars] without #[files(...)]"), |
| 489 |
) |
| 490 |
}); |
| 491 |
ignore_directories.into_iter().for_each(|attr| { |
| 492 |
self.errors |
| 493 |
.push(attr.error("You cannot use #[dirs] without #[files(...)]")) |
| 494 |
}); |
| 495 |
base_dir.into_iter().for_each(|attr| { |
| 496 |
self.errors |
| 497 |
.push(attr.error(r#"You cannot use #[base_dir = "..."] without #[files(...)]"#)) |
| 498 |
}); |
| 499 |
} |
| 500 |
} |
| 501 |
} |
| 502 |
|
| 503 |
trait BaseDir { |
| 504 |
fn base_dir(&self) -> Result<PathBuf, String> { |
| 505 |
env::var("CARGO_MANIFEST_DIR") |
| 506 |
.map(PathBuf::from) |
| 507 |
.map_err(|_| |
| 508 |
"Rstest's #[files(...)] requires that CARGO_MANIFEST_DIR is defined to define glob the relative path".to_string() |
| 509 |
) |
| 510 |
} |
| 511 |
} |
| 512 |
|
| 513 |
struct DefaultBaseDir; |
| 514 |
|
| 515 |
impl BaseDir for DefaultBaseDir {} |
| 516 |
|
| 517 |
trait EnvironmentResolver { |
| 518 |
fn get(&self, var: &str) -> Option<String>; |
| 519 |
} |
| 520 |
|
| 521 |
struct StdEnvironmentResolver; |
| 522 |
|
| 523 |
impl EnvironmentResolver for StdEnvironmentResolver { |
| 524 |
fn get(&self, var: &str) -> Option<String> { |
| 525 |
env::var(var).ok() |
| 526 |
} |
| 527 |
} |
| 528 |
|
| 529 |
trait GlobResolver { |
| 530 |
fn glob(&self, pattern: &str) -> Result<Vec<PathBuf>, String> { |
| 531 |
let globs = |
| 532 |
glob(pattern).map_err(|e| format!("glob failed for whole path `{pattern}` due {e}"))?; |
| 533 |
globs |
| 534 |
.into_iter() |
| 535 |
.map(|p| p.map_err(|e| format!("glob failed for file due {e}"))) |
| 536 |
.map(|r| { |
| 537 |
r.and_then(|p| { |
| 538 |
p.canonicalize() |
| 539 |
.map_err(|e| format!("failed to canonicalize {} due {e}", p.display())) |
| 540 |
}) |
| 541 |
}) |
| 542 |
.collect() |
| 543 |
} |
| 544 |
} |
| 545 |
|
| 546 |
struct DefaultGlobResolver; |
| 547 |
|
| 548 |
impl GlobResolver for DefaultGlobResolver {} |
| 549 |
|
| 550 |
/// The struct used to gel te values from the files attributes. You can inject |
| 551 |
/// the base dir resolver and glob resolver implementation. |
| 552 |
pub(crate) struct ValueListFromFiles<'a> { |
| 553 |
base_dir: Box<dyn BaseDir + 'a>, |
| 554 |
g_resolver: Box<dyn GlobResolver + 'a>, |
| 555 |
} |
| 556 |
|
| 557 |
impl Default for ValueListFromFiles<'_> { |
| 558 |
fn default() -> Self { |
| 559 |
Self { |
| 560 |
g_resolver: Box::new(DefaultGlobResolver), |
| 561 |
base_dir: Box::new(DefaultBaseDir), |
| 562 |
} |
| 563 |
} |
| 564 |
} |
| 565 |
|
| 566 |
impl ValueListFromFiles<'_> { |
| 567 |
pub fn to_value_list( |
| 568 |
&self, |
| 569 |
files: Vec<(Ident, FilesGlobReferences)>, |
| 570 |
) -> Result<Vec<ValueList>, syn::Error> { |
| 571 |
files |
| 572 |
.into_iter() |
| 573 |
.map(|(arg, refs)| { |
| 574 |
self.file_list_values(refs).map(|values| ValueList { |
| 575 |
arg: arg.into_pat(), |
| 576 |
values, |
| 577 |
}) |
| 578 |
}) |
| 579 |
.collect::<Result<Vec<ValueList>, _>>() |
| 580 |
} |
| 581 |
|
| 582 |
fn file_list_values(&self, refs: FilesGlobReferences) -> Result<Vec<Value>, syn::Error> { |
| 583 |
let default_base_dir = self |
| 584 |
.base_dir |
| 585 |
.base_dir() |
| 586 |
.map_err(|msg| refs.glob[0].error(&msg))?; |
| 587 |
|
| 588 |
let base_dir = match refs.base_dir()? { |
| 589 |
Some(p) if p.is_relative() => default_base_dir.join(p), |
| 590 |
Some(p) => p, |
| 591 |
None => default_base_dir, |
| 592 |
}; |
| 593 |
|
| 594 |
let base_dir = match base_dir.canonicalize() { |
| 595 |
Ok(base_dir) => base_dir, |
| 596 |
Err(e) if e.kind() == std::io::ErrorKind::NotFound => base_dir, |
| 597 |
Err(e) => { |
| 598 |
let msg = format!("Cannot canonicalize base dir {base_dir:?}: {e}"); |
| 599 |
return Err(refs.glob[0].error(&msg)); |
| 600 |
} |
| 601 |
}; |
| 602 |
|
| 603 |
let resolved_paths = refs.paths(&base_dir)?; |
| 604 |
|
| 605 |
let mut values: Vec<(Expr, String)> = vec![]; |
| 606 |
for (attr, abs_path) in self.all_files_path(resolved_paths)? { |
| 607 |
let relative_path = abs_path.relative_to(&base_dir).map_err(|e| { |
| 608 |
attr.error(&format!( |
| 609 |
"Cannot make {} relative to {}: {e}", |
| 610 |
abs_path.display(), |
| 611 |
base_dir.display() |
| 612 |
)) |
| 613 |
})?; |
| 614 |
|
| 615 |
if (refs.ignore_directories && abs_path.is_dir()) || !refs.is_valid(&relative_path) { |
| 616 |
continue; |
| 617 |
} |
| 618 |
|
| 619 |
let path_str = abs_path.to_string_lossy(); |
| 620 |
let value = match refs.files_mode { |
| 621 |
FilesMode::Path => parse_quote! { |
| 622 |
<::std::path::PathBuf as std::str::FromStr>::from_str(#path_str).unwrap() |
| 623 |
}, |
| 624 |
FilesMode::IncludeStr => parse_quote! { |
| 625 |
include_str!(#path_str) |
| 626 |
}, |
| 627 |
FilesMode::IncludeBytes => parse_quote! { |
| 628 |
include_bytes!(#path_str) |
| 629 |
}, |
| 630 |
}; |
| 631 |
values.push((value, render_file_description(&relative_path))); |
| 632 |
} |
| 633 |
|
| 634 |
if values.is_empty() { |
| 635 |
Err(refs.glob[0].error("No file found"))?; |
| 636 |
} |
| 637 |
|
| 638 |
Ok(values |
| 639 |
.into_iter() |
| 640 |
.map(|(e, desc)| Value::new(e, Some(desc))) |
| 641 |
.collect()) |
| 642 |
} |
| 643 |
|
| 644 |
/// Return the tuples of attribute, file path resolved via glob resolver, sorted by path and without duplications. |
| 645 |
fn all_files_path<'b>( |
| 646 |
&self, |
| 647 |
resolved_paths: Vec<(&'b LitStrAttr, String)>, |
| 648 |
) -> Result<Vec<(&'b LitStrAttr, PathBuf)>, syn::Error> { |
| 649 |
let mut paths = resolved_paths |
| 650 |
.iter() |
| 651 |
.map(|(attr, pattern)| { |
| 652 |
self.g_resolver |
| 653 |
.glob(pattern.as_ref()) |
| 654 |
.map_err(|msg| attr.error(&msg)) |
| 655 |
.map(|p| (attr, p)) |
| 656 |
}) |
| 657 |
.collect::<Result<Vec<_>, _>>()? |
| 658 |
.into_iter() |
| 659 |
.flat_map(|(&attr, inner)| inner.into_iter().map(move |p| (attr, p))) |
| 660 |
.collect::<Vec<_>>(); |
| 661 |
paths.sort_by(|(_, a), (_, b)| a.cmp(b)); |
| 662 |
paths.dedup_by(|(_, a), (_, b)| a.eq(&b)); |
| 663 |
Ok(paths) |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
fn render_file_description(file: &RelativePath) -> String { |
| 668 |
let mut description = String::new(); |
| 669 |
for c in file.components() { |
| 670 |
match c { |
| 671 |
relative_path::Component::CurDir => continue, |
| 672 |
relative_path::Component::ParentDir => description.push_str("_UP"), |
| 673 |
relative_path::Component::Normal(segment) => description.push_str(segment), |
| 674 |
} |
| 675 |
description.push('/') |
| 676 |
} |
| 677 |
description.pop(); |
| 678 |
description |
| 679 |
} |
| 680 |
|
| 681 |
#[cfg(test)] |
| 682 |
mod should { |
| 683 |
use std::collections::HashMap; |
| 684 |
|
| 685 |
use super::*; |
| 686 |
use crate::test::{assert_eq, *}; |
| 687 |
use maplit::hashmap; |
| 688 |
use rstest_test::assert_in; |
| 689 |
|
| 690 |
fn lit_str_attr(name: &str, value: impl AsRef<str>) -> LitStrAttr { |
| 691 |
attrs(&format!(r#"#[{name}("{}")]"#, value.as_ref())) |
| 692 |
.into_iter() |
| 693 |
.next() |
| 694 |
.unwrap() |
| 695 |
.try_into() |
| 696 |
.unwrap() |
| 697 |
} |
| 698 |
|
| 699 |
fn name_value_attr(name: &str, value: impl AsRef<str>) -> LitStrAttr { |
| 700 |
LitStrAttr::parse_meta_name_value( |
| 701 |
&attrs(&format!(r#"#[{name} = "{}"]"#, value.as_ref())) |
| 702 |
.into_iter() |
| 703 |
.next() |
| 704 |
.unwrap(), |
| 705 |
) |
| 706 |
.expect("Could not parse attribute") |
| 707 |
} |
| 708 |
|
| 709 |
fn files_attr(lstr: impl AsRef<str>) -> LitStrAttr { |
| 710 |
lit_str_attr("files", lstr) |
| 711 |
} |
| 712 |
|
| 713 |
fn base_dir_attr(lstr: impl AsRef<str>) -> LitStrAttr { |
| 714 |
name_value_attr("base_dir", lstr) |
| 715 |
} |
| 716 |
|
| 717 |
fn exclude_attr(lstr: impl AsRef<str>) -> LitStrAttr { |
| 718 |
lit_str_attr("exclude", lstr) |
| 719 |
} |
| 720 |
|
| 721 |
impl Exclude { |
| 722 |
fn fake(value: &str, r: Option<Regex>) -> Self { |
| 723 |
let r = r.unwrap_or_else(|| regex::Regex::new(value).unwrap()); |
| 724 |
Self { |
| 725 |
attr: exclude_attr(value), |
| 726 |
r, |
| 727 |
} |
| 728 |
} |
| 729 |
} |
| 730 |
|
| 731 |
impl From<&str> for Exclude { |
| 732 |
fn from(value: &str) -> Self { |
| 733 |
Self { |
| 734 |
attr: exclude_attr(value), |
| 735 |
r: Regex::new(value).unwrap(), |
| 736 |
} |
| 737 |
} |
| 738 |
} |
| 739 |
|
| 740 |
#[rstest] |
| 741 |
#[case::simple(r#"fn f(#[files("some_glob")] a: PathBuf) {}"#, "fn f(a: PathBuf) {}", &[("a", None, &["some_glob"], &[], true, true, false)])] |
| 742 |
#[case::more_than_one( |
| 743 |
r#"fn f(#[files("first")] a: PathBuf, b: u32, #[files("third")] c: PathBuf) {}"#, |
| 744 |
r#"fn f(a: PathBuf, |
| 745 |
b: u32, |
| 746 |
c: PathBuf) {}"#, |
| 747 |
&[("a", None, &["first"], &[], true, true, false), ("c", None, &["third"], &[], true, true, false)], |
| 748 |
)] |
| 749 |
#[case::more_globs_on_the_same_var( |
| 750 |
r#"fn f(#[files("first")] #[files("second")] a: PathBuf) {}"#, |
| 751 |
r#"fn f(a: PathBuf) {}"#, |
| 752 |
&[("a", None, &["first", "second"], &[], true, true, false)], |
| 753 |
)] |
| 754 |
#[case::exclude(r#"fn f(#[files("some_glob")] #[exclude("exclude")] a: PathBuf) {}"#, |
| 755 |
"fn f(a: PathBuf) {}", &[("a", None, &["some_glob"], &["exclude"], true, true, false)])] |
| 756 |
#[case::exclude_more(r#"fn f(#[files("some_glob")] #[exclude("first")] #[exclude("second")] a: PathBuf) {}"#, |
| 757 |
"fn f(a: PathBuf) {}", &[("a", None, &["some_glob"], &["first", "second"], true, true, false)])] |
| 758 |
#[case::include_dot_files(r#"fn f(#[files("some_glob")] #[include_dot_files] a: PathBuf) {}"#, |
| 759 |
"fn f(a: PathBuf) {}", &[("a", None, &["some_glob"], &[], true, false, false)])] |
| 760 |
#[case::base_dir(r#"fn f(#[files("some_glob")] #[base_dir = "/base/"] a: PathBuf) {}"#, |
| 761 |
"fn f(a: PathBuf) {}", &[("a", Some("/base/"), &["some_glob"], &[], true, true, false)])] |
| 762 |
#[case::ignore_env_vars(r#"fn f(#[files("some_glob")] #[ignore_missing_env_vars] a: PathBuf) {}"#, |
| 763 |
"fn f(a: PathBuf) {}", &[("a", None, &["some_glob"], &[], true, true, true)])] |
| 764 |
#[case::ignore_env_vars_unknown(r#"fn f(#[files("some${SOME_VAR}_glob")] #[ignore_missing_env_vars] a: PathBuf) {}"#, |
| 765 |
"fn f(a: PathBuf) {}", &[("a", None, &["some${SOME_VAR}_glob"], &[], true, true, true)])] |
| 766 |
#[case::ignore_directories(r#"fn f(#[files("some_glob")] #[dirs] a: PathBuf) {}"#, |
| 767 |
"fn f(a: PathBuf) {}", &[("a", None, &["some_glob"], &[], false, true, false)])] |
| 768 |
#[case::env_vars_default(r#"fn f(#[files("some${__UNKNOWN__:-default/value}_glob")] a: PathBuf) {}"#, |
| 769 |
"fn f(a: PathBuf) {}", &[("a", None, &["some${__UNKNOWN__:-default/value}_glob"], &[], true, true, false)])] |
| 770 |
fn extract<'a, G: AsRef<[&'a str]>, E: AsRef<[&'a str]>>( |
| 771 |
#[case] item_fn: &str, |
| 772 |
#[case] expected: &str, |
| 773 |
#[case] expected_files: &[(&str, Option<&str>, G, E, bool, bool, bool)], |
| 774 |
) { |
| 775 |
let mut item_fn: ItemFn = item_fn.ast(); |
| 776 |
let expected: ItemFn = expected.ast(); |
| 777 |
|
| 778 |
let files = extract_files(&mut item_fn).unwrap(); |
| 779 |
|
| 780 |
assert_eq!(expected, item_fn); |
| 781 |
assert_eq!( |
| 782 |
files, |
| 783 |
expected_files |
| 784 |
.into_iter() |
| 785 |
.map(|(id, base_dir, globs, ex, ignore_dirs, ignore, ignore_envvars)| { |
| 786 |
( |
| 787 |
ident(id), |
| 788 |
FilesGlobReferences::new( |
| 789 |
globs.as_ref().iter().map(files_attr).collect(), |
| 790 |
ex.as_ref().iter().map(|&ex| ex.into()).collect(), |
| 791 |
*ignore_dirs, |
| 792 |
*ignore, |
| 793 |
*ignore_envvars, |
| 794 |
Default::default(), |
| 795 |
) |
| 796 |
.with_base_dir_opt(base_dir.map(base_dir_attr)), |
| 797 |
) |
| 798 |
}) |
| 799 |
.collect::<Vec<_>>() |
| 800 |
); |
| 801 |
} |
| 802 |
|
| 803 |
#[rstest] |
| 804 |
#[case::no_files_arg("fn f(#[files] a: PathBuf) {}", "#[files(...)]")] |
| 805 |
#[case::invalid_files_inner("fn f(#[files(a::b::c)] a: PathBuf) {}", "string literal")] |
| 806 |
#[case::no_exclude_args( |
| 807 |
r#"fn f(#[files("some")] #[exclude] a: PathBuf) {}"#, |
| 808 |
"#[exclude(...)]" |
| 809 |
)] |
| 810 |
#[case::invalid_exclude_inner( |
| 811 |
r#"fn f(#[files("some")] #[exclude(a::b)] a: PathBuf) {}"#, |
| 812 |
"string literal" |
| 813 |
)] |
| 814 |
#[case::invalid_exclude_regex( |
| 815 |
r#"fn f(#[files("some")] #[exclude("invalid(reg(ex")] a: PathBuf) {}"#, |
| 816 |
"valid regex" |
| 817 |
)] |
| 818 |
#[case::include_dot_files_with_args( |
| 819 |
r#"fn f(#[files("some")] #[include_dot_files(some)] a: PathBuf) {}"#, |
| 820 |
"#[include_dot_files]" |
| 821 |
)] |
| 822 |
#[case::exclude_without_files( |
| 823 |
r#"fn f(#[exclude("some")] a: PathBuf) {}"#, |
| 824 |
"#[exclude(...)] without #[files(...)]" |
| 825 |
)] |
| 826 |
#[case::include_dot_files_without_files( |
| 827 |
r#"fn f(#[include_dot_files] a: PathBuf) {}"#, |
| 828 |
"#[include_dot_files] without #[files(...)]" |
| 829 |
)] |
| 830 |
#[case::include_dot_files_more_than_once( |
| 831 |
r#"fn f(#[files("some")] #[include_dot_files] #[include_dot_files] a: PathBuf) {}"#, |
| 832 |
"more than once" |
| 833 |
)] |
| 834 |
#[case::dirs_without_files( |
| 835 |
r#"fn f(#[dirs] a: PathBuf) {}"#, |
| 836 |
"#[dirs] without #[files(...)]" |
| 837 |
)] |
| 838 |
#[case::dirs_more_than_once( |
| 839 |
r#"fn f(#[files("some")] #[dirs] #[dirs] a: PathBuf) {}"#, |
| 840 |
"more than once" |
| 841 |
)] |
| 842 |
#[case::ignore_missing_env_vars_without_files( |
| 843 |
r#"fn f(#[ignore_missing_env_vars] a: PathBuf) {}"#, |
| 844 |
"#[ignore_missing_env_vars] without #[files(...)]" |
| 845 |
)] |
| 846 |
#[case::ignore_missing_env_vars_more_than_once( |
| 847 |
r#"fn f(#[files("some")] #[ignore_missing_env_vars] #[ignore_missing_env_vars] a: PathBuf) {}"#, |
| 848 |
"more than once" |
| 849 |
)] |
| 850 |
#[case::override_base_dir_more_than_once( |
| 851 |
r#"fn f(#[files("some")] #[base_dir = "/"] #[base_dir = "/"] a: PathBuf) {}"#, |
| 852 |
"more than once" |
| 853 |
)] |
| 854 |
#[case::invalid_base_dir( |
| 855 |
r#"fn f(#[files("some")] #[base_dir = 123] a: PathBuf) {}"#, |
| 856 |
"base directory for the glob path" |
| 857 |
)] |
| 858 |
#[case::multiple_file_modes( |
| 859 |
r#"fn f(#[files("some")] #[mode = str] #[mode = str] a: PathBuf) {}"#, |
| 860 |
r#"Cannot use #[mode = ...] more than once"# |
| 861 |
)] |
| 862 |
#[case::unknown_file_mode( |
| 863 |
r#"fn f(#[files("some")] #[mode = blabla] a: PathBuf) {}"#, |
| 864 |
r#"Expected one of the following keywords: path, str or bytes"# |
| 865 |
)] |
| 866 |
#[case::wrong_attr_file_mode( |
| 867 |
r#"fn f(#[files("some")] #[mode(blabla)] a: PathBuf) {}"#, |
| 868 |
"Use #[mode = ...] to define the argument of the file input" |
| 869 |
)] |
| 870 |
fn raise_error(#[case] item_fn: &str, #[case] message: &str) { |
| 871 |
let mut item_fn: ItemFn = item_fn.ast(); |
| 872 |
|
| 873 |
let err = extract_files(&mut item_fn).unwrap_err(); |
| 874 |
|
| 875 |
assert_in!(format!("{:?}", err), message); |
| 876 |
} |
| 877 |
|
| 878 |
#[rstest] |
| 879 |
#[case::unknown_env_var( |
| 880 |
r#"fn f(#[files("so${__UNKNOWN__}me")] a: PathBuf) {}"#, |
| 881 |
"Could not find the environment variable \\\"__UNKNOWN__\\\"" |
| 882 |
)] |
| 883 |
#[case::invalid_env_var( |
| 884 |
r#"fn f(#[files("so${__INVALID%%__}me")] a: PathBuf) {}"#, |
| 885 |
"The variable \\\"__INVALID%%__\\\" name does not match [a-zA-Z0-9_]+" |
| 886 |
)] |
| 887 |
#[case::base_dir_unknown_env_var( |
| 888 |
r#"fn f(#[base_dir = "${__UNKNOWN__}"] #[files("some")] a: PathBuf) {}"#, |
| 889 |
"Could not find the environment variable \\\"__UNKNOWN__\\\"" |
| 890 |
)] |
| 891 |
fn raise_error_on_paths(#[case] item_fn: &str, #[case] message: &str) { |
| 892 |
let mut item_fn: ItemFn = item_fn.ast(); |
| 893 |
|
| 894 |
let ok = extract_files(&mut item_fn).unwrap(); |
| 895 |
let err: syn::Error = ok |
| 896 |
.into_iter() |
| 897 |
.map(|(_id, refs)| { |
| 898 |
let base_dir = refs.base_dir()?; |
| 899 |
let x = refs.paths(base_dir.as_ref().unwrap_or(&PathBuf::from("/default")))?; |
| 900 |
eprintln!("x {:?}", x); |
| 901 |
Ok(()) |
| 902 |
}) |
| 903 |
.collect::<Result<(), _>>() |
| 904 |
.unwrap_err(); |
| 905 |
|
| 906 |
assert_in!(format!("{:?}", err), message); |
| 907 |
} |
| 908 |
|
| 909 |
#[derive(Default)] |
| 910 |
struct FakeBaseDir(PathBuf); |
| 911 |
impl From<&str> for FakeBaseDir { |
| 912 |
fn from(value: &str) -> Self { |
| 913 |
Self(PathBuf::from(value)) |
| 914 |
} |
| 915 |
} |
| 916 |
impl BaseDir for FakeBaseDir { |
| 917 |
fn base_dir(&self) -> Result<PathBuf, String> { |
| 918 |
Ok(self.0.clone()) |
| 919 |
} |
| 920 |
} |
| 921 |
|
| 922 |
impl<'a> ValueListFromFiles<'a> { |
| 923 |
fn new(bdir: impl BaseDir + 'a, g_resover: impl GlobResolver + 'a) -> Self { |
| 924 |
Self { |
| 925 |
base_dir: Box::new(bdir), |
| 926 |
g_resolver: Box::new(g_resover), |
| 927 |
} |
| 928 |
} |
| 929 |
} |
| 930 |
|
| 931 |
#[derive(Default)] |
| 932 |
struct FakeResolver(Vec<String>); |
| 933 |
|
| 934 |
impl From<&[&str]> for FakeResolver { |
| 935 |
fn from(value: &[&str]) -> Self { |
| 936 |
Self(value.iter().map(ToString::to_string).collect()) |
| 937 |
} |
| 938 |
} |
| 939 |
|
| 940 |
impl GlobResolver for FakeResolver { |
| 941 |
fn glob(&self, _pattern: &str) -> Result<Vec<PathBuf>, String> { |
| 942 |
Ok(self.0.iter().map(PathBuf::from).collect()) |
| 943 |
} |
| 944 |
} |
| 945 |
|
| 946 |
#[derive(Default)] |
| 947 |
struct FakeMapResolver(String, HashMap<String, Vec<PathBuf>>); |
| 948 |
|
| 949 |
impl From<(&str, &HashMap<&str, &[&str]>)> for FakeMapResolver { |
| 950 |
fn from(value: (&str, &HashMap<&str, &[&str]>)) -> Self { |
| 951 |
Self( |
| 952 |
value.0.to_string(), |
| 953 |
value |
| 954 |
.1 |
| 955 |
.iter() |
| 956 |
.map(|(&key, &values)| { |
| 957 |
( |
| 958 |
key.to_string(), |
| 959 |
values |
| 960 |
.iter() |
| 961 |
.map(|&v| PathBuf::from(format!("{}/{v}", value.0))) |
| 962 |
.collect::<Vec<_>>(), |
| 963 |
) |
| 964 |
}) |
| 965 |
.collect(), |
| 966 |
) |
| 967 |
} |
| 968 |
} |
| 969 |
|
| 970 |
impl GlobResolver for FakeMapResolver { |
| 971 |
fn glob(&self, pattern: &str) -> Result<Vec<PathBuf>, String> { |
| 972 |
let pattern = pattern |
| 973 |
.strip_prefix(&format!("{}{}", self.0, std::path::MAIN_SEPARATOR)) |
| 974 |
.unwrap(); |
| 975 |
Ok(self.1.get(pattern).cloned().unwrap_or_default()) |
| 976 |
} |
| 977 |
} |
| 978 |
|
| 979 |
#[rstest] |
| 980 |
#[case::simple("/base", None, FakeResolver::from(["/base/first", "/base/second"].as_slice()), vec![], true, &["first", "second"])] |
| 981 |
#[case::more_glob("/base", Some(["path1", "path2"].as_slice()), FakeMapResolver::from( |
| 982 |
("/base", &hashmap!( |
| 983 |
"path1" => ["first", "second"].as_slice(), |
| 984 |
"path2" => ["third", "zzzz"].as_slice() |
| 985 |
)) |
| 986 |
), vec![], true, &["first", "second", "third", "zzzz"])] |
| 987 |
#[case::should_remove_duplicates("/base", Some(["path1", "path2"].as_slice()), FakeMapResolver::from( |
| 988 |
("/base", &hashmap!( |
| 989 |
"path1" => ["first", "second"].as_slice(), |
| 990 |
"path2" => ["second", "third"].as_slice() |
| 991 |
)) |
| 992 |
), vec![], true, &["first", "second", "third"])] |
| 993 |
#[case::should_sort("/base", None, FakeResolver::from(["/base/second", "/base/first"].as_slice()), vec![], true, &["first", "second"])] |
| 994 |
#[case::exclude("/base", None, FakeResolver::from([ |
| 995 |
"/base/first", "/base/rem_1", "/base/other/rem_2", "/base/second"].as_slice()), |
| 996 |
vec![Exclude::fake("no_mater", Some(Regex::new("rem_").unwrap()))], true, &["first", "second"])] |
| 997 |
#[case::exclude_more("/base", None, FakeResolver::from([ |
| 998 |
"/base/first", "/base/rem_1", "/base/other/rem_2", "/base/some/other", "/base/second"].as_slice()), |
| 999 |
vec![ |
| 1000 |
Exclude::fake("no_mater", Some(Regex::new("rem_").unwrap())), |
| 1001 |
Exclude::fake("no_mater", Some(Regex::new("some").unwrap())), |
| 1002 |
], true, &["first", "second"])] |
| 1003 |
#[case::ignore_dot_files("/base", None, FakeResolver::from([ |
| 1004 |
"/base/first", "/base/.ignore", "/base/.ignore_dir/a", "/base/second/.not", "/base/second/but_include", "/base/in/.out/other/ignored"].as_slice()), |
| 1005 |
vec![], true, &["first", "second/but_include"])] |
| 1006 |
#[case::include_dot_files("/base", None, FakeResolver::from([ |
| 1007 |
"/base/first", "/base/.ignore", "/base/.ignore_dir/a", "/base/second/.not", "/base/second/but_include", "/base/in/.out/other/ignored"].as_slice()), |
| 1008 |
vec![], false, &[".ignore", ".ignore_dir/a", "first", "in/.out/other/ignored", "second/.not", "second/but_include"])] |
| 1009 |
#[case::relative_path("/base/some/other/folders", None, |
| 1010 |
FakeResolver::from(["/base/first", "/base/second"].as_slice()), vec![], true, &["../../../first", "../../../second"])] |
| 1011 |
fn generate_a_variable_with_the_glob_resolved_path( |
| 1012 |
#[case] bdir: &str, |
| 1013 |
#[case] paths: Option<&[&str]>, |
| 1014 |
#[case] resolver: impl GlobResolver, |
| 1015 |
#[case] exclude: Vec<Exclude>, |
| 1016 |
#[case] ignore_dot_files: bool, |
| 1017 |
#[case] expected: &[&str], |
| 1018 |
) { |
| 1019 |
let paths = paths |
| 1020 |
.map(|inner| inner.into_iter().map(files_attr).collect()) |
| 1021 |
.unwrap_or(vec![files_attr("no_mater")]); |
| 1022 |
let values = ValueListFromFiles::new(FakeBaseDir::from(bdir), resolver) |
| 1023 |
.to_value_list(vec![( |
| 1024 |
ident("a"), |
| 1025 |
FilesGlobReferences::new( |
| 1026 |
paths, |
| 1027 |
exclude, |
| 1028 |
true, |
| 1029 |
ignore_dot_files, |
| 1030 |
false, |
| 1031 |
Default::default(), |
| 1032 |
), |
| 1033 |
)]) |
| 1034 |
.unwrap(); |
| 1035 |
|
| 1036 |
let mut v_list = values_list( |
| 1037 |
"a", |
| 1038 |
&expected |
| 1039 |
.iter() |
| 1040 |
.map(|&p| RelativePath::from_path(p).unwrap()) |
| 1041 |
.map(|r| r.to_logical_path(bdir)) |
| 1042 |
.map(|p| { |
| 1043 |
let p = p.as_os_str().to_str().unwrap(); |
| 1044 |
#[cfg(windows)] |
| 1045 |
let p = p.replace('\\', "/"); |
| 1046 |
format!( |
| 1047 |
r#"<::std::path::PathBuf as std::str::FromStr>::from_str("{p}").unwrap()"#, |
| 1048 |
) |
| 1049 |
}) |
| 1050 |
.collect::<Vec<_>>(), |
| 1051 |
); |
| 1052 |
v_list |
| 1053 |
.values |
| 1054 |
.iter_mut() |
| 1055 |
.zip(expected.iter()) |
| 1056 |
.for_each(|(v, &ex)| { |
| 1057 |
v.description = Some(render_file_description( |
| 1058 |
&RelativePath::from_path(ex).unwrap(), |
| 1059 |
)) |
| 1060 |
}); |
| 1061 |
assert_eq!(vec![v_list], values); |
| 1062 |
} |
| 1063 |
|
| 1064 |
#[rstest] |
| 1065 |
#[case::file("name.txt", "name.txt")] |
| 1066 |
#[case::in_folder("some/folder/name.txt", "some/folder/name.txt")] |
| 1067 |
#[case::no_extension("name", "name")] |
| 1068 |
#[case::parent("../../name.txt", "_UP/_UP/name.txt")] |
| 1069 |
#[case::ignore_current("./../other/name.txt", "_UP/other/name.txt")] |
| 1070 |
fn render_file_description_should(#[case] path: &str, #[case] expected: &str) { |
| 1071 |
assert_eq!( |
| 1072 |
render_file_description(&RelativePath::from_path(path).unwrap()), |
| 1073 |
expected |
| 1074 |
); |
| 1075 |
} |
| 1076 |
|
| 1077 |
#[test] |
| 1078 |
#[should_panic(expected = "Fake error")] |
| 1079 |
fn raise_error_if_fail_to_get_root() { |
| 1080 |
#[derive(Default)] |
| 1081 |
struct ErrorBaseDir; |
| 1082 |
impl BaseDir for ErrorBaseDir { |
| 1083 |
fn base_dir(&self) -> Result<PathBuf, String> { |
| 1084 |
Err("Fake error".to_string()) |
| 1085 |
} |
| 1086 |
} |
| 1087 |
|
| 1088 |
ValueListFromFiles::new(ErrorBaseDir::default(), FakeResolver::default()) |
| 1089 |
.to_value_list(vec![( |
| 1090 |
ident("a"), |
| 1091 |
FilesGlobReferences::new( |
| 1092 |
vec![files_attr("no_mater")], |
| 1093 |
Default::default(), |
| 1094 |
true, |
| 1095 |
true, |
| 1096 |
false, |
| 1097 |
Default::default(), |
| 1098 |
), |
| 1099 |
)]) |
| 1100 |
.unwrap(); |
| 1101 |
} |
| 1102 |
|
| 1103 |
#[test] |
| 1104 |
#[should_panic(expected = "No file found")] |
| 1105 |
fn raise_error_if_no_files_found() { |
| 1106 |
ValueListFromFiles::new(FakeBaseDir::default(), FakeResolver::default()) |
| 1107 |
.to_value_list(vec![( |
| 1108 |
ident("a"), |
| 1109 |
FilesGlobReferences::new( |
| 1110 |
vec![files_attr("no_mater")], |
| 1111 |
Default::default(), |
| 1112 |
true, |
| 1113 |
true, |
| 1114 |
false, |
| 1115 |
Default::default(), |
| 1116 |
), |
| 1117 |
)]) |
| 1118 |
.unwrap(); |
| 1119 |
} |
| 1120 |
|
| 1121 |
#[test] |
| 1122 |
#[should_panic(expected = "glob failed")] |
| 1123 |
fn default_glob_resolver_raise_error_if_invalid_glob_path() { |
| 1124 |
DefaultGlobResolver.glob("/invalid/path/***").unwrap(); |
| 1125 |
} |
| 1126 |
|
| 1127 |
struct MapEnvironmentResolver(HashMap<String, String>); |
| 1128 |
|
| 1129 |
impl EnvironmentResolver for MapEnvironmentResolver { |
| 1130 |
fn get(&self, var: &str) -> Option<String> { |
| 1131 |
self.0.get(var).cloned() |
| 1132 |
} |
| 1133 |
} |
| 1134 |
|
| 1135 |
#[rstest] |
| 1136 |
#[case::works(&[("VALUE", "VVV")], false, "some${VALUE}_glob", Ok("someVVV_glob"))] |
| 1137 |
#[case::works_simple(&[("VALUE", "VVV")], false, "some/$VALUE/glob", Ok("some/VVV/glob"))] |
| 1138 |
#[case::unknown_err(&[], false, "some${__UNKNOWN__}_glob", Err("__UNKNOWN__"))] |
| 1139 |
#[case::ignore_unknown(&[], true, "some${__UNKNOWN__}_glob", Ok("some_glob"))] |
| 1140 |
#[case::invalid(&[], false, "some${__%$!@__}_glob", Err("__%$!@__"))] |
| 1141 |
#[case::default_unknown(&[], false, "some${__UNKNOWN__:-VVV}_glob", Ok("someVVV_glob"))] |
| 1142 |
#[case::default_empty(&[("EMPTY", "")], false, "some${EMPTY:-EEE}_glob", Ok("someEEE_glob"))] |
| 1143 |
fn replace_env_vars( |
| 1144 |
#[case] env_vars: &[(&str, &str)], |
| 1145 |
#[case] ignore_missing_env_vars: bool, |
| 1146 |
#[case] glob: &str, |
| 1147 |
#[case] expected: Result<&str, &str>, |
| 1148 |
) { |
| 1149 |
let resolver = MapEnvironmentResolver( |
| 1150 |
env_vars |
| 1151 |
.iter() |
| 1152 |
.map(|(k, v)| (k.to_string(), v.to_string())) |
| 1153 |
.collect(), |
| 1154 |
); |
| 1155 |
let refs = FilesGlobReferences::new( |
| 1156 |
vec![], |
| 1157 |
Default::default(), |
| 1158 |
true, |
| 1159 |
true, |
| 1160 |
ignore_missing_env_vars, |
| 1161 |
Default::default(), |
| 1162 |
); |
| 1163 |
|
| 1164 |
let result = refs.replace_env_vars(&files_attr(glob), resolver); |
| 1165 |
match (&result, expected) { |
| 1166 |
(Ok(r), Ok(e)) => assert_eq!(r, e), |
| 1167 |
(Err(r), Err(e)) => assert_in!(format!("{:?}", r), e), |
| 1168 |
_ => panic!( |
| 1169 |
"Expected and result should be the same. Expected: {:?}, Result: {:?}", |
| 1170 |
expected, result |
| 1171 |
), |
| 1172 |
} |
| 1173 |
} |
| 1174 |
} |