Skip to content

Commit

Permalink
Add PreviewMode option to formatter
Browse files Browse the repository at this point in the history
## Summary

This PR adds the `--preview` and `--no-preview` options to the `format` command (hidden) and passes it through to the formatte. 

## Test Plan

I added the `dbg(f.options().preview())` statement in `FormatNodeRule::fmt` and verified that the option gets correctly passed to the formatter.
  • Loading branch information
MichaReiser committed Sep 8, 2023
1 parent d9544a2 commit 47a253f
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 7 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions crates/ruff_cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,12 @@ pub struct FormatCommand {
/// The name of the file when passing it through stdin.
#[arg(long, help_heading = "Miscellaneous")]
pub stdin_filename: Option<PathBuf>,

/// Enable preview mode; checks will include unstable rules and fixes.
#[arg(long, overrides_with("no_preview"), hide = true)]
preview: bool,
#[clap(long, overrides_with("preview"), hide = true)]
no_preview: bool,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
Expand Down Expand Up @@ -496,6 +502,7 @@ impl FormatCommand {
self.respect_gitignore,
self.no_respect_gitignore,
),
preview: resolve_bool_arg(self.preview, self.no_preview).map(PreviewMode::from),
force_exclude: resolve_bool_arg(self.force_exclude, self.no_force_exclude),
// Unsupported on the formatter CLI, but required on `Overrides`.
..Overrides::default()
Expand Down
9 changes: 8 additions & 1 deletion crates/ruff_cli/src/commands/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use tracing::{debug, warn};

use ruff::fs;
use ruff::logging::LogLevel;
use ruff::settings::types::PreviewMode;
use ruff::warn_user_once;
use ruff_formatter::LineWidth;
use ruff_python_ast::{PySourceType, SourceType};
Expand Down Expand Up @@ -72,9 +73,15 @@ pub(crate) fn format(
return None;
};

let preview = match pyproject_config.settings.lib.preview {
PreviewMode::Enabled => ruff_python_formatter::PreviewMode::Enabled,
PreviewMode::Disabled => ruff_python_formatter::PreviewMode::Disabled,
};

let line_length = resolver.resolve(path, &pyproject_config).line_length;
let options = PyFormatOptions::from_source_type(source_type)
.with_line_width(LineWidth::from(NonZeroU16::from(line_length)));
.with_line_width(LineWidth::from(NonZeroU16::from(line_length)))
.with_preview(preview);
debug!("Formatting {} with {:?}", path.display(), options);
Some(format_path(path, options, mode))
}
Expand Down
1 change: 0 additions & 1 deletion crates/ruff_python_formatter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ anyhow = { workspace = true }
bitflags = { workspace = true }
clap = { workspace = true }
countme = "3.0.1"
is-macro = { workspace = true }
itertools = { workspace = true }
memchr = { workspace = true }
once_cell = { workspace = true }
Expand Down
12 changes: 9 additions & 3 deletions crates/ruff_python_formatter/src/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,10 +388,10 @@ fn can_omit_optional_parentheses(expr: &Expr, context: &PyFormatContext) -> bool
// Only use the layout if the first or last expression has parentheses of some sort, and
// those parentheses are non-empty.
let first_parenthesized = visitor.first.is_some_and(|first| {
has_parentheses(first, context).is_some_and(|parentheses| parentheses.is_non_empty())
has_parentheses(first, context).is_some_and(OwnParentheses::is_non_empty)
});
let last_parenthesized = visitor.last.is_some_and(|last| {
has_parentheses(last, context).is_some_and(|parentheses| parentheses.is_non_empty())
has_parentheses(last, context).is_some_and(OwnParentheses::is_non_empty)
});
first_parenthesized || last_parenthesized
}
Expand Down Expand Up @@ -706,14 +706,20 @@ impl CallChainLayout {
}
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, is_macro::Is)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum OwnParentheses {
/// The node has parentheses, but they are empty (e.g., `[]` or `f()`).
Empty,
/// The node has parentheses, and they are non-empty (e.g., `[1]` or `f(1)`).
NonEmpty,
}

impl OwnParentheses {
const fn is_non_empty(self) -> bool {
matches!(self, OwnParentheses::NonEmpty)
}
}

/// Returns the [`OwnParentheses`] value for a given [`Expr`], to indicate whether it has its
/// own parentheses or is itself parenthesized.
///
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_python_formatter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::comments::{
dangling_comments, leading_comments, trailing_comments, Comments, SourceComment,
};
pub use crate::context::PyFormatContext;
pub use crate::options::{MagicTrailingComma, PyFormatOptions, QuoteStyle};
pub use crate::options::{MagicTrailingComma, PreviewMode, PyFormatOptions, QuoteStyle};
use crate::verbatim::suppressed_node;

pub(crate) mod builders;
Expand Down
29 changes: 29 additions & 0 deletions crates/ruff_python_formatter/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ pub struct PyFormatOptions {
/// Should the formatter generate a source map that allows mapping source positions to positions
/// in the formatted document.
source_map_generation: SourceMapGeneration,

/// Whether preview style formatting is enabled or not
preview: PreviewMode,
}

fn default_line_width() -> LineWidth {
Expand All @@ -64,6 +67,7 @@ impl Default for PyFormatOptions {
line_ending: LineEnding::default(),
magic_trailing_comma: MagicTrailingComma::default(),
source_map_generation: SourceMapGeneration::default(),
preview: PreviewMode::default(),
}
}
}
Expand Down Expand Up @@ -101,6 +105,10 @@ impl PyFormatOptions {
self.line_ending
}

pub fn preview(&self) -> PreviewMode {
self.preview
}

#[must_use]
pub fn with_tab_width(mut self, tab_width: TabWidth) -> Self {
self.tab_width = tab_width;
Expand Down Expand Up @@ -136,6 +144,12 @@ impl PyFormatOptions {
self.line_ending = line_ending;
self
}

#[must_use]
pub fn with_preview(mut self, preview: PreviewMode) -> Self {
self.preview = preview;
self
}
}

impl FormatOptions for PyFormatOptions {
Expand Down Expand Up @@ -246,3 +260,18 @@ impl FromStr for MagicTrailingComma {
}
}
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PreviewMode {
#[default]
Disabled,

Enabled,
}

impl PreviewMode {
pub const fn is_enabled(self) -> bool {
matches!(self, PreviewMode::Enabled)
}
}

0 comments on commit 47a253f

Please sign in to comment.