Skip to content

Commit

Permalink
Parenthesize multi-context managers
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaReiser committed Dec 21, 2023
1 parent c6d8076 commit 786a2e1
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 588 deletions.
9 changes: 9 additions & 0 deletions crates/ruff_python_formatter/src/preview.rs
Expand Up @@ -33,3 +33,12 @@ pub(crate) const fn is_no_blank_line_before_class_docstring_enabled(
) -> bool {
context.is_preview()
}

/// Returns `true` if the [`wrap_multiple_context_managers_in_parens`](https://github.com/astral-sh/ruff/issues/8889) preview style is enabled.
///
/// Unlike Black, we re-use the same preview style feature flag for [`improved_async_statements_handling`](https://github.com/astral-sh/ruff/issues/8890)
pub(crate) const fn is_wrap_multiple_context_managers_in_parens_enabled(
context: &PyFormatContext,
) -> bool {
context.is_preview()
}
17 changes: 13 additions & 4 deletions crates/ruff_python_formatter/src/statement/stmt_with.rs
Expand Up @@ -9,8 +9,9 @@ use crate::comments::SourceComment;
use crate::expression::parentheses::parenthesized;
use crate::other::commas;
use crate::prelude::*;
use crate::preview::is_wrap_multiple_context_managers_in_parens_enabled;
use crate::statement::clause::{clause_body, clause_header, ClauseHeader};
use crate::PyFormatOptions;
use crate::{PyFormatOptions, PythonVersion};

#[derive(Default)]
pub struct FormatStmtWith;
Expand Down Expand Up @@ -115,14 +116,22 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {

/// Returns `true` if the `with` items should be parenthesized, if at least one item expands.
///
/// Black parenthesizes `with` items if there's more than one item and they're already
/// parenthesized, _or_ there's a single item with a trailing comma.
/// Parenthesize `with` items if
/// * The last item has a trailing comma
/// * There's more than one item and they're already parenthesized
/// * There's more than one item and the target python version is >= 3.9
fn should_parenthesize(
with: &StmtWith,
options: &PyFormatOptions,
context: &PyFormatContext,
) -> FormatResult<bool> {
if has_magic_trailing_comma(with, options, context) {
if with.items.len() <= 1 {
return Ok(has_magic_trailing_comma(with, options, context));
}

if is_wrap_multiple_context_managers_in_parens_enabled(context)
&& options.target_version() >= PythonVersion::Py39
{
return Ok(true);
}

Expand Down

This file was deleted.

0 comments on commit 786a2e1

Please sign in to comment.