Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: prettier/eslint-plugin-prettier
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v4.2.1
Choose a base ref
...
head repository: prettier/eslint-plugin-prettier
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v5.0.0
Choose a head ref
  • 19 commits
  • 30 files changed
  • 5 contributors

Commits on Jun 30, 2022

  1. Copy the full SHA
    2de3442 View commit details

Commits on Jul 9, 2022

  1. Copy the full SHA
    2280b88 View commit details
  2. Copy the full SHA
    2373d0c View commit details
  3. chore: add FUNDING.yml

    JounQin committed Jul 9, 2022
    Copy the full SHA
    905c77f View commit details
  4. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    599aba4 View commit details
  5. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    42e4b2b View commit details
  6. chore: release eslint-plugin-prettier (#496)

    Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
    github-actions[bot] and github-actions[bot] authored Jul 9, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    19c4173 View commit details

Commits on Jul 10, 2022

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    c2d7367 View commit details

Commits on Aug 12, 2022

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    7cd0393 View commit details
  2. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    21d87ab View commit details

Commits on Sep 2, 2022

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    910aeb6 View commit details
  2. chore: release eslint-plugin-prettier v5.0.0-alpha.0 (#517)

    Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
    github-actions[bot] and github-actions[bot] authored Sep 2, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    477f890 View commit details
  3. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    ba490d7 View commit details

Commits on Mar 10, 2023

  1. fix: add missing dependency synckit (#548)

    Co-authored-by: JounQin <admin@1stg.me>
    fisker and JounQin authored Mar 10, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    82a3db8 View commit details
  2. chore: release eslint-plugin-prettier (alpha) (#553)

    Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
    github-actions[bot] and github-actions[bot] authored Mar 10, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    00449df View commit details

Commits on Jul 6, 2023

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    ae7a73c View commit details
  2. chore: release eslint-plugin-prettier (alpha) (#566)

    Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
    github-actions[bot] and github-actions[bot] authored Jul 6, 2023
    Copy the full SHA
    6878434 View commit details

Commits on Jul 11, 2023

  1. Copy the full SHA
    370e88f View commit details
  2. chore: release eslint-plugin-prettier (#569)

    Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
    github-actions[bot] and github-actions[bot] authored Jul 11, 2023
    Copy the full SHA
    b2b93c3 View commit details
2 changes: 1 addition & 1 deletion .changeset/config.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"$schema": "https://unpkg.com/@changesets/config@1.6.0/schema.json",
"$schema": "https://unpkg.com/@changesets/config/schema.json",
"changelog": [
"@changesets/changelog-github",
{
2 changes: 1 addition & 1 deletion .commitlintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"extends": "@1stg"
"extends": "@commitlint/config-conventional"
}
22 changes: 22 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"root": true,
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"env": {
"mocha": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:@eslint-community/eslint-comments/recommended",
"plugin:eslint-plugin/recommended",
"plugin:n/recommended",
"plugin:mdx/recommended",
"plugin:prettier/recommended"
],
"rules": {
"eslint-plugin/report-message-format": ["error", "^[^a-z].*\\.$"]
}
}
35 changes: 0 additions & 35 deletions .eslintrc.json

This file was deleted.

12 changes: 12 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
github:
- JounQin
- 1stG
- rx-ts
- un-ts
patreon: 1stG
open_collective: prettier
custom:
- https://opencollective.com/1stG
- https://opencollective.com/rxts
- https://opencollective.com/unts
- https://afdian.net/@JounQin
21 changes: 9 additions & 12 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -8,35 +8,32 @@ on:

jobs:
ci:
name: 'Test: Node ${{ matrix.node-version }} - ESLint ${{ matrix.eslint-version }}'
name: Lint and Test on Node ${{ matrix.node-version }}
runs-on: ubuntu-latest
strategy:
matrix:
eslint-version:
- 7
- 8
node-version:
- 12
- 14
- 16
- 18
- 20

steps:
- uses: actions/checkout@v3

- uses: pnpm/action-setup@v2

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: yarn

- name: Use ESLint ${{ matrix.eslint-version }}
run: yarn upgrade eslint@${{ matrix.eslint-version }}
cache: pnpm

- name: Install
run: yarn --frozen-lockfile
run: pnpm install

- name: Test
run: yarn mocha
run: pnpm mocha

- name: Perf
run: TIMING=1 yarn lint
run: TIMING=1 pnpm lint
14 changes: 7 additions & 7 deletions .github/workflows/pkg-size.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: Package Size Report

on:
pull_request:
pull_request_target:
branches:
- master

@@ -11,14 +11,14 @@ jobs:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3
- uses: actions/checkout@v3

- name: Setup Node.js
uses: actions/setup-node@v3
- uses: pnpm/action-setup@v2

- uses: actions/setup-node@v3
with:
node-version: 16.x
cache: yarn
node-version: 16
cache: pnpm

- name: Package Size Report
uses: pkg-size/action@v1
18 changes: 9 additions & 9 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -10,23 +10,23 @@ jobs:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v3
- uses: actions/checkout@v3

- name: Setup Node.js 16.x
uses: actions/setup-node@v3
- uses: pnpm/action-setup@v2

- uses: actions/setup-node@v3
with:
node-version: 16.x
cache: yarn
node-version: 16
cache: pnpm

- name: Install Dependencies
run: yarn --frozen-lockfile
run: pnpm install

- name: Create Release Pull Request or Publish to npm
id: changesets
uses: changesets/action@v1
with:
commit: 'chore: release prettier-plugin-svelte'
title: 'chore: release prettier-plugin-svelte'
commit: 'chore: release eslint-plugin-prettier'
title: 'chore: release eslint-plugin-prettier'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
node_modules
*.log
.*cache
.yarn/*
!.yarn/plugins
!.yarn/releases
4 changes: 4 additions & 0 deletions .lintstagedrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"*.{js,md,ts}": ["eslint --cache -f friendly --fix"],
"*.{json,yml}": ["prettier --write"]
}
1 change: 0 additions & 1 deletion .lintstagedrc.js

This file was deleted.

2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
lts/*
14
6 changes: 5 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
"@1stg/prettier-config/semi"
{
"arrowParens": "avoid",
"singleQuote": true,
"plugins": ["prettier-plugin-pkg"]
}
2 changes: 1 addition & 1 deletion .remarkrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"plugins": [
"@1stg/config"
"@1stg/preset"
]
}
1 change: 0 additions & 1 deletion .simple-git-hooks.js

This file was deleted.

4 changes: 4 additions & 0 deletions .simple-git-hooks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"pre-commit": "npx lint-staged",
"commit-msg": "npx commitlint -e"
}
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
# Changelog

## 5.0.0

### Major Changes

- [#508](https://github.com/prettier/eslint-plugin-prettier/pull/508) [`910aeb6`](https://github.com/prettier/eslint-plugin-prettier/commit/910aeb60a7456beb6193c634bb8dec1b7181312d) Thanks [@JounQin](https://github.com/JounQin)! - feat!: bump peer eslint to ">=8.0.0" and node to "^14.18.0 || >=16.0.0"

- [#508](https://github.com/prettier/eslint-plugin-prettier/pull/508) [`910aeb6`](https://github.com/prettier/eslint-plugin-prettier/commit/910aeb60a7456beb6193c634bb8dec1b7181312d) Thanks [@JounQin](https://github.com/JounQin)! - feat!: upgrade to prettier v3

### Minor Changes

- [#508](https://github.com/prettier/eslint-plugin-prettier/pull/508) [`910aeb6`](https://github.com/prettier/eslint-plugin-prettier/commit/910aeb60a7456beb6193c634bb8dec1b7181312d) Thanks [@JounQin](https://github.com/JounQin)! - feat: add typings support

### Patch Changes

- [#548](https://github.com/prettier/eslint-plugin-prettier/pull/548) [`82a3db8`](https://github.com/prettier/eslint-plugin-prettier/commit/82a3db878baf1a8f8ef53393069fe23c3a80ce15) Thanks [@fisker](https://github.com/fisker)! - fix: add missing dependency `synckit`

- [#564](https://github.com/prettier/eslint-plugin-prettier/pull/564) [`ae7a73c`](https://github.com/prettier/eslint-plugin-prettier/commit/ae7a73c6c4b306c617c5dd9baaaa2ae7c0f9f44b) Thanks [@auvred](https://github.com/auvred)! - fix: compatibility with prettier@3 without plugins

## 4.2.2

### Patch Changes

- [`2373d0c`](https://github.com/prettier/eslint-plugin-prettier/commit/2373d0c0c9f30aee30e6059ba386fdc4435ed333) Thanks [@JounQin](https://github.com/JounQin)! - docs: add Sponsors and Backers sections

## 4.2.1

### Patch Changes
8 changes: 4 additions & 4 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -7,18 +7,18 @@ Thanks for contributing!
```sh
git clone https://github.com/prettier/eslint-plugin-prettier.git
cd eslint-plugin-prettier
yarn
pnpm install
```

## Running the tests

```sh
yarn test
pnpm test
```

This is an [ESLint](http://eslint.org) plugin. Documentation for the APIs that it uses can be found on ESLint's [Working with Plugins](http://eslint.org/docs/developer-guide/working-with-plugins) page.

This plugin is used to lint itself. The style is checked when `yarn test` is run, and the build will fail if there are any linting errors. You can use `yarn lint --fix` to fix some linting errors. To run the tests without running the linter, you can use `yarn mocha`.
This plugin is used to lint itself. The style is checked when `pnpm test` is run, and the build will fail if there are any linting errors. You can use `pnpm lint --fix` to fix some linting errors. To run the tests without running the linter, you can use `pnpm mocha`.

## Commit messages

@@ -27,7 +27,7 @@ Please view [commitlint](https://commitlint.js.org) for more details.
## Publishing

```sh
yarn release
pnpm release
```

Please view [changesets](https://github.com/changesets/changesets) and its [action](https://github.com/changesets/action) for more details.
16 changes: 13 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -97,7 +97,11 @@ Exactly what does `plugin:prettier/recommended` do? Well, this is what it expand

## `Svelte` support

We recommend to use [`eslint-plugin-svelte`](https://github.com/ota-meshi/eslint-plugin-svelte) instead of [`eslint-plugin-svelte3`](https://github.com/sveltejs/eslint-plugin-svelte3) because `eslint-plugin-svelte` has a correct [`eslint-svelte-parser`](https://github.com/ota-meshi/svelte-eslint-parser) instead of hacking, when use with `eslint-plugin-svelte3`, `eslint-plugin-prettier` will just ignore the text passed by `eslint-plugin-svelte3`, because the text they has been modified.
We recommend to use [`eslint-plugin-svelte`](https://github.com/ota-meshi/eslint-plugin-svelte) instead of [`eslint-plugin-svelte3`](https://github.com/sveltejs/eslint-plugin-svelte3) because `eslint-plugin-svelte` has a correct [`eslint-svelte-parser`](https://github.com/ota-meshi/svelte-eslint-parser) instead of hacking.

When use with `eslint-plugin-svelte3`, `eslint-plugin-prettier` will just ignore the text passed by `eslint-plugin-svelte3`, because the text has been modified.

If you still decide to use `eslint-plugin-svelte3`, you'll need to run `prettier --write *.svelte` manually.

## `arrow-body-style` and `prefer-arrow-callback` issue

@@ -119,7 +123,13 @@ If you’re fixing large of amounts of previously unformatted code, consider tem

```json
{
"prettier/prettier": ["error", { "singleQuote": true, "parser": "flow" }]
"prettier/prettier": [
"error",
{
"singleQuote": true,
"parser": "flow"
}
]
}
```

@@ -129,7 +139,7 @@ If you’re fixing large of amounts of previously unformatted code, consider tem

- An object with the following options

- `usePrettierrc`: Enables loading of the Prettier configuration file, (default: `true`). May be useful if you are using multiple tools that conflict with each other, or do not wish to mix your ESLint settings with your Prettier configuration.
- `usePrettierrc`: Enables loading of the Prettier configuration file, (default: `true`). May be useful if you are using multiple tools that conflict with each other, or do not wish to mix your ESLint settings with your Prettier configuration. And also, it is possible to run prettier without loading the prettierrc config file [via the CLI's --no-config option](https://prettier.io/docs/en/cli.html#--no-config) or through the API by [calling prettier.format() without passing through the options generated by calling resolveConfig](https://prettier.io/docs/en/api.html#prettierresolveconfigfilepath--options).

```json
{
5 changes: 5 additions & 0 deletions eslint-plugin-prettier.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { ESLint } from 'eslint';

declare const eslintPluginPrettier: ESLint.Plugin;

export = eslintPluginPrettier;
189 changes: 57 additions & 132 deletions eslint-plugin-prettier.js
Original file line number Diff line number Diff line change
@@ -3,6 +3,16 @@
* @author Andres Suarez
*/

// @ts-check

/**
* @typedef {import('eslint').AST.Range} Range
* @typedef {import('eslint').AST.SourceLocation} SourceLocation
* @typedef {import('eslint').ESLint.Plugin} Plugin
* @typedef {import('prettier').FileInfoOptions} FileInfoOptions
* @typedef {import('prettier').Options & { onDiskFilepath: string, parserPath: string, usePrettierrc?: boolean }} Options
*/

'use strict';

// ------------------------------------------------------------------------------
@@ -26,9 +36,9 @@ const { INSERT, DELETE, REPLACE } = generateDifferences;

// Lazily-loaded Prettier.
/**
* @type {import('prettier')}
* @type {(source: string, options: Options, fileInfoOptions: FileInfoOptions) => string}
*/
let prettier;
let prettierFormat;

// ------------------------------------------------------------------------------
// Rule Definition
@@ -43,7 +53,7 @@ let prettier;
*/
function reportDifference(context, difference) {
const { operation, offset, deleteText = '', insertText = '' } = difference;
const range = [offset, offset + deleteText.length];
const range = /** @type {Range} */ ([offset, offset + deleteText.length]);
const [start, end] = range.map(index =>
context.getSourceCode().getLocFromIndex(index),
);
@@ -63,7 +73,10 @@ function reportDifference(context, difference) {
// Module Definition
// ------------------------------------------------------------------------------

module.exports = {
/**
* @type {Plugin}
*/
const eslintPluginPrettier = {
configs: {
recommended: {
extends: ['prettier'],
@@ -112,7 +125,10 @@ module.exports = {
create(context) {
const usePrettierrc =
!context.options[1] || context.options[1].usePrettierrc !== false;
const eslintFileInfoOptions =
/**
* @type {FileInfoOptions}
*/
const fileInfoOptions =
(context.options[1] && context.options[1].fileInfoOptions) || {};
const sourceCode = context.getSourceCode();
const filepath = context.getFilename();
@@ -125,134 +141,19 @@ module.exports = {
const source = sourceCode.text;

return {
// eslint-disable-next-line sonarjs/cognitive-complexity
Program() {
if (!prettier) {
if (!prettierFormat) {
// Prettier is expensive to load, so only load it if needed.
prettier = require('prettier');
prettierFormat = require('synckit').createSyncFn(
require.resolve('./worker'),
);
}

/**
* @type {{}}
*/
const eslintPrettierOptions = context.options[0] || {};

const prettierRcOptions = usePrettierrc
? prettier.resolveConfig.sync(onDiskFilepath, {
editorconfig: true,
})
: null;

const { ignored, inferredParser } = prettier.getFileInfo.sync(
onDiskFilepath,
{
resolveConfig: false,
withNodeModules: false,
ignorePath: '.prettierignore',
plugins: prettierRcOptions ? prettierRcOptions.plugins : null,
...eslintFileInfoOptions,
},
);

// Skip if file is ignored using a .prettierignore file
if (ignored) {
return;
}

const initialOptions = {};

// ESLint supports processors that let you extract and lint JS
// fragments within a non-JS language. In the cases where prettier
// supports the same language as a processor, we want to process
// the provided source code as javascript (as ESLint provides the
// rules with fragments of JS) instead of guessing the parser
// based off the filename. Otherwise, for instance, on a .md file we
// end up trying to run prettier over a fragment of JS using the
// markdown parser, which throws an error.
// Processors may set virtual filenames for these extracted blocks.
// If they do so then we want to trust the file extension they
// provide, and no override is needed.
// If the processor does not set any virtual filename (signified by
// `filepath` and `onDiskFilepath` being equal) AND we can't
// infer the parser from the filename, either because no filename
// was provided or because there is no parser found for the
// filename, use javascript.
// This is added to the options first, so that
// prettierRcOptions and eslintPrettierOptions can still override
// the parser.
//
// `parserBlocklist` should contain the list of prettier parser
// names for file types where:
// * Prettier supports parsing the file type
// * There is an ESLint processor that extracts JavaScript snippets
// from the file type.
if (filepath === onDiskFilepath) {
// The following list means the plugin process source into js content
// but with same filename, so we need to change the parser to `babel`
// by default.
// Related ESLint plugins are:
// 1. `eslint-plugin-graphql` (replacement: `@graphql-eslint/eslint-plugin`)
// 2. `eslint-plugin-html`
// 3. `eslint-plugin-markdown@1` (replacement: `eslint-plugin-markdown@2+`)
// 4. `eslint-plugin-svelte3` (replacement: `eslint-plugin-svelte@2+`)
const parserBlocklist = [null, 'markdown', 'html'];

let inferParserToBabel = parserBlocklist.includes(inferredParser);

switch (inferredParser) {
// it could be processed by `@graphql-eslint/eslint-plugin` or `eslint-plugin-graphql`
case 'graphql': {
if (
// for `eslint-plugin-graphql`, see https://github.com/apollographql/eslint-plugin-graphql/blob/master/src/index.js#L416
source.startsWith('ESLintPluginGraphQLFile`')
) {
inferParserToBabel = true;
}
break;
}
// it could be processed by `@ota-meshi/eslint-plugin-svelte`, `eslint-plugin-svelte` or `eslint-plugin-svelte3`
case 'svelte': {
// The `source` would be modified by `eslint-plugin-svelte3`
if (!context.parserPath.includes('svelte-eslint-parser')) {
// We do not support `eslint-plugin-svelte3`,
// the users should run `prettier` on `.svelte` files manually
return;
}
}
}

if (inferParserToBabel) {
initialOptions.parser = 'babel';
}
} else {
// Similar to https://github.com/prettier/stylelint-prettier/pull/22
// In all of the following cases ESLint extracts a part of a file to
// be formatted and there exists a prettier parser for the whole file.
// If you're interested in prettier you'll want a fully formatted file so
// you're about to run prettier over the whole file anyway.
// Therefore running prettier over just the style section is wasteful, so
// skip it.
const parserBlocklist = [
'babel',
'babylon',
'flow',
'typescript',
'vue',
'markdown',
'html',
'mdx',
'angular',
'svelte',
];
if (parserBlocklist.includes(inferredParser)) {
return;
}
}

const prettierOptions = {
...initialOptions,
...prettierRcOptions,
...eslintPrettierOptions,
filepath,
};

// prettier.format() may throw a SyntaxError if it cannot parse the
// source code it is given. Usually for JS files this isn't a
// problem as ESLint will report invalid syntax before trying to
@@ -261,29 +162,51 @@ module.exports = {
// files throw an error if they contain unclosed elements, such as
// `<template><div></template>. In this case report an error at the
// point at which parsing failed.
/**
* @type {string}
*/
let prettierSource;
try {
prettierSource = prettier.format(source, prettierOptions);
prettierSource = prettierFormat(
source,
{
...eslintPrettierOptions,
filepath,
onDiskFilepath,
parserPath: context.parserPath,
usePrettierrc,
},
fileInfoOptions,
);
} catch (err) {
if (!(err instanceof SyntaxError)) {
throw err;
}

let message = 'Parsing error: ' + err.message;

const error =
/** @type {SyntaxError & {codeFrame: string; loc: SourceLocation}} */ (
err
);

// Prettier's message contains a codeframe style preview of the
// invalid code and the line/column at which the error occurred.
// ESLint shows those pieces of information elsewhere already so
// remove them from the message
if (err.codeFrame) {
message = message.replace(`\n${err.codeFrame}`, '');
if (error.codeFrame) {
message = message.replace(`\n${error.codeFrame}`, '');
}
if (err.loc) {
if (error.loc) {
message = message.replace(/ \(\d+:\d+\)$/, '');
}

context.report({ message, loc: err.loc });
context.report({ message, loc: error.loc });

return;
}

if (prettierSource == null) {
return;
}

@@ -300,3 +223,5 @@ module.exports = {
},
},
};

module.exports = eslintPluginPrettier;
84 changes: 51 additions & 33 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
{
"name": "eslint-plugin-prettier",
"version": "4.2.1",
"version": "5.0.0",
"description": "Runs prettier as an eslint rule",
"repository": "git+https://github.com/prettier/eslint-plugin-prettier.git",
"homepage": "https://github.com/prettier/eslint-plugin-prettier#readme",
"author": "Teddy Katz",
"contributors": [
"JounQin (https://github.com/JounQin) <admin@1stg.me>"
],
"funding": "https://opencollective.com/prettier",
"license": "MIT",
"packageManager": "pnpm@7.33.3",
"engines": {
"node": ">=12.0.0"
"node": "^14.18.0 || >=16.0.0"
},
"main": "eslint-plugin-prettier.js",
"types": "eslint-plugin-prettier.d.ts",
"files": [
"eslint-plugin-prettier.js"
"eslint-plugin-prettier.d.ts",
"eslint-plugin-prettier.js",
"worker.js"
],
"keywords": [
"eslint",
@@ -23,49 +28,62 @@
"prettier"
],
"scripts": {
"format": "yarn prettier '**/*.{js,json,md,yml}' --write && yarn lint --fix",
"format": "prettier --write . && pnpm lint --fix",
"lint": "eslint . --cache -f friendly --max-warnings 10",
"prepare": "patch-package && simple-git-hooks && yarn-deduplicate --strategy fewer || exit 0",
"prerelease": "yarn format && yarn test",
"prepare": "simple-git-hooks",
"prerelease": "pnpm format && pnpm test",
"release": "changeset publish",
"test": "yarn lint && mocha"
"test": "pnpm lint && mocha"
},
"peerDependencies": {
"eslint": ">=7.28.0",
"prettier": ">=2.0.0"
"@types/eslint": ">=8.0.0",
"eslint": ">=8.0.0",
"prettier": ">=3.0.0"
},
"peerDependenciesMeta": {
"@types/eslint": {
"optional": true
},
"eslint-config-prettier": {
"optional": true
}
},
"dependencies": {
"prettier-linter-helpers": "^1.0.0"
"prettier-linter-helpers": "^1.0.0",
"synckit": "^0.8.5"
},
"devDependencies": {
"@1stg/common-config": "~3.0.0",
"@1stg/eslint-config": "~3.0.0",
"@changesets/changelog-github": "^0.4.5",
"@changesets/cli": "^2.23.0",
"@graphql-eslint/eslint-plugin": "^2.5.0",
"@ota-meshi/eslint-plugin-svelte": "^0.34.1",
"@typescript-eslint/parser": "^5.29.0",
"eslint-config-prettier": "^8.5.0",
"eslint-mdx": "^1.17.0",
"eslint-plugin-eslint-plugin": "^4.3.0",
"eslint-plugin-mdx": "^1.17.0",
"eslint-plugin-self": "^1.2.1",
"eslint-plugin-utils": "^0.1.0",
"graphql": "^16.5.0",
"mocha": "^9.2.2",
"patch-package": "^6.4.7",
"svelte": "^3.48.0",
"vue-eslint-parser": "^8.3.0"
},
"resolutions": {
"@babel/traverse": "^7.18.5",
"@1stg/remark-preset": "^2.0.0",
"@changesets/changelog-github": "^0.4.8",
"@changesets/cli": "^2.26.2",
"@commitlint/config-conventional": "^17.6.6",
"@eslint-community/eslint-plugin-eslint-comments": "^3.2.1",
"@graphql-eslint/eslint-plugin": "^3.20.0",
"@types/eslint": "^8.44.0",
"@types/prettier-linter-helpers": "^1.0.1",
"commitlint": "^17.6.6",
"eslint": "^8.44.0",
"eslint-config-prettier": "^8.8.0",
"eslint-formatter-friendly": "^7.0.0",
"eslint-mdx": "^2.1.0",
"eslint-plugin-eslint-plugin": "^5.1.0",
"eslint-plugin-mdx": "^2.1.0",
"eslint-plugin-n": "^16.0.1",
"eslint-plugin-prettier": "link:.",
"prettier": "^2.7.1"
"eslint-plugin-svelte": "^2.32.2",
"eslint-plugin-svelte3": "^4.0.0",
"graphql": "^16.7.1",
"lint-staged": "^13.2.3",
"mocha": "^10.2.0",
"prettier": "^3.0.0",
"prettier-plugin-pkg": "^0.18.0",
"simple-git-hooks": "^2.8.1",
"svelte": "^4.0.5",
"vue-eslint-parser": "^9.3.1"
},
"packageManager": "yarn@1.22.19"
"pnpm": {
"patchedDependencies": {
"@graphql-eslint/eslint-plugin@3.20.0": "patches/@graphql-eslint__eslint-plugin@3.20.0.patch"
}
}
}
13 changes: 0 additions & 13 deletions patches/@1stg+lint-staged+1.7.5.patch

This file was deleted.

74 changes: 74 additions & 0 deletions patches/@graphql-eslint__eslint-plugin@3.20.0.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
diff --git a/cjs/documents.js b/cjs/documents.js
index f418f624fec59761e9537d7e0acc43a0bebb843e..0cda9fb8be4888d5a8d8c38a0b82f84b5745edb8 100644
--- a/cjs/documents.js
+++ b/cjs/documents.js
@@ -44,7 +44,7 @@ const handleVirtualPath = (documents) => {
if ([".gql", ".graphql"].some((extension) => location.endsWith(extension))) {
return source;
}
- filepathMap[location] ??= -1;
+ filepathMap[location] = filepathMap[location] != null ? filepathMap[location] : -1;
const index = filepathMap[location] += 1;
return {
...source,
diff --git a/cjs/parser.js b/cjs/parser.js
index 269ecb5e2107d08ac185af6175d921de38fac476..4b9d5a698b515feaf6107f73dbdc14186d507354 100644
--- a/cjs/parser.js
+++ b/cjs/parser.js
@@ -44,7 +44,7 @@ debug("cwd %o", import_utils2.CWD);
function parseForESLint(code, options) {
try {
const { filePath } = options;
- options.documents ||= options.operations;
+ options.documents = options.documents || options.operations;
const { document } = (0, import_utils.parseGraphQLSDL)(filePath, code, {
...options.graphQLParserOptions,
noLocation: false
diff --git a/cjs/rules/graphql-js-validation.js b/cjs/rules/graphql-js-validation.js
index 9130aae0f12847ce0d9cd69c7dae673d80f75de4..168cdf270ba1dfc39e8f5002b76b5242b154f1c5 100644
--- a/cjs/rules/graphql-js-validation.js
+++ b/cjs/rules/graphql-js-validation.js
@@ -49,7 +49,7 @@ function validateDocument({
};
if (token) {
loc = // if cursor on `@` symbol than use next node
- token.type === "@" ? sourceCode.getNodeByRangeIndex(token.range[1] + 1).loc : token.loc;
+ token.type === "@" ? sourceCode.getNodeByRangeIndex(token.range[1] + 1).loc : token.loc;
}
const didYouMeanContent = error.message.match(/Did you mean (?<content>.*)\?$/)?.groups.content;
const matches = didYouMeanContent ? [...didYouMeanContent.matchAll(/"(?<name>[^"]*)"/g)] : [];
@@ -407,7 +407,7 @@ const GRAPHQL_JS_VALIDATIONS = Object.assign(
...siblings.getOperations(),
...siblings.getFragments()
].reduce((map, { filePath, document }) => {
- map[filePath] ??= [];
+ map[filePath] = map[filePath] != null ? map[filePath] : [];
map[filePath].push(document);
return map;
}, /* @__PURE__ */ Object.create(null));
diff --git a/cjs/rules/no-one-place-fragments.js b/cjs/rules/no-one-place-fragments.js
index 0f4e2c34a00d4267eef2cf0f6e6e2d5369e4a11f..adbee674fbda8710acad8690dc7c637d8e6f1956 100644
--- a/cjs/rules/no-one-place-fragments.js
+++ b/cjs/rules/no-one-place-fragments.js
@@ -87,7 +87,7 @@ const rule = {
(0, import_graphql.visit)(document, {
FragmentSpread({ name }) {
const spreadName = name.value;
- usedFragmentsMap[spreadName] ||= [];
+ usedFragmentsMap[spreadName] = usedFragmentsMap[spreadName] || [];
usedFragmentsMap[spreadName].push(relativeFilePath);
}
});
diff --git a/cjs/rules/no-unused-fields.js b/cjs/rules/no-unused-fields.js
index dab854e13820dcf4037cc51729354e67fbb3bf90..1f1b1ddd52119bea302e4998bff6a5a316ca0a3d 100644
--- a/cjs/rules/no-unused-fields.js
+++ b/cjs/rules/no-unused-fields.js
@@ -39,7 +39,7 @@ function getUsedFields(schema, operations) {
}
const parentTypeName = typeInfo.getParentType().name;
const fieldName = node.name.value;
- usedFields[parentTypeName] ??= /* @__PURE__ */ new Set();
+ usedFields[parentTypeName] = usedFields[parentTypeName] != null ? usedFields[parentTypeName] : /* @__PURE__ */ new Set();
usedFields[parentTypeName].add(fieldName);
}
});
21 changes: 0 additions & 21 deletions patches/@pkgr+utils+2.2.0.patch

This file was deleted.

6,857 changes: 6,857 additions & 0 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

114 changes: 63 additions & 51 deletions test/prettier.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable sonarjs/no-duplicate-string */

/**
* @file Runs `prettier` as an ESLint rule.
* @author Andres Suarez
@@ -14,9 +12,9 @@
// Requirements
// ------------------------------------------------------------------------------

const assert = require('assert');
const fs = require('fs');
const path = require('path');
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');

const { ESLint, RuleTester } = require('eslint');

@@ -31,7 +29,7 @@ const rule = eslintPluginPrettier.rules.prettier;
const eslint = new ESLint({
baseConfig: {
parserOptions: {
ecmaVersion: 2021,
ecmaVersion: 'latest',
ecmaFeatures: {
jsx: true,
},
@@ -58,8 +56,8 @@ const eslint = new ESLint({
},
},
{
files: '**/@ota-meshi/eslint-plugin-svelte/*.svelte',
extends: ['plugin:@ota-meshi/svelte/recommended'],
files: '**/eslint-plugin-svelte/*.svelte',
extends: ['plugin:svelte/recommended'],
},
],
},
@@ -184,7 +182,9 @@ atGraphqlEslintRuleTester.run('@graphql-eslint/eslint-plugin', rule, {
// `newRuleTester({processor: require('eslint-plugin-graphql').processor['.graphql']})
// and then pass in pure graphql into the code value.
const eslintPluginGraphqlRuleTester = new RuleTester({
parserOptions: { ecmaVersion: 2015 },
parserOptions: {
ecmaVersion: 'latest',
},
});

eslintPluginGraphqlRuleTester.run('eslint-plugin-graphql', rule, {
@@ -200,9 +200,8 @@ eslintPluginGraphqlRuleTester.run('eslint-plugin-graphql', rule, {
const mdxRuleTester = new RuleTester({
parser: require.resolve('eslint-mdx'),
parserOptions: {
...require('eslint-mdx').DEFAULT_PARSER_OPTIONS,
// mdx-js/eslint-mdx#366
ecmaVersion: 2021,
sourceType: 'module',
ecmaVersion: 'latest',
},
});

@@ -260,42 +259,52 @@ runFixture('*.mdx', [
],
]);

runFixture('@ota-meshi/eslint-plugin-svelte/*.svelte', [
runFixture(
'eslint-plugin-svelte/*.svelte',
[
{
column: 5,
endColumn: 11,
endLine: 2,
fix: {
range: [13, 19],
text: 'name',
[
{
column: 5,
endColumn: 11,
endLine: 2,
fix: {
range: [13, 19],
text: 'name',
},
line: 2,
message: 'Replace `·name·` with `name`',
messageId: 'replace',
nodeType: null,
ruleId: 'prettier/prettier',
severity: 2,
},
line: 2,
message: 'Replace `·name·` with `name`',
messageId: 'replace',
nodeType: null,
ruleId: 'prettier/prettier',
severity: 2,
},
{
column: 4,
endColumn: 20,
endLine: 5,
fix: {
range: [45, 61],
text: '>Hello {name',
{
column: 4,
endColumn: 20,
endLine: 5,
fix: {
range: [45, 61],
text: '>Hello {name',
},
line: 5,
message: 'Replace `·>·Hello·{·name·` with `>Hello·{name`',
messageId: 'replace',
nodeType: null,
ruleId: 'prettier/prettier',
severity: 2,
},
line: 5,
message: 'Replace `·>·Hello·{·name·` with `>Hello·{name`',
messageId: 'replace',
nodeType: null,
ruleId: 'prettier/prettier',
severity: 2,
},
],
],
]);
// FIXME: https://github.com/sveltejs/prettier-plugin-svelte/issues/317
true,
);

runFixture('eslint-plugin-svelte3/*.svelte', [[], []]);
runFixture(
'eslint-plugin-svelte3/*.svelte',
[[], []],
// FIXME: https://github.com/sveltejs/prettier-plugin-svelte/issues/317
true,
);

// ------------------------------------------------------------------------------
// Helpers
@@ -313,14 +322,12 @@ runFixture('eslint-plugin-svelte3/*.svelte', [[], []]);
function loadInvalidFixture(name) {
const filename = path.join(__dirname, 'invalid', name + '.txt');
const src = fs.readFileSync(filename, 'utf8');
const sections = src
.split(/^[A-Z]+:\n/m)
.map(x => x.replace(/(?=\n)\n$/, ''));
const sections = src.split(/^[A-Z]+:\n/m).map(x => x.replace(/\n$/, ''));
const item = {
code: sections[1],
output: sections[2],
options: eval(sections[3]), // eslint-disable-line no-eval, sonar/code-eval
errors: eval(sections[4]), // eslint-disable-line no-eval, sonar/code-eval
options: eval(sections[3]), // eslint-disable-line no-eval
errors: eval(sections[4]), // eslint-disable-line no-eval
filename: getPrettierRcJsFilename('double-quote', name + '.txt'),
};
if (sections.length >= 6) {
@@ -343,10 +350,14 @@ function getPrettierRcJsFilename(dir, file = 'dummy.js') {
/**
*
* @param {string} pattern
* @param {import('eslint').Linter.LintMessage[]} asserts
* @param {import('eslint').Linter.LintMessage[][]} asserts
* @param {boolean} [skip]
* @returns {Promise<void>}
*/
async function runFixture(pattern, asserts) {
async function runFixture(pattern, asserts, skip) {
if (skip) {
return;
}
try {
const results = await eslint.lintFiles([`test/fixtures/${pattern}`]);
return assert.deepStrictEqual(
@@ -355,6 +366,7 @@ async function runFixture(pattern, asserts) {
);
} catch (err) {
console.error(err);
process.exitCode = 1;
// eslint-disable-next-line n/no-process-exit -- the fix is not correctly working
process.exit(1);
}
}
160 changes: 160 additions & 0 deletions worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// @ts-check

/**
* @typedef {import('prettier').FileInfoOptions} FileInfoOptions
* @typedef {import('prettier').Options & { onDiskFilepath: string, parserPath: string, usePrettierrc?: boolean }} Options
*/

const { runAsWorker } = require('synckit');

/**
* @type {typeof import('prettier')}
*/
let prettier;

runAsWorker(
/**
* @param {string} source - The source code to format.
* @param {Options} options - The prettier options.
* @param {FileInfoOptions} eslintFileInfoOptions - The file info options.
* @returns {Promise<string | undefined>} The formatted source code.
*/
async (
source,
{
filepath,
onDiskFilepath,
parserPath,
usePrettierrc,
...eslintPrettierOptions
},
eslintFileInfoOptions,
) => {
if (!prettier) {
prettier = await import('prettier');
}

const prettierRcOptions = usePrettierrc
? await prettier.resolveConfig(onDiskFilepath, {
editorconfig: true,
})
: null;

const { ignored, inferredParser } = await prettier.getFileInfo(
onDiskFilepath,
{
resolveConfig: false,
withNodeModules: false,
ignorePath: '.prettierignore',
plugins: /** @type {string[] | undefined} */ (
prettierRcOptions ? prettierRcOptions.plugins : undefined
),
...eslintFileInfoOptions,
},
);

// Skip if file is ignored using a .prettierignore file
if (ignored) {
return;
}

const initialOptions = {};

// ESLint supports processors that let you extract and lint JS
// fragments within a non-JS language. In the cases where prettier
// supports the same language as a processor, we want to process
// the provided source code as javascript (as ESLint provides the
// rules with fragments of JS) instead of guessing the parser
// based off the filename. Otherwise, for instance, on a .md file we
// end up trying to run prettier over a fragment of JS using the
// markdown parser, which throws an error.
// Processors may set virtual filenames for these extracted blocks.
// If they do so then we want to trust the file extension they
// provide, and no override is needed.
// If the processor does not set any virtual filename (signified by
// `filepath` and `onDiskFilepath` being equal) AND we can't
// infer the parser from the filename, either because no filename
// was provided or because there is no parser found for the
// filename, use javascript.
// This is added to the options first, so that
// prettierRcOptions and eslintPrettierOptions can still override
// the parser.
//
// `parserBlocklist` should contain the list of prettier parser
// names for file types where:
// * Prettier supports parsing the file type
// * There is an ESLint processor that extracts JavaScript snippets
// from the file type.
if (filepath === onDiskFilepath) {
// The following list means the plugin process source into js content
// but with same filename, so we need to change the parser to `babel`
// by default.
// Related ESLint plugins are:
// 1. `eslint-plugin-graphql` (replacement: `@graphql-eslint/eslint-plugin`)
// 2. `eslint-plugin-html`
// 3. `eslint-plugin-markdown@1` (replacement: `eslint-plugin-markdown@2+`)
// 4. `eslint-plugin-svelte3` (replacement: `eslint-plugin-svelte@2+`)
const parserBlocklist = [null, 'markdown', 'html'];

let inferParserToBabel = parserBlocklist.includes(inferredParser);

switch (inferredParser) {
// it could be processed by `@graphql-eslint/eslint-plugin` or `eslint-plugin-graphql`
case 'graphql': {
if (
// for `eslint-plugin-graphql`, see https://github.com/apollographql/eslint-plugin-graphql/blob/master/src/index.js#L416
source.startsWith('ESLintPluginGraphQLFile`')
) {
inferParserToBabel = true;
}
break;
}
// it could be processed by `@ota-meshi/eslint-plugin-svelte`, `eslint-plugin-svelte` or `eslint-plugin-svelte3`
case 'svelte': {
// The `source` would be modified by `eslint-plugin-svelte3`
if (!parserPath.includes('svelte-eslint-parser')) {
// We do not support `eslint-plugin-svelte3`,
// the users should run `prettier` on `.svelte` files manually
return;
}
}
}

if (inferParserToBabel) {
initialOptions.parser = 'babel';
}
} else {
// Similar to https://github.com/prettier/stylelint-prettier/pull/22
// In all of the following cases ESLint extracts a part of a file to
// be formatted and there exists a prettier parser for the whole file.
// If you're interested in prettier you'll want a fully formatted file so
// you're about to run prettier over the whole file anyway.
// Therefore running prettier over just the style section is wasteful, so
// skip it.
const parserBlocklist = [
'babel',
'babylon',
'flow',
'typescript',
'vue',
'markdown',
'html',
'mdx',
'angular',
'svelte',
];
if (parserBlocklist.includes(/** @type {string} */ (inferredParser))) {
return;
}
}

const prettierOptions = {
...initialOptions,
...prettierRcOptions,
...eslintPrettierOptions,
filepath,
};

return prettier.format(source, prettierOptions);
},
);
8,561 changes: 0 additions & 8,561 deletions yarn.lock

This file was deleted.