Giter VIP home page Giter VIP logo

dprint-plugin-json's Introduction

dprint

CI Homebrew

Monorepo for dprint—a pluggable and configurable code formatting platform.

Links

Plugins

Notes

This repo is under active early development.

  1. The interface between the CLI and plugins might change often. You may need to keep updating to the latest version of both the CLI and plugins (the CLI will let you know what to do).
    • An upgrade path will be outlined in the release notes when this occurs.
  2. I do a lot of this development in my spare time. Please consider sponsoring if you are a commercial company using this.

dprint-plugin-json's People

Contributors

bartlomieju avatar dsherret avatar mmastrac avatar so1ve avatar zamiell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

dprint-plugin-json's Issues

Unable to parse correctly number with exponent and no sign

Describe the bug

The scanner is not able to parse numbers where no prefix (+ or -) is given for the exponent. According to the spec, specifying a prefix is optional, making values like this a valid number: 1e1.

This issue additionally hurt by the fact, that Go's standard JSON marshaler will not add the optional +, so a huge amount of JSON files generated by Go API backends can currently not be correctly formatted by dprint.

dprint-plugin-json version: 0.17.1

Input Code

1e1

Expected Output

1e1

Actual Output

Line 1, column 3: Expected plus or minus symbol in number literal

JSON formatting is super slow on a 700KB single line JSON file

I provided dprint with a 700KB single line JSON file and there seems to be no end in sight to it finishing formatting. I can't provide the file here because it's proprietary information. I formatted it with VS code rather quickly and it ended up being 40K lines.

Worth noting that after the file was formatted with VSCode it is back to being quick enough again.

Formatting JSONC can lose comments yet still indicate success

Describe the bug

deno fmt can lose comments without any indication.
Minimal reproducible examples (via deno fmt): here
Additional details: denoland/deno_std#3502 (comment)

Another way to reproduce:

dprint fmt --config <(echo '{"plugins": ["https://plugins.dprint.dev/json-0.17.4.wasm"]}')

dprint version: 0.41.0
dprint-plugin-json version: 0.17.4

Input Code

// before-value (context: top-level)
{
  // before-key (context: object spot 0)
  "k0"
  // after-key (context: object spot 0)
  :
  // before-value (context: object spot 0)
  "v0"
  // after-value (context: object spot 0)
  ,
  // before-key (context: object spot 1)
}
// after-value (context: top-level)

Expected Output

One of two options:

  • A canonical rearrangement of the comments' contents.
  • Failure if comments would otherwise be lost! (To signal to the user that the comments should be rearranged in order to avoid comment loss.)

Actual Output

// before-value (context: top-level)
{
  // before-key (context: object spot 0)
  "k0": // before-value (context: object spot 0)
  "v0"
  // before-key (context: object spot 1)
}
// after-value (context: top-level)

🙏🏻[feat/req] add 'preferSingleLine' option

Currently, for JSON elements which are split onto multiple lines, but fit into the line length, the multi-line format is always maintained. For example,

{
  "includes": ["**/*.{ts,tsx,js,jsx,cjs,mjs,json,md,rs}"],
  "excludes": [
    ".history",
    "**/node_modules"
  ]
}

won't shrink the excludes entry unless the first entry (".history") is on the initial line.

Ultimately, I'm trying to create repeatable final formatting for files which might be formatted in a different style (eg, deno or prettier). A 'preferSingleLine' option makes that an easier/possible task.

In fact, while thinking about this post, it occurs to me that a "global" version of 'preferSingleLine' indicating a default to capable plugins might be a useful option to help create the same output no matter the form (basically differing only in whitespace).

Can't formatting over 4 files with `.sh` script

OS

Windows 11 Pro. WSL 2.

11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz 2.80 GHz

RAM 16gb

Dprint version

0.41.0

JSON plugin

https://plugins.dprint.dev/json-0.17.4.wasm

dprint.json

{
  "plugins": [
    "https://plugins.dprint.dev/json-0.17.4.wasm"
  ]
}

My script

# /bin/sh

echo "dprint:"

START=$(date +%s%N)
  
npx dprint fmt --incremental=false
  
END=$(date +%s%N)

milliseconds=$((($END - $START)/1000000))

seconds=$(($milliseconds/1000))

minutes=$(($seconds/60))

echo "$milliseconds"
echo "$seconds"
echo "$minutes"

Log

WARNING: Formatting is slow for [my_path]/jsonformat/benches/large-file_1.json
WARNING: Formatting is slow for [my_path]/jsonformat/benches/large-file_2.json
WARNING: Formatting is slow for [my_path]/jsonformat/benches/large-file_3.json
WARNING: Formatting is slow for [my_path]/jsonformat/benches/large-file_4.json
WARNING: Formatting is slow for [my_path]/jsonformat/benches/large-file_5.json
WARNING: Formatting is slow for [my_path]/jsonformat/benches/large-file_6.json
....

I created 100 identical files from https://github.com/Nilstrieb/jsonformat/blob/master/benches/large-file.json.

When I format 4 files everything is fine! But when I try to format more, then I see a WARNING and not one file is formatted.

no meaningful error message given for `\u200b` in text

Describe the bug

dprint-plugin-json version: 0.13.2

Input Code

{
  "compilerOptions": {
    "esModuleInterop": true​
  }
}

Expected Output

something meaningful.

Actual Output

Error formatting C:/Users/Trim21/proj/cactbot/tsconfig-for-webpack.json. Message: RuntimeError: unreachable
    at __rust_start_panic (<module>[543]:0x3a39e)
    at rust_panic (<module>[540]:0x3a364)
    at std::panicking::rust_panic_with_hook::ha223473efd20893e (<module>[535]:0x3a0ac)
    at std::panicking::begin_panic_handler::{{closure}}::h0eb6605d81329fe7 (<module>[527]:0x39a44)
    at std::sys_common::backtrace::__rust_end_short_backtrace::h8c7d312a147e1df9 (<module>[526]:0x39993)
    at rust_begin_unwind (<module>[534]:0x39f85)
    at core::panicking::panic_fmt::hca0bee0b11468063 (<module>[619]:0x40554)
    at core::str::slice_error_fail::h2e3fd31345cd0cd6 (<module>[639]:0x41a85)
    at dprint_core::formatting::utils::string_utils::format_diagnostic::ha38e663e29e48684 (<module>[452]:0x351da)
    at dprint_plugin_json::format_text::format_text::h90fe515ff2009a58 (<module>[240]:0x1aacb)
    at format (<module>[208]:0x177de)
Had 1 error(s) formatting.

https://dprint.dev/playground/#code/N4WAUABBBEDGD2BbADgSwDYFMBOB5ZALqvAHYDO0AXBKJFDJmQLLwAmArlgJIkE7zIqEAtnaZA0ATgoAX3CywQA/language/json

Allow having trailing commas for config files like tsconfig.json

I like having trailing commas in files like:

  • tsconfig.json
  • jsconfig.json
  • .vscode/settings.json
  • .vscode/extensions.json

Even though these files have .json in their name, it is common enough and acceptable to sometimes have trailing commas in these files. But dprint always removes them.

Invalid UTF-8 chars prevent formatting

Describe the bug

deno fmt fails to format a JSON file because it contains invalid UTF8 chars.

dprint-plugin-json version: 0.10.2

Input Code

See https://gist.github.com/lucacasonato/a060df497ca3156327bcef46a554a8fb

Expected Output

A nicely formatted file, like prettier is able to generate.

Actual Output

Error formatting: /home/lucacasonato/Downloads/report.json
   Line 1, column 785340: Invalid unicode escape sequence. 'd834' is not a valid UTF8 character

  to ArrayBuffer with \ud834A\udf06A¥
                      ~~~~~~

Allow disabling the new line requirement

Most packcage managers will remove the trailing new line when adding or removing packcages, but otherwise the file matches dprints format.

Allow ignore mising newlines at the end of the file

Comments at the end of objects have their preceding newlines removed

Describe the bug

Comments at the end of objects have their preceding newlines removed; this is awkward in config files where I'm commenting out a setting at the bottom of an object temporarily, as it removes the formatting I had there for spacing.

dprint-plugin-json version: 0.19.2

Input Code

{
  // This is a setting.
  "foo": "",

  // These settings are temporarily commented out.
  // "baz": "",
  // "qux": ""
}

Expected Output

{
  // This is a setting.
  "foo": ""

  // These settings are temporarily commented out.
  // "baz": "",
  // "qux": ""
}

Actual Output

{
  // This is a setting.
  "foo": ""
  // These settings are temporarily commented out.
  // "baz": "",
  // "qux": ""
}

Panic on invalid JSON

Describe the bug

dprint-plugin-json version: 0.17.1

Input Code

{},


Note the two newlines after the comma.

Expected Output

some diagnostic about this being invalid code

Actual Output

Panic!

============================================================
Deno has panicked. This is a bug in Deno. Please report this
at https://github.com/denoland/deno/issues/new.
If you can reliably reproduce this panic, include the
reproduction steps and re-run with the RUST_BACKTRACE=1 env
var set and include the backtrace in your report.

Platform: macos aarch64
Version: 1.32.1
Args: ["deno", "fmt", "test.json"]

thread 'tokio-runtime-worker' panicked at 'capacity overflow', library/alloc/src/raw_vec.rs:518:5
stack backtrace:
   0: _rust_begin_unwind
   1: core::panicking::panic_fmt
   2: alloc::raw_vec::capacity_overflow
   3: alloc::str::<impl str>::repeat
   4: dprint_core::formatting::utils::string_utils::format_diagnostic
   5: dprint_plugin_json::format_text::format_text
   6: deno::tools::fmt::format_json
   7: deno::tools::fmt::format_file
   8: tokio::runtime::task::raw::poll

Lint performance slower than `biome` and even slower than Prettier

I am creating all-in-one linter (yes, another one) and found dprint-plugin-json slower than biome (even both written in Rust) and even slower than Prettier.
Here benchmark repo: https://github.com/dalisoft/json-lint-benchmark

Here project which does JSON linting/formatting very fast: https://github.com/jsona/jsona
I am migrated project into JS ecosystem by using download binary method, see at here if you want check

package-lock.json

| Command                                                                        |    Mean [ms] | Min [ms] | Max [ms] |     Relative |
| :----------------------------------------------------------------------------- | -----------: | -------: | -------: | -----------: |
| `biome format data/package-lock-test.json`                                     |   45.7 ± 1.2 |     44.7 |     47.0 |  7.18 ± 0.30 |
| `prettier -c data/package-lock-test.json`                                      |  154.1 ± 2.4 |    152.2 |    156.8 | 24.21 ± 0.87 |
| `dprint check data/package-lock-test.json`                                     | 199.3 ± 13.5 |    190.0 |    214.7 | 31.31 ± 2.35 |
| `deno fmt data/package-lock-test.json`                                         |    7.2 ± 0.3 |      6.8 |      7.4 |  1.13 ± 0.06 |
| `jsona fmt --option trailing_newline=true --check data/package-lock-test.json` |    6.4 ± 0.2 |      6.1 |      6.5 |         1.00 |
| `spectral lint --ignore-unknown-format data/package-lock-test.json`            |  372.1 ± 3.8 |    367.8 |    374.7 | 58.47 ± 1.99 |

package.json

| Command                                                                       |    Mean [ms] | Min [ms] | Max [ms] |      Relative |
| :---------------------------------------------------------------------------- | -----------: | -------: | -------: | ------------: |
| `biome format data/package-template.json`                                     |   48.5 ± 9.3 |     42.9 |     59.2 |   9.36 ± 7.25 |
| `prettier -c data/package-template.json`                                      |  109.5 ± 1.9 |    108.2 |    111.7 | 21.13 ± 15.85 |
| `dprint check data/package-template.json`                                     | 197.0 ± 15.9 |    187.0 |    215.3 | 38.01 ± 28.67 |
| `deno fmt data/package-template.json`                                         |  21.1 ± 23.9 |      6.9 |     48.7 |   4.08 ± 5.53 |
| `jsona fmt --option trailing_newline=true --check data/package-template.json` |    5.2 ± 3.9 |      2.4 |      9.6 |          1.00 |
| `spectral lint --ignore-unknown-format data/package-template.json`            | 410.3 ± 88.6 |    358.9 |    512.6 | 79.16 ± 61.78 |

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.