Skip to content

Commit

Permalink
apply suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico committed Mar 1, 2024
1 parent b21059c commit 2cd670e
Show file tree
Hide file tree
Showing 45 changed files with 168 additions and 87 deletions.
1 change: 0 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,6 @@ our [guidelines for writing a good changelog entry](https://github.com/biomejs/b
#### New features

- Add option `json.formatter.trailingComma`, to provide a better control over the trailing comma in JSON/JSONC files. Its default value is `"none"`.
When this option isn't provided, and you set the parser option `json.parser.allowTrailingComma` to `true`, the value of `json.formatter.trailingComma` is `"all"`.

#### Bug fixes

Expand Down
2 changes: 1 addition & 1 deletion crates/biome_cli/src/commands/rage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ impl Display for RageConfiguration<'_, '_> {
{KeyValuePair("Indent size", markup!({DebugDisplayOption(json_formatter_configuration.indent_size)}))}
{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("Trailing Comma", markup!({DebugDisplayOption(json_formatter_configuration.trailing_comma)}))}
{KeyValuePair("Trailing Commas", markup!({DebugDisplayOption(json_formatter_configuration.trailing_commas)}))}
).fmt(fmt)?;
}

Expand Down
2 changes: 1 addition & 1 deletion crates/biome_cli/src/execute/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub(crate) fn run(migrate_payload: MigratePayload) -> Result<(), CliDiagnostic>
path: biome_path.clone(),
content: configuration_content.to_string(),
version: 0,
document_file_source: JsonFileSource::json().into(),
document_file_source: Some(JsonFileSource::json().into()),
})?;

let parsed = parse_json_with_cache(
Expand Down
4 changes: 2 additions & 2 deletions crates/biome_cli/src/execute/process_file/workspace_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::execute::diagnostics::{ResultExt, ResultIoExt};
use crate::execute::process_file::SharedTraversalOptions;
use biome_diagnostics::{category, Error};
use biome_fs::{BiomePath, File, OpenOptions};
use biome_service::workspace::{DocumentFileSource, FileGuard, OpenFileParams};
use biome_service::workspace::{FileGuard, OpenFileParams};
use biome_service::{Workspace, WorkspaceError};
use std::path::{Path, PathBuf};

Expand Down Expand Up @@ -36,7 +36,7 @@ impl<'ctx, 'app> WorkspaceFile<'ctx, 'app> {
let guard = FileGuard::open(
ctx.workspace,
OpenFileParams {
document_file_source: DocumentFileSource::from_path(&biome_path),
document_file_source: None,
path: biome_path,
version: 0,
content: input.clone(),
Expand Down
9 changes: 4 additions & 5 deletions crates/biome_cli/src/execute/std_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ use biome_diagnostics::Diagnostic;
use biome_diagnostics::PrintDiagnostic;
use biome_fs::BiomePath;
use biome_service::workspace::{
ChangeFileParams, DocumentFileSource, FeaturesBuilder, FixFileParams, FormatFileParams,
OpenFileParams, OrganizeImportsParams, PullDiagnosticsParams, RuleCategories,
SupportsFeatureParams,
ChangeFileParams, FeaturesBuilder, FixFileParams, FormatFileParams, OpenFileParams,
OrganizeImportsParams, PullDiagnosticsParams, RuleCategories, SupportsFeatureParams,
};
use biome_service::WorkspaceError;
use std::borrow::Cow;
Expand Down Expand Up @@ -49,7 +48,7 @@ pub(crate) fn run<'a>(
path: biome_path.clone(),
version: 0,
content: content.into(),
document_file_source: DocumentFileSource::default(),
document_file_source: None,
})?;
let printed = workspace.format_file(FormatFileParams { path: biome_path })?;

Expand All @@ -72,7 +71,7 @@ pub(crate) fn run<'a>(
path: biome_path.clone(),
version: 0,
content: content.into(),
document_file_source: DocumentFileSource::default(),
document_file_source: None,
})?;
// apply fix file of the linter
let file_features = workspace.file_features(SupportsFeatureParams {
Expand Down
48 changes: 46 additions & 2 deletions crates/biome_cli/tests/commands/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2265,7 +2265,7 @@ fn format_json_when_allow_trailing_commas_write() {

assert!(result.is_ok(), "run_cli returned {result:?}");

assert_file_contents(&fs, Path::new(file_path), "{\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n}\n");
assert_file_contents(&fs, Path::new(file_path), "{\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\"\n}\n");

assert_cli_snapshot(SnapshotPayload::new(
module_path!(),
Expand All @@ -2284,7 +2284,7 @@ fn format_omits_json_trailing_comma() {
let config_json = r#"{
"json": {
"parser": { "allowTrailingCommas": true },
"formatter": { "trailingComma": "none" }
"formatter": { "trailingCommas": "none" }
}
}"#;
let biome_config = "biome.json";
Expand Down Expand Up @@ -2320,6 +2320,50 @@ fn format_omits_json_trailing_comma() {
));
}

#[test]
fn format_omits_json_trailing_comma_omit() {
let mut fs = MemoryFileSystem::default();
let mut console = BufferConsole::default();

let config_json = r#"{
"json": {
"parser": { "allowTrailingCommas": true },
"formatter": { "trailingCommas": "all" }
}
}"#;
let biome_config = "biome.json";
let code = r#"{ "loreum_ipsum_lorem_ipsum": "bar", "loreum_ipsum_lorem_ipsum": "bar", "loreum_ipsum_lorem_ipsum": "bar", "loreum_ipsum_lorem_ipsum": "bar", "loreum_ipsum_lorem_ipsum": "bar",
}"#;
let file_path = Path::new("file.json");
fs.insert(file_path.into(), code.as_bytes());
fs.insert(biome_config.into(), config_json);

let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from(
[
("format"),
"--write",
file_path.as_os_str().to_str().unwrap(),
]
.as_slice(),
),
);

assert!(result.is_ok(), "run_cli returned {result:?}");

assert_file_contents(&fs, Path::new(file_path), "{\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n\t\"loreum_ipsum_lorem_ipsum\": \"bar\",\n}\n");

assert_cli_snapshot(SnapshotPayload::new(
module_path!(),
"format_omits_json_trailing_comma_omit",
fs,
console,
result,
));
}

#[test]
fn treat_known_json_files_as_jsonc_files() {
let mut fs = MemoryFileSystem::default();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ The configuration that is contained inside the file `biome.json`
languages) files.
--json-formatter-line-width=NUMBER What's the max width of a line applied to JSON (and its super
languages) files. Defaults to 80.
--json-formatter-trailing-comma=<omit|allow> Print trailing commas wherever possible in multi-line
--json-formatter-trailing-commas=<omit|allow> Print trailing commas wherever possible in multi-line
comma-separated syntactic structures. Defaults to "omit".
Global options applied to all commands
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ The configuration that is contained inside the file `biome.json`
languages) files.
--json-formatter-line-width=NUMBER What's the max width of a line applied to JSON (and its super
languages) files. Defaults to 80.
--json-formatter-trailing-comma=<omit|allow> Print trailing commas wherever possible in multi-line
--json-formatter-trailing-commas=<omit|allow> Print trailing commas wherever possible in multi-line
comma-separated syntactic structures. Defaults to "omit".
Global options applied to all commands
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ Available options:
languages) files.
--json-formatter-line-width=NUMBER What's the max width of a line applied to JSON (and its super
languages) files. Defaults to 80.
--json-formatter-trailing-comma=<omit|allow> Print trailing commas wherever possible in multi-line
--json-formatter-trailing-commas=<omit|allow> Print trailing commas wherever possible in multi-line
comma-separated syntactic structures. Defaults to "omit".
--stdin-file-path=PATH Use this option when you want to format code piped from `stdin`, and
print the output to `stdout`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ file.json format ━━━━━━━━━━━━━━━━━━━━━
3 │ - ········1,
4 │ - ····],
5 │ - }
2 │ + → "array":·[1],
2 │ + → "array":·[1]
3 │ + }
4 │ +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ expression: content
"loreum_ipsum_lorem_ipsum": "bar",
"loreum_ipsum_lorem_ipsum": "bar",
"loreum_ipsum_lorem_ipsum": "bar",
"loreum_ipsum_lorem_ipsum": "bar",
"loreum_ipsum_lorem_ipsum": "bar"
}

```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ expression: content
{
"json": {
"parser": { "allowTrailingCommas": true },
"formatter": { "trailingComma": "none" }
"formatter": { "trailingCommas": "none" }
}
}
```
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
---
source: crates/biome_cli/tests/snap_test.rs
expression: content
---
## `biome.json`

```json
{
"json": {
"parser": { "allowTrailingCommas": true },
"formatter": { "trailingCommas": "all" }
}
}
```

## `file.json`

```json
{
"loreum_ipsum_lorem_ipsum": "bar",
"loreum_ipsum_lorem_ipsum": "bar",
"loreum_ipsum_lorem_ipsum": "bar",
"loreum_ipsum_lorem_ipsum": "bar",
"loreum_ipsum_lorem_ipsum": "bar",
}

```

# Emitted Messages

```block
Formatted 1 file in <TIME>. Fixed 1 file.
```


Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ JSON Formatter:
Indent size: unset
Line ending: Lf
Line width: 100
Trailing Comma: unset
Trailing Commas: unset
Server:
Version: 0.0.0
Expand Down
26 changes: 13 additions & 13 deletions crates/biome_json_formatter/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub struct JsonFormatOptions {
line_width: LineWidth,
attribute_position: AttributePosition,
/// Print trailing commas wherever possible in multi-line comma-separated syntactic structures. Defaults to "none".
trailing_comma: TrailingComma,
trailing_commas: TrailingCommas,
}

#[derive(Clone, Copy, Debug, Default, Eq, Hash, Deserializable, Merge, PartialEq)]
Expand All @@ -75,31 +75,31 @@ pub struct JsonFormatOptions {
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub enum TrailingComma {
pub enum TrailingCommas {
#[default]
/// The formatter will remove the trailing comma
None,
/// The trailing comma is allowed and advised
All,
}

impl FromStr for TrailingComma {
impl FromStr for TrailingCommas {
type Err = &'static str;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"none" => Ok(Self::None),
"all" => Ok(Self::All),
_ => Err("Value not supported for TrailingComma"),
_ => Err("Value not supported for TrailingCommas"),
}
}
}

impl fmt::Display for TrailingComma {
impl fmt::Display for TrailingCommas {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
match self {
TrailingComma::None => std::write!(f, "None"),
TrailingComma::All => std::write!(f, "All"),
TrailingCommas::None => std::write!(f, "None"),
TrailingCommas::All => std::write!(f, "All"),
}
}
}
Expand Down Expand Up @@ -131,8 +131,8 @@ impl JsonFormatOptions {
self
}

pub fn with_trailing_comma(mut self, trailing_comma: TrailingComma) -> Self {
self.trailing_comma = trailing_comma;
pub fn with_trailing_comma(mut self, trailing_comma: TrailingCommas) -> Self {
self.trailing_commas = trailing_comma;
self
}

Expand All @@ -153,9 +153,9 @@ impl JsonFormatOptions {
}

pub(crate) fn to_trailing_separator(&self) -> TrailingSeparator {
match self.trailing_comma {
TrailingComma::None => TrailingSeparator::Omit,
TrailingComma::All => TrailingSeparator::Allowed,
match self.trailing_commas {
TrailingCommas::None => TrailingSeparator::Omit,
TrailingCommas::All => TrailingSeparator::Allowed,
}
}
}
Expand Down Expand Up @@ -192,6 +192,6 @@ impl fmt::Display for JsonFormatOptions {
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, "Trailing comma: {}", self.trailing_comma)
writeln!(f, "Trailing comma: {}", self.trailing_commas)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Indent style: Tab
Indent width: 2
Line ending: LF
Line width: 80
Trailing comma: None
-----

```json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Indent style: Tab
Indent width: 2
Line ending: LF
Line width: 80
Trailing comma: None
-----

```json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Indent style: Tab
Indent width: 2
Line ending: LF
Line width: 80
Trailing comma: None
-----

```json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Indent style: Tab
Indent width: 2
Line ending: LF
Line width: 80
Trailing comma: None
-----

```json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Indent style: Tab
Indent width: 2
Line ending: LF
Line width: 80
Trailing comma: None
-----

```json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Indent style: Tab
Indent width: 2
Line ending: LF
Line width: 80
Trailing comma: None
-----

```json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Indent style: Tab
Indent width: 2
Line ending: LF
Line width: 80
Trailing comma: None
-----

```json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Indent style: Tab
Indent width: 2
Line ending: LF
Line width: 80
Trailing comma: None
-----

```json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Indent style: Tab
Indent width: 2
Line ending: LF
Line width: 80
Trailing comma: None
-----

```json
Expand Down
Loading

0 comments on commit 2cd670e

Please sign in to comment.