Add autofix for F504 and F522 (#1184)

This commit is contained in:
Reiner Gerecke
2022-12-10 22:33:09 +01:00
committed by GitHub
parent 74668915b0
commit 06ed125771
10 changed files with 284 additions and 62 deletions

View File

@@ -1,3 +1,9 @@
use once_cell::sync::Lazy;
use regex::Regex;
pub static STRING_QUOTE_PREFIX_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"^(?i)[urb]*['"](?P<raw>.*)['"]$"#).unwrap());
pub fn is_lower(s: &str) -> bool {
let mut cased = false;
for c in s.chars() {
@@ -22,9 +28,22 @@ pub fn is_upper(s: &str) -> bool {
cased
}
/// Remove prefixes (u, r, b) and quotes around a string. This expects the given
/// string to be a valid Python string representation, it doesn't do any
/// validation.
pub fn strip_quotes_and_prefixes(s: &str) -> &str {
match STRING_QUOTE_PREFIX_REGEX.captures(s) {
Some(caps) => match caps.name("raw") {
Some(m) => m.as_str(),
None => s,
},
None => s,
}
}
#[cfg(test)]
mod tests {
use crate::python::string::{is_lower, is_upper};
use crate::python::string::{is_lower, is_upper, strip_quotes_and_prefixes};
#[test]
fn test_is_lower() {
@@ -47,4 +66,12 @@ mod tests {
assert!(!is_upper(""));
assert!(!is_upper("_"));
}
#[test]
fn test_strip_quotes_and_prefixes() {
assert_eq!(strip_quotes_and_prefixes(r#"'a'"#), "a");
assert_eq!(strip_quotes_and_prefixes(r#"bur'a'"#), "a");
assert_eq!(strip_quotes_and_prefixes(r#"UrB'a'"#), "a");
assert_eq!(strip_quotes_and_prefixes(r#""a""#), "a");
}
}