Skip to content

Commit

Permalink
feat: forbid usage of many WildcardGroup::Fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
l4l committed Oct 22, 2023
1 parent 1f9350c commit f43dc9a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
1 change: 1 addition & 0 deletions Configurations.md
Original file line number Diff line number Diff line change
Expand Up @@ -2301,6 +2301,7 @@ Handy aliases are supported:

- `$std` prefix is an alias for standard library (i.e `std`, `core`, `alloc`);
- `$crate` prefix is an alias for crate-local modules (i.e `self`, `crate`, `super`).
- `*` is a special fallback group (i.e used if no other group matches), could only be specified once.

For a given config:

Expand Down
33 changes: 27 additions & 6 deletions src/config/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,13 +190,27 @@ impl<'de> Deserialize<'de> for GroupImportsTactic {
lines.push(elem);
}

lines
let value = lines
.into_iter()
.map(TryFrom::try_from)
.collect::<Result<Vec<_>, _>>()
.map(WildcardGroups)
.map(GroupImportsTactic::Wildcards)
.map_err(serde::de::Error::custom)
.map_err(serde::de::Error::custom)?;

if value
.0
.iter()
.filter(|g| matches!(g, WildcardGroup::Fallback))
.count()
> 1
{
return Err(serde::de::Error::custom(concat!(
"Wildcard format group must include at ",
"most one fallback (i.e \"*\") group."
)));
}

Ok(GroupImportsTactic::Wildcards(value))
}
}

Expand Down Expand Up @@ -246,7 +260,7 @@ impl WildcardGroup {
}

impl TryFrom<Vec<String>> for WildcardGroup {
type Error = regex::Error;
type Error = anyhow::Error;

fn try_from(i: Vec<String>) -> Result<Self, Self::Error> {
enum Kind {
Expand All @@ -258,7 +272,14 @@ impl TryFrom<Vec<String>> for WildcardGroup {
return Ok(Self::Fallback);
}

i.into_iter()
if i.iter().any(|x| x == "*") {
return Err(anyhow::anyhow!(concat!(
"'*' is a special wildcard for a fallback group ",
"and could only be a single item within this group"
)));
}

Ok(i.into_iter()
.map(|s| {
let (s, kind) = if let Some(tail) = s.strip_prefix("$std") {
(tail, Some(Kind::Std))
Expand All @@ -279,7 +300,7 @@ impl TryFrom<Vec<String>> for WildcardGroup {
regex::Regex::new(&format!("^{wildcard}$"))
})
.collect::<Result<_, _>>()
.map(Self::Group)
.map(Self::Group)?)
}
}

Expand Down

0 comments on commit f43dc9a

Please sign in to comment.