Refactor magic trailing comma (#5339)

## Summary

This is small refactoring to reuse the code that detects the magic
trailing comma across functions. I make this change now to avoid copying
code in a later PR. @MichaReiser is planning on making a larger
refactoring later that integrates with the join nodes builder

## Test Plan

No functional changes. The magic trailing comma behaviour is checked by
the fixtures.
This commit is contained in:
konstin 2023-06-23 18:53:55 +02:00 committed by GitHub
parent cb580f960f
commit 4b65446de6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 28 additions and 42 deletions

View file

@ -1,8 +1,9 @@
use crate::context::NodeLevel;
use crate::prelude::*;
use crate::trivia::{lines_after, skip_trailing_trivia};
use crate::trivia::{first_non_trivia_token, lines_after, skip_trailing_trivia, Token, TokenKind};
use crate::USE_MAGIC_TRAILING_COMMA;
use ruff_formatter::write;
use ruff_text_size::TextSize;
use ruff_text_size::{TextRange, TextSize};
use rustpython_parser::ast::Ranged;
/// Provides Python specific extensions to [`Formatter`].
@ -145,6 +146,17 @@ impl<'fmt, 'ast, 'buf> JoinNodesBuilder<'fmt, 'ast, 'buf> {
}
}
pub(crate) fn use_magic_trailing_comma(f: &mut PyFormatter, range: TextRange) -> bool {
USE_MAGIC_TRAILING_COMMA
&& matches!(
first_non_trivia_token(range.end(), f.context().contents()),
Some(Token {
kind: TokenKind::Comma,
..
})
)
}
#[cfg(test)]
mod tests {
use crate::comments::Comments;