Extend UP032 to support repeated format fields (#6266)

This commit is contained in:
Harutaka Kawamura 2023-08-03 03:23:25 +09:00 committed by GitHub
parent 556abf4bd3
commit bcc41ba062
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 356 additions and 313 deletions

View file

@ -6,8 +6,12 @@
"{1} {0}".format(a, b)
"{0} {1} {0}".format(a, b)
"{x.y}".format(x=z)
"{x} {y} {x}".format(x=a, y=b)
"{.x} {.y}".format(a, b)
"{} {}".format(a.b, c.d)
@ -85,8 +89,6 @@ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
"{} {}".format(*a)
"{0} {0}".format(arg)
"{x} {x}".format(arg)
"{x.y} {x.z}".format(arg)

View file

@ -59,6 +59,7 @@ impl AlwaysAutofixableViolation for FString {
struct FormatSummaryValues<'a> {
args: Vec<&'a Expr>,
kwargs: FxHashMap<&'a str, &'a Expr>,
auto_index: usize,
}
impl<'a> FormatSummaryValues<'a> {
@ -102,27 +103,25 @@ impl<'a> FormatSummaryValues<'a> {
Some(Self {
args: extracted_args,
kwargs: extracted_kwargs,
auto_index: 0,
})
}
fn consume_next(&mut self) -> Option<&Expr> {
if self.args.is_empty() {
None
} else {
Some(self.args.remove(0))
}
/// Return the next positional argument.
fn arg_auto(&mut self) -> Option<&Expr> {
let idx = self.auto_index;
self.auto_index += 1;
self.arg_positional(idx)
}
fn consume_arg(&mut self, index: usize) -> Option<&Expr> {
if self.args.len() > index {
Some(self.args.remove(index))
} else {
None
}
/// Return the positional argument at the given index.
fn arg_positional(&self, index: usize) -> Option<&Expr> {
self.args.get(index).copied()
}
fn consume_kwarg(&mut self, key: &str) -> Option<&Expr> {
self.kwargs.remove(key)
/// Return the keyword argument with the given name.
fn arg_keyword(&self, key: &str) -> Option<&Expr> {
self.kwargs.get(key).copied()
}
}
@ -254,9 +253,9 @@ fn try_convert_to_f_string(expr: &Expr, locator: &Locator) -> Option<String> {
let field = FieldName::parse(&field_name).ok()?;
let arg = match field.field_type {
FieldType::Auto => summary.consume_next(),
FieldType::Index(index) => summary.consume_arg(index),
FieldType::Keyword(name) => summary.consume_kwarg(&name),
FieldType::Auto => summary.arg_auto(),
FieldType::Index(index) => summary.arg_positional(index),
FieldType::Keyword(name) => summary.arg_keyword(&name),
}?;
converted.push_str(&formatted_expr(
arg,