From 493f2c1c44cad81bd9624201c0d6a90f85d568ff Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Thu, 6 Jun 2024 16:06:31 +0100 Subject: [PATCH] chore: address feedback --- crates/biome_cli/src/commands/rage.rs | 6 +- crates/biome_cli/src/execute/migrate.rs | 4 +- .../biome_cli/src/execute/migrate/prettier.rs | 6 +- .../biome_cli/tests/cases/config_extends.rs | 2 +- .../with_formatter_configuration.snap | 10 +-- .../biome_configuration/src/editorconfig.rs | 2 +- crates/biome_css_formatter/src/context.rs | 2 +- crates/biome_formatter/src/lib.rs | 87 ++++++++++++++----- crates/biome_formatter_test/src/spec.rs | 4 +- .../src/test_prettier_snapshot.rs | 2 +- crates/biome_js_formatter/src/context.rs | 2 +- .../src/utils/assignment_like.rs | 2 +- crates/biome_json_formatter/src/context.rs | 2 +- 13 files changed, 85 insertions(+), 46 deletions(-) diff --git a/crates/biome_cli/src/commands/rage.rs b/crates/biome_cli/src/commands/rage.rs index 36587530898e..87b915cd51ac 100644 --- a/crates/biome_cli/src/commands/rage.rs +++ b/crates/biome_cli/src/commands/rage.rs @@ -215,7 +215,7 @@ impl Display for RageConfiguration<'_, '_> { {KeyValuePair("Indent style", markup!({DebugDisplay(formatter_configuration.indent_style)}))} {KeyValuePair("Indent width", markup!({DebugDisplay(formatter_configuration.indent_width)}))} {KeyValuePair("Line ending", markup!({DebugDisplay(formatter_configuration.line_ending)}))} - {KeyValuePair("Line width", markup!({DebugDisplay(formatter_configuration.line_width.get())}))} + {KeyValuePair("Line width", markup!({DebugDisplay(formatter_configuration.line_width.value())}))} {KeyValuePair("Attribute position", markup!({DebugDisplay(formatter_configuration.attribute_position)}))} {KeyValuePair("Ignore", markup!({DebugDisplay(formatter_configuration.ignore.iter().collect::>())}))} {KeyValuePair("Include", markup!({DebugDisplay(formatter_configuration.include.iter().collect::>())}))} @@ -237,7 +237,7 @@ impl Display for RageConfiguration<'_, '_> { {KeyValuePair("Indent style", markup!({DebugDisplayOption(javascript_formatter_configuration.indent_style)}))} {KeyValuePair("Indent width", markup!({DebugDisplayOption(javascript_formatter_configuration.indent_width)}))} {KeyValuePair("Line ending", markup!({DebugDisplayOption(javascript_formatter_configuration.line_ending)}))} - {KeyValuePair("Line width", markup!({DebugDisplayOption(javascript_formatter_configuration.line_width.map(|lw| lw.get()))}))} + {KeyValuePair("Line width", markup!({DebugDisplayOption(javascript_formatter_configuration.line_width.map(|lw| lw.value()))}))} {KeyValuePair("Attribute position", markup!({DebugDisplay(javascript_formatter_configuration.attribute_position)}))} ) .fmt(fmt)?; @@ -250,7 +250,7 @@ impl Display for RageConfiguration<'_, '_> { {KeyValuePair("Indent style", markup!({DebugDisplayOption(json_formatter_configuration.indent_style)}))} {KeyValuePair("Indent width", markup!({DebugDisplayOption(json_formatter_configuration.indent_width)}))} {KeyValuePair("Line ending", markup!({DebugDisplayOption(json_formatter_configuration.line_ending)}))} - {KeyValuePair("Line width", markup!({DebugDisplayOption(json_formatter_configuration.line_width.map(|lw| lw.get()))}))} + {KeyValuePair("Line width", markup!({DebugDisplayOption(json_formatter_configuration.line_width.map(|lw| lw.value()))}))} {KeyValuePair("Trailing Commas", markup!({DebugDisplayOption(json_formatter_configuration.trailing_commas)}))} ).fmt(fmt)?; diff --git a/crates/biome_cli/src/execute/migrate.rs b/crates/biome_cli/src/execute/migrate.rs index eca8386a835b..ed088458c044 100644 --- a/crates/biome_cli/src/execute/migrate.rs +++ b/crates/biome_cli/src/execute/migrate.rs @@ -8,7 +8,7 @@ use biome_deserialize::json::deserialize_from_json_ast; use biome_deserialize::Merge; use biome_diagnostics::Diagnostic; use biome_diagnostics::{category, PrintDiagnostic}; -use biome_formatter::ParseLineWidthError; +use biome_formatter::ParseFormatNumberError; use biome_fs::{BiomePath, ConfigName, FileSystemExt, OpenOptions}; use biome_json_parser::{parse_json_with_cache, JsonParserOptions}; use biome_json_syntax::{JsonFileSource, JsonRoot}; @@ -93,7 +93,7 @@ pub(crate) fn run(migrate_payload: MigratePayload) -> Result<(), CliDiagnostic> let prettier_biome_config = prettier_config .try_into() - .map_err(|err: ParseLineWidthError| { + .map_err(|err: ParseFormatNumberError| { CliDiagnostic::MigrateError(MigrationDiagnostic { reason: err.to_string(), }) diff --git a/crates/biome_cli/src/execute/migrate/prettier.rs b/crates/biome_cli/src/execute/migrate/prettier.rs index 0d2019d4a441..4a4037c2c36b 100644 --- a/crates/biome_cli/src/execute/migrate/prettier.rs +++ b/crates/biome_cli/src/execute/migrate/prettier.rs @@ -5,7 +5,7 @@ use biome_deserialize::{json::deserialize_from_json_str, StringSet}; use biome_deserialize_macros::Deserializable; use biome_diagnostics::{DiagnosticExt, PrintDiagnostic}; use biome_formatter::{ - AttributePosition, IndentWidth, LineEnding, LineWidth, ParseLineWidthError, QuoteStyle, + AttributePosition, IndentWidth, LineEnding, LineWidth, ParseFormatNumberError, QuoteStyle, }; use biome_fs::{FileSystem, OpenOptions}; use biome_js_formatter::context::{ArrowParentheses, QuoteProperties, Semicolons, TrailingCommas}; @@ -187,7 +187,7 @@ impl From for QuoteProperties { } impl TryFrom for biome_configuration::PartialConfiguration { - type Error = ParseLineWidthError; + type Error = ParseFormatNumberError; fn try_from(value: PrettierConfiguration) -> Result { let mut result = biome_configuration::PartialConfiguration::default(); @@ -267,7 +267,7 @@ impl TryFrom for biome_configuration::PartialConfiguratio } impl TryFrom for biome_configuration::OverridePattern { - type Error = ParseLineWidthError; + type Error = ParseFormatNumberError; fn try_from(Override { files, options }: Override) -> Result { let mut result = biome_configuration::OverridePattern { include: Some(StringSet::new(files.into_iter().collect())), diff --git a/crates/biome_cli/tests/cases/config_extends.rs b/crates/biome_cli/tests/cases/config_extends.rs index f0d43ec36c92..0859b8c84cce 100644 --- a/crates/biome_cli/tests/cases/config_extends.rs +++ b/crates/biome_cli/tests/cases/config_extends.rs @@ -325,7 +325,7 @@ fn allows_reverting_fields_in_extended_config_to_default() { rome_json.into(), format!( r#"{{ "extends": ["format.json"], "formatter": {{ "lineWidth": {} }} }}"#, - LineWidth::default().get() + LineWidth::default().value() ), ); diff --git a/crates/biome_cli/tests/snapshots/main_commands_rage/with_formatter_configuration.snap b/crates/biome_cli/tests/snapshots/main_commands_rage/with_formatter_configuration.snap index c36f7daca61d..9ae3f9451c9b 100644 --- a/crates/biome_cli/tests/snapshots/main_commands_rage/with_formatter_configuration.snap +++ b/crates/biome_cli/tests/snapshots/main_commands_rage/with_formatter_configuration.snap @@ -78,7 +78,7 @@ Biome Configuration: Formatter: Format with errors: true Indent style: Space - Indent width: IndentWidth(2) + Indent width: 2 Line ending: Lf Line width: 120 Attribute position: Multiline @@ -96,7 +96,7 @@ JavaScript Formatter: Bracket same line: false Quote style: Double Indent style: Tab - Indent width: IndentWidth(2) + Indent width: 2 Line ending: Lf Line width: 100 Attribute position: Auto @@ -104,7 +104,7 @@ JavaScript Formatter: JSON Formatter: Enabled: true Indent style: Space - Indent width: IndentWidth(2) + Indent width: 2 Line ending: Lf Line width: 100 Trailing Commas: unset @@ -112,9 +112,9 @@ JSON Formatter: CSS Formatter: Enabled: false Indent style: Tab - Indent width: IndentWidth(2) + Indent width: 2 Line ending: Lf - Line width: LineWidth(80) + Line width: 80 Quote style: Double Server: diff --git a/crates/biome_configuration/src/editorconfig.rs b/crates/biome_configuration/src/editorconfig.rs index c31e44a60c46..251fb21840e6 100644 --- a/crates/biome_configuration/src/editorconfig.rs +++ b/crates/biome_configuration/src/editorconfig.rs @@ -237,7 +237,7 @@ max_line_length = 80 assert_eq!(formatter.indent_style, Some(PlainIndentStyle::Space)); assert_eq!(formatter.indent_width.unwrap().value(), 4); assert_eq!(formatter.line_ending, Some(LineEnding::Crlf)); - assert_eq!(formatter.line_width.map(|v| v.get()), Some(80)); + assert_eq!(formatter.line_width.map(|v| v.value()), Some(80)); } #[test] diff --git a/crates/biome_css_formatter/src/context.rs b/crates/biome_css_formatter/src/context.rs index a595f8bffef3..87e1fa1c6906 100644 --- a/crates/biome_css_formatter/src/context.rs +++ b/crates/biome_css_formatter/src/context.rs @@ -160,7 +160,7 @@ impl fmt::Display for CssFormatOptions { writeln!(f, "Indent style: {}", self.indent_style)?; writeln!(f, "Indent width: {}", self.indent_width.value())?; writeln!(f, "Line ending: {}", self.line_ending)?; - writeln!(f, "Line width: {}", self.line_width.get())?; + writeln!(f, "Line width: {}", self.line_width.value())?; writeln!(f, "Quote style: {}", self.quote_style) } } diff --git a/crates/biome_formatter/src/lib.rs b/crates/biome_formatter/src/lib.rs index 4a3af7c24360..b4414e3c8cb8 100644 --- a/crates/biome_formatter/src/lib.rs +++ b/crates/biome_formatter/src/lib.rs @@ -44,7 +44,7 @@ mod verbatim; use crate::formatter::Formatter; use crate::group_id::UniqueGroupIdBuilder; use crate::prelude::TagKind; -use std::fmt::Debug; +use std::fmt::{Debug, Display}; use crate::builders::syntax_token_cow_slice; use crate::comments::{CommentStyle, Comments, SourceComment}; @@ -55,6 +55,7 @@ use crate::printed_tokens::PrintedTokens; use crate::printer::{Printer, PrinterOptions}; use crate::trivia::{format_skipped_token_trivia, format_trimmed_token}; pub use arguments::{Argument, Arguments}; +use biome_console::markup; use biome_deserialize::{ Deserializable, DeserializableValue, DeserializationDiagnostic, TextNumber, }; @@ -119,7 +120,7 @@ impl FromStr for IndentStyle { } } -impl std::fmt::Display for IndentStyle { +impl Display for IndentStyle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { IndentStyle::Tab => std::write!(f, "Tab"), @@ -197,7 +198,7 @@ impl std::fmt::Display for LineEnding { } } -#[derive(Clone, Copy, Debug, Eq, Merge, Hash, PartialEq)] +#[derive(Clone, Copy, Eq, Merge, Hash, PartialEq)] #[cfg_attr( feature = "serde", derive(serde::Serialize, schemars::JsonSchema), @@ -206,9 +207,9 @@ impl std::fmt::Display for LineEnding { pub struct IndentWidth(u8); impl IndentWidth { - pub const MIN: u8 = 2; + pub const MIN: u8 = 0; - pub const MAX: u8 = 80; + pub const MAX: u8 = 24; /// Return the numeric value for this [IndentWidth] pub fn value(&self) -> u8 { @@ -254,11 +255,11 @@ impl<'de> serde::Deserialize<'de> for IndentWidth { } impl FromStr for IndentWidth { - type Err = ParseLineWidthError; + type Err = ParseFormatNumberError; fn from_str(s: &str) -> Result { - let value = u8::from_str(s).map_err(ParseLineWidthError::ParseError)?; - let value = Self::try_from(value).map_err(ParseLineWidthError::TryFromU8Error)?; + let value = u8::from_str(s).map_err(ParseFormatNumberError::ParseError)?; + let value = Self::try_from(value).map_err(ParseFormatNumberError::TryFromU8Error)?; Ok(value) } } @@ -275,10 +276,29 @@ impl TryFrom for IndentWidth { } } +impl biome_console::fmt::Display for IndentWidth { + fn fmt(&self, fmt: &mut biome_console::fmt::Formatter) -> std::io::Result<()> { + fmt.write_markup(markup! {{self.value()}}) + } +} + +impl Display for IndentWidth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let value = self.value(); + f.write_str(&std::format!("{}", value)) + } +} + +impl Debug for IndentWidth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(self, f) + } +} + /// Validated value for the `line_width` formatter options /// /// The allowed range of values is 1..=320 -#[derive(Clone, Copy, Debug, Eq, Merge, PartialEq)] +#[derive(Clone, Copy, Eq, Merge, PartialEq)] #[cfg_attr( feature = "serde", derive(serde::Serialize, schemars::JsonSchema), @@ -293,7 +313,7 @@ impl LineWidth { pub const MAX: u16 = 320; /// Return the numeric value for this [LineWidth] - pub fn get(&self) -> u16 { + pub fn value(&self) -> u16 { self.0 } } @@ -335,9 +355,28 @@ impl<'de> serde::Deserialize<'de> for LineWidth { } } -/// Error type returned when parsing a [LineWidth] from a string fails -pub enum ParseLineWidthError { - /// The string could not be parsed as a valid [u16] +impl biome_console::fmt::Display for LineWidth { + fn fmt(&self, fmt: &mut biome_console::fmt::Formatter) -> std::io::Result<()> { + fmt.write_markup(markup! {{self.0}}) + } +} + +impl Display for LineWidth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let value = self.value(); + f.write_str(&std::format!("{}", value)) + } +} + +impl Debug for LineWidth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(self, f) + } +} + +/// Error type returned when parsing a [LineWidth] or [IndentWidth] from a string fails +pub enum ParseFormatNumberError { + /// The string could not be parsed to a number ParseError(ParseIntError), /// The `u16` value of the string is not a valid [LineWidth] TryFromU16Error(LineWidthFromIntError), @@ -345,36 +384,36 @@ pub enum ParseLineWidthError { TryFromU8Error(IndentWidthFromIntError), } -impl From for ParseLineWidthError { +impl From for ParseFormatNumberError { fn from(value: IndentWidthFromIntError) -> Self { Self::TryFromU8Error(value) } } -impl From for ParseLineWidthError { +impl From for ParseFormatNumberError { fn from(value: LineWidthFromIntError) -> Self { Self::TryFromU16Error(value) } } -impl From for ParseLineWidthError { +impl From for ParseFormatNumberError { fn from(value: ParseIntError) -> Self { Self::ParseError(value) } } -impl Debug for ParseLineWidthError { +impl Debug for ParseFormatNumberError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(self, f) } } -impl std::fmt::Display for ParseLineWidthError { +impl std::fmt::Display for ParseFormatNumberError { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ParseLineWidthError::ParseError(err) => std::fmt::Display::fmt(err, fmt), - ParseLineWidthError::TryFromU16Error(err) => std::fmt::Display::fmt(err, fmt), - ParseLineWidthError::TryFromU8Error(err) => std::fmt::Display::fmt(err, fmt), + ParseFormatNumberError::ParseError(err) => std::fmt::Display::fmt(err, fmt), + ParseFormatNumberError::TryFromU16Error(err) => std::fmt::Display::fmt(err, fmt), + ParseFormatNumberError::TryFromU8Error(err) => std::fmt::Display::fmt(err, fmt), } } } @@ -392,11 +431,11 @@ impl TryFrom for LineWidth { } impl FromStr for LineWidth { - type Err = ParseLineWidthError; + type Err = ParseFormatNumberError; fn from_str(s: &str) -> Result { - let value = u16::from_str(s).map_err(ParseLineWidthError::ParseError)?; - let value = Self::try_from(value).map_err(ParseLineWidthError::TryFromU16Error)?; + let value = u16::from_str(s).map_err(ParseFormatNumberError::ParseError)?; + let value = Self::try_from(value).map_err(ParseFormatNumberError::TryFromU16Error)?; Ok(value) } } diff --git a/crates/biome_formatter_test/src/spec.rs b/crates/biome_formatter_test/src/spec.rs index 0596f42a29eb..61c44c653a33 100644 --- a/crates/biome_formatter_test/src/spec.rs +++ b/crates/biome_formatter_test/src/spec.rs @@ -225,7 +225,7 @@ where let (output_code, printed) = self.formatted(&parsed, self.options.clone()); - let max_width = self.options.line_width().get() as usize; + let max_width = self.options.line_width().value() as usize; snapshot_builder = snapshot_builder .with_output_and_options( @@ -263,7 +263,7 @@ where let (mut output_code, printed) = self.formatted(&parsed, options.clone()); - let max_width = options.line_width().get() as usize; + let max_width = options.line_width().value() as usize; // There are some logs that print different line endings, and we can't snapshot those // otherwise we risk automatically having them replaced with LF by git. diff --git a/crates/biome_formatter_test/src/test_prettier_snapshot.rs b/crates/biome_formatter_test/src/test_prettier_snapshot.rs index d89d9bc7890c..373aa50ea9c6 100644 --- a/crates/biome_formatter_test/src/test_prettier_snapshot.rs +++ b/crates/biome_formatter_test/src/test_prettier_snapshot.rs @@ -203,7 +203,7 @@ where .with_output(SnapshotOutput::new(&formatted)) .with_errors(&parsed, &self.test_file().parse_input); - let max_width = self.options.line_width().get() as usize; + let max_width = self.options.line_width().value() as usize; builder = builder.with_lines_exceeding_max_width(&formatted, max_width); builder.finish(relative_file_name); diff --git a/crates/biome_js_formatter/src/context.rs b/crates/biome_js_formatter/src/context.rs index e140bc174f01..8604e8349c2f 100644 --- a/crates/biome_js_formatter/src/context.rs +++ b/crates/biome_js_formatter/src/context.rs @@ -386,7 +386,7 @@ impl fmt::Display for JsFormatOptions { writeln!(f, "Indent style: {}", self.indent_style)?; writeln!(f, "Indent width: {}", self.indent_width.value())?; writeln!(f, "Line ending: {}", self.line_ending)?; - writeln!(f, "Line width: {}", self.line_width.get())?; + writeln!(f, "Line width: {}", self.line_width.value())?; writeln!(f, "Quote style: {}", self.quote_style)?; writeln!(f, "JSX quote style: {}", self.jsx_quote_style)?; writeln!(f, "Quote properties: {}", self.quote_properties)?; diff --git a/crates/biome_js_formatter/src/utils/assignment_like.rs b/crates/biome_js_formatter/src/utils/assignment_like.rs index 2ad872f3e639..9f96520c5e88 100644 --- a/crates/biome_js_formatter/src/utils/assignment_like.rs +++ b/crates/biome_js_formatter/src/utils/assignment_like.rs @@ -1154,7 +1154,7 @@ fn is_poorly_breakable_member_or_call_chain( expression: &AnyJsExpression, f: &Formatter, ) -> SyntaxResult { - let threshold = f.options().line_width().get() / 4; + let threshold = f.options().line_width().value() / 4; // Only call and member chains are poorly breakable // - `obj.member.prop` diff --git a/crates/biome_json_formatter/src/context.rs b/crates/biome_json_formatter/src/context.rs index 206f76f3b2e3..406c442e5b35 100644 --- a/crates/biome_json_formatter/src/context.rs +++ b/crates/biome_json_formatter/src/context.rs @@ -195,7 +195,7 @@ impl fmt::Display for JsonFormatOptions { writeln!(f, "Indent style: {}", self.indent_style)?; writeln!(f, "Indent width: {}", self.indent_width.value())?; writeln!(f, "Line ending: {}", self.line_ending)?; - writeln!(f, "Line width: {}", self.line_width.get())?; + writeln!(f, "Line width: {}", self.line_width.value())?; writeln!(f, "Trailing commas: {}", self.trailing_commas) } }