Skip to content

Commit 6de494f

Browse files
authoredMay 16, 2017
Merge with eslint-plugin-prettify (#21)
* Chore: Use eslint-plugin-prettier without symlink * Chore: Lint .eslintrc.js via CLI automatically * Chore: Update remaining repo links * New: Replace implementation with line-by-line reporting (fixes #17) This code is originally from zertosh/eslint-plugin-prettify@2fb5dfb. It's has been adjusted to conform to the existing ESLint style. * Fix: Use non-global line ending regex * Fix: Use unicode literals instead of escapes in showInvisibles * Fix: Use documented range form when calling insertTextAfterRange * Fix: Un-shebang test file * Fix: ESLint 4.x compat (handle shebangs and no deprecated APIs)
1 parent 6b69492 commit 6de494f

33 files changed

+881
-221
lines changed
 

‎.eslintignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
!.eslintrc.js

‎.eslintrc.js

+4-10
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,11 @@
11
'use strict';
22

3-
const fs = require('fs');
4-
const path = require('path');
5-
const PACKAGE_NAME = require('./package').name;
6-
const SYMLINK_LOCATION = path.join(__dirname, 'node_modules', PACKAGE_NAME);
7-
8-
// Symlink node_modules/{package name} to this directory so that ESLint resolves this plugin name correctly.
9-
if (!fs.existsSync(SYMLINK_LOCATION)) {
10-
fs.symlinkSync(__dirname, SYMLINK_LOCATION);
11-
}
3+
// Register ourselves as a plugin to avoid `node_modules` trickery.
4+
const Plugins = require('eslint/lib/config/plugins');
5+
Plugins.define('prettier', require('.'));
126

137
module.exports = {
14-
plugins: ['node', 'eslint-plugin', PACKAGE_NAME],
8+
plugins: ['node', 'eslint-plugin', 'prettier'],
159
extends: [
1610
'not-an-aardvark/node',
1711
'plugin:node/recommended',

‎CHANGELOG.md

-2
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,3 @@
1616
* Breaking: Make prettier a peerDependency ([#1](https://github.com/not-an-aardvark/eslint-plugin-prettier/issues/1)) ([d8a8992](https://github.com/not-an-aardvark/eslint-plugin-prettier/commit/d8a89922ddc6b747c474b62a0948deba6ea2657d))
1717
* Docs: add repo url to package.json ([2474bc9](https://github.com/not-an-aardvark/eslint-plugin-prettier/commit/2474bc9dd3f05dbd0b1fec38e27bc91a9cb0f1c7))
1818
* Docs: suggest prettier-eslint if eslint rules disagree with prettier ([3414437](https://github.com/not-an-aardvark/eslint-plugin-prettier/commit/341443754ae231a17d82f037f8b35663257d282a))
19-
20-

‎CONTRIBUTING.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,4 @@ npm test
1818

1919
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.
2020

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

‎LICENSE.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
The MIT License (MIT)
22
=====================
33

4-
Copyright © 2017 Teddy Katz
4+
Copyright © 2017 Andres Suarez and Teddy Katz
55

66
Permission is hereby granted, free of charge, to any person
77
obtaining a copy of this software and associated documentation

‎README.md

+85-45
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,118 @@
11
# eslint-plugin-prettier [![Build Status](https://travis-ci.org/prettier/eslint-plugin-prettier.svg?branch=master)](https://travis-ci.org/prettier/eslint-plugin-prettier)
22

3-
Runs [prettier](https://github.com/jlongster/prettier) as an eslint rule
3+
Runs [Prettier](https://github.com/prettier/prettier) as an [ESLint](http://eslint.org) rule and reports differences as individual ESLint issues.
44

5-
## Installation
5+
## Sample
66

7-
You'll first need to install [ESLint](http://eslint.org):
7+
```js
8+
error: Insert `,` (prettier/prettier) at pkg/commons-atom/ActiveEditorRegistry.js:22:25:
9+
20 | import {
10+
21 | observeActiveEditorsDebounced,
11+
> 22 | editorChangesDebounced
12+
| ^
13+
23 | } from './debounced';;
14+
24 |
15+
25 | import {observableFromSubscribeFunction} from '../commons-node/event';
816

9-
```
10-
$ npm install eslint --save-dev
11-
```
1217

13-
Next, install `prettier`:
18+
error: Delete `;` (prettier/prettier) at pkg/commons-atom/ActiveEditorRegistry.js:23:21:
19+
21 | observeActiveEditorsDebounced,
20+
22 | editorChangesDebounced
21+
> 23 | } from './debounced';;
22+
| ^
23+
24 |
24+
25 | import {observableFromSubscribeFunction} from '../commons-node/event';
25+
26 | import {cacheWhileSubscribed} from '../commons-node/observable';
1426

15-
```
16-
$ npm install prettier --save-dev
27+
28+
2 errors found.
1729
```
1830

19-
Finally, install `eslint-plugin-prettier`:
31+
> `./node_modules/.bin/eslint --format codeframe pkg/commons-atom/ActiveEditorRegistry.js` (code from [nuclide](https://github.com/facebook/nuclide)).
2032
21-
```
22-
$ npm install eslint-plugin-prettier --save-dev
23-
```
33+
## Installation
2434

25-
**Note:** If you installed ESLint globally (using the `-g` flag) then you must also install `eslint-plugin-prettier` globally.
35+
```sh
36+
npm install --save-dev prettier eslint-plugin-prettier
37+
```
2638

27-
## Usage
39+
**_`eslint-plugin-prettier` does not install Prettier or ESLint for you._** _You must install these yourself._
2840

29-
Add `prettier` to the plugins section of your `.eslintrc` configuration file. You can omit the `eslint-plugin-` prefix:
41+
Then, in your `.eslintrc`:
3042

3143
```json
3244
{
33-
"plugins": [
34-
"prettier"
35-
]
45+
"plugins": [
46+
"prettier"
47+
],
48+
"rules": {
49+
"prettier/prettier": "error"
50+
}
3651
}
3752
```
3853

54+
## Options
3955

40-
Then configure the `prettier` rule under the `rules` section:
56+
* The first option:
4157

42-
```json
43-
{
44-
"rules": {
45-
"prettier/prettier": "error"
46-
}
47-
}
48-
```
58+
- Objects are passed directly to Prettier as [options](https://github.com/prettier/prettier#api). Example:
59+
60+
```json
61+
"prettier/prettier": ["error", {"singleQuote": true, "parser": "flow"}]
62+
```
4963

50-
You can also pass [`prettier` configuration](https://github.com/prettier/prettier#api) as an option:
64+
- Or the string `"fb"` may be used to set "Facebook style" defaults:
5165

52-
```json
53-
{
54-
"rules": {
55-
"prettier/prettier": ["error", {"trailingComma": "es5", "singleQuote": true}]
56-
}
57-
}
58-
```
66+
```json
67+
"prettier/prettier": ["error", "fb"]
68+
```
5969

60-
The rule will report an error if your code does not match `prettier` style. The rule is autofixable -- if you run `eslint` with the `--fix` flag, your code will be formatted according to `prettier` style.
70+
Equivalent to:
6171

62-
---
72+
```json
73+
"prettier/prettier": ["error", {
74+
"singleQuote": true,
75+
"trailingComma": "all",
76+
"bracketSpacing": false,
77+
"jsxBracketSameLine": true,
78+
"parser": "flow"
79+
}]
80+
```
6381

64-
This plugin works best if you disable all other ESLint rules relating to code formatting, and only enable rules that detect patterns in the AST. (If another active ESLint rule disagrees with `prettier` about how code should be formatted, it will be impossible to avoid lint errors.) You can use [eslint-config-prettier](https://github.com/lydell/eslint-config-prettier) to disable all formatting-related ESLint rules. If your desired formatting does not match the `prettier` output, you should use a different tool such as [prettier-eslint](https://github.com/kentcdodds/prettier-eslint) instead.
82+
* The second option:
6583

66-
## Migrating to 2.0.0
84+
- A string with a pragma that triggers this rule. By default, this rule applies to all files. However, if you set a pragma (this option), only files with that pragma in the heading docblock will be checked. All pragmas must start with `@`. Example:
6785

68-
Starting in 2.0.0, `prettier` is a peerDependency of this module, rather than a dependency. This means that you can use any version of `prettier` with this plugin, but it also means that you need to install it separately and include it as a devDependency in your project.
86+
```json
87+
"prettier/prettier": ["error", null, "@prettier"]
88+
```
6989

70-
To install `prettier`, use:
90+
Only files with `@prettier` in the heading docblock will be checked:
7191

72-
```bash
73-
npm install prettier --save-dev
74-
```
92+
```js
93+
/** @prettier */
94+
95+
console.log(1 + 2 + 3);
96+
```
97+
98+
Or:
99+
100+
```js
101+
/**
102+
* @prettier
103+
*/
104+
105+
console.log(4 + 5 + 6);
106+
```
107+
108+
_This option is useful if you're migrating a large codebase and already use pragmas like `@flow`._
109+
110+
* The rule is autofixable -- if you run `eslint` with the `--fix` flag, your code will be formatted according to `prettier` style.
111+
112+
---
113+
114+
This plugin works best if you disable all other ESLint rules relating to code formatting, and only enable rules that detect patterns in the AST. (If another active ESLint rule disagrees with `prettier` about how code should be formatted, it will be impossible to avoid lint errors.) You can use [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) to disable all formatting-related ESLint rules. If your desired formatting does not match the `prettier` output, you should use a different tool such as [prettier-eslint](https://github.com/prettier/prettier-eslint) instead.
75115

76116
## Contributing
77117

78-
See [CONTRIBUTING.md](https://github.com/not-an-aardvark/eslint-plugin-prettier/blob/master/CONTRIBUTING.md)
118+
See [CONTRIBUTING.md](https://github.com/prettier/eslint-plugin-prettier/blob/master/CONTRIBUTING.md)

‎eslint-plugin-prettier.js

+313
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,313 @@
1+
/**
2+
* @fileoverview Runs `prettier` as an ESLint rule.
3+
* @author Andres Suarez
4+
*/
5+
6+
'use strict';
7+
8+
// ------------------------------------------------------------------------------
9+
// Requirements
10+
// ------------------------------------------------------------------------------
11+
12+
const diff = require('fast-diff');
13+
const docblock = require('jest-docblock');
14+
15+
// ------------------------------------------------------------------------------
16+
// Constants
17+
// ------------------------------------------------------------------------------
18+
19+
// Preferred Facebook style.
20+
const FB_PRETTIER_OPTIONS = {
21+
singleQuote: true,
22+
trailingComma: 'all',
23+
bracketSpacing: false,
24+
jsxBracketSameLine: true,
25+
parser: 'flow'
26+
};
27+
28+
const LINE_ENDING_RE = /\r\n|[\r\n\u2028\u2029]/;
29+
30+
// ------------------------------------------------------------------------------
31+
// Privates
32+
// ------------------------------------------------------------------------------
33+
34+
// Lazily-loaded Prettier.
35+
let prettier;
36+
37+
// ------------------------------------------------------------------------------
38+
// Helpers
39+
// ------------------------------------------------------------------------------
40+
41+
/**
42+
* Gets the location of a given index in the source code for a given context.
43+
* @param {RuleContext} context - The ESLint rule context.
44+
* @param {number} index - An index in the source code.
45+
* @returns {Object} An object containing numeric `line` and `column` keys.
46+
*/
47+
function getLocFromIndex(context, index) {
48+
// If `sourceCode.getLocFromIndex` is available from ESLint, use it.
49+
// Otherwise, use the private version from eslint/lib/ast-utils.
50+
// `sourceCode.getLocFromIndex` was added in ESLint 3.16.0.
51+
const sourceCode = context.getSourceCode();
52+
if (typeof sourceCode.getLocFromIndex === 'function') {
53+
return sourceCode.getLocFromIndex(index);
54+
}
55+
const astUtils = require('eslint/lib/ast-utils');
56+
return astUtils.getLocationFromRangeIndex(sourceCode, index);
57+
}
58+
59+
/**
60+
* Converts invisible characters to a commonly recognizable visible form.
61+
* @param {string} str - The string with invisibles to convert.
62+
* @returns {string} The converted string.
63+
*/
64+
function showInvisibles(str) {
65+
let ret = '';
66+
for (let i = 0; i < str.length; i++) {
67+
switch (str[i]) {
68+
case ' ':
69+
ret += '·'; // Middle Dot, \u00B7
70+
break;
71+
case '\n':
72+
ret += '⏎'; // Return Symbol, \u23ce
73+
break;
74+
case '\t':
75+
ret += '↹'; // Left Arrow To Bar Over Right Arrow To Bar, \u21b9
76+
break;
77+
default:
78+
ret += str[i];
79+
break;
80+
}
81+
}
82+
return ret;
83+
}
84+
85+
// ------------------------------------------------------------------------------
86+
// Rule Definition
87+
// ------------------------------------------------------------------------------
88+
89+
/**
90+
* Reports issues where the context's source code differs from the Prettier
91+
formatted version.
92+
* @param {RuleContext} context - The ESLint rule context.
93+
* @param {string} prettierSource - The Prettier formatted source.
94+
* @returns {void}
95+
*/
96+
function reportDifferences(context, prettierSource) {
97+
// fast-diff returns the differences between two texts as a series of
98+
// INSERT, DELETE or EQUAL operations. The results occur only in these
99+
// sequences:
100+
// /-> INSERT -> EQUAL
101+
// EQUAL | /-> EQUAL
102+
// \-> DELETE |
103+
// \-> INSERT -> EQUAL
104+
// Instead of reporting issues at each INSERT or DELETE, certain sequences
105+
// are batched together and are reported as a friendlier "replace" operation:
106+
// - A DELETE immediately followed by an INSERT.
107+
// - Any number of INSERTs and DELETEs where the joining EQUAL of one's end
108+
// and another's beginning does not have line endings (i.e. issues that occur
109+
// on contiguous lines).
110+
111+
const source = context.getSourceCode().text;
112+
const results = diff(source, prettierSource);
113+
114+
const batch = [];
115+
let offset = 0; // NOTE: INSERT never advances the offset.
116+
while (results.length) {
117+
const result = results.shift();
118+
const op = result[0];
119+
const text = result[1];
120+
switch (op) {
121+
case diff.INSERT:
122+
case diff.DELETE:
123+
batch.push(result);
124+
break;
125+
case diff.EQUAL:
126+
if (results.length) {
127+
if (batch.length) {
128+
if (LINE_ENDING_RE.test(text)) {
129+
flush();
130+
offset += text.length;
131+
} else {
132+
batch.push(result);
133+
}
134+
} else {
135+
offset += text.length;
136+
}
137+
}
138+
break;
139+
default:
140+
throw new Error(`Unexpected fast-diff operation "${op}"`);
141+
}
142+
if (batch.length && !results.length) {
143+
flush();
144+
}
145+
}
146+
147+
function flush() {
148+
let aheadDeleteText = '';
149+
let aheadInsertText = '';
150+
while (batch.length) {
151+
const next = batch.shift();
152+
const op = next[0];
153+
const text = next[1];
154+
switch (op) {
155+
case diff.INSERT:
156+
aheadInsertText += text;
157+
break;
158+
case diff.DELETE:
159+
aheadDeleteText += text;
160+
break;
161+
case diff.EQUAL:
162+
aheadDeleteText += text;
163+
aheadInsertText += text;
164+
break;
165+
}
166+
}
167+
if (aheadDeleteText && aheadInsertText) {
168+
reportReplace(context, offset, aheadDeleteText, aheadInsertText);
169+
} else if (!aheadDeleteText && aheadInsertText) {
170+
reportInsert(context, offset, aheadInsertText);
171+
} else if (aheadDeleteText && !aheadInsertText) {
172+
reportDelete(context, offset, aheadDeleteText);
173+
}
174+
offset += aheadDeleteText.length;
175+
}
176+
}
177+
178+
/**
179+
* Reports an "Insert ..." issue where text must be inserted.
180+
* @param {RuleContext} context - The ESLint rule context.
181+
* @param {number} offset - The source offset where to insert text.
182+
* @param {string} text - The text to be inserted.
183+
* @returns {void}
184+
*/
185+
function reportInsert(context, offset, text) {
186+
const pos = getLocFromIndex(context, offset);
187+
const range = [offset, offset];
188+
context.report({
189+
message: 'Insert `{{ code }}`',
190+
data: { code: showInvisibles(text) },
191+
loc: { start: pos, end: pos },
192+
fix(fixer) {
193+
return fixer.insertTextAfterRange(range, text);
194+
}
195+
});
196+
}
197+
198+
/**
199+
* Reports a "Delete ..." issue where text must be deleted.
200+
* @param {RuleContext} context - The ESLint rule context.
201+
* @param {number} offset - The source offset where to delete text.
202+
* @param {string} text - The text to be deleted.
203+
* @returns {void}
204+
*/
205+
function reportDelete(context, offset, text) {
206+
const start = getLocFromIndex(context, offset);
207+
const end = getLocFromIndex(context, offset + text.length);
208+
const range = [offset, offset + text.length];
209+
context.report({
210+
message: 'Delete `{{ code }}`',
211+
data: { code: showInvisibles(text) },
212+
loc: { start, end },
213+
fix(fixer) {
214+
return fixer.removeRange(range);
215+
}
216+
});
217+
}
218+
219+
/**
220+
* Reports a "Replace ... with ..." issue where text must be replaced.
221+
* @param {RuleContext} context - The ESLint rule context.
222+
* @param {number} offset - The source offset where to replace deleted text
223+
with inserted text.
224+
* @param {string} deleteText - The text to be deleted.
225+
* @param {string} insertText - The text to be inserted.
226+
* @returns {void}
227+
*/
228+
function reportReplace(context, offset, deleteText, insertText) {
229+
const start = getLocFromIndex(context, offset);
230+
const end = getLocFromIndex(context, offset + deleteText.length);
231+
const range = [offset, offset + deleteText.length];
232+
context.report({
233+
message: 'Replace `{{ deleteCode }}` with `{{ insertCode }}`',
234+
data: {
235+
deleteCode: showInvisibles(deleteText),
236+
insertCode: showInvisibles(insertText)
237+
},
238+
loc: { start, end },
239+
fix(fixer) {
240+
return fixer.replaceTextRange(range, insertText);
241+
}
242+
});
243+
}
244+
245+
// ------------------------------------------------------------------------------
246+
// Module Definition
247+
// ------------------------------------------------------------------------------
248+
249+
module.exports.rules = {
250+
prettier: {
251+
meta: {
252+
fixable: 'code',
253+
schema: [
254+
// Prettier options:
255+
{
256+
anyOf: [
257+
{ enum: [null, 'fb'] },
258+
{ type: 'object', properties: {}, additionalProperties: true }
259+
]
260+
},
261+
// Pragma:
262+
{ type: 'string', pattern: '^@\\w+$' }
263+
]
264+
},
265+
create(context) {
266+
const prettierOptions = context.options[0] === 'fb'
267+
? FB_PRETTIER_OPTIONS
268+
: context.options[0];
269+
270+
const pragma = context.options[1]
271+
? context.options[1].slice(1) // Remove leading @
272+
: null;
273+
274+
const sourceCode = context.getSourceCode();
275+
const source = sourceCode.text;
276+
277+
// The pragma is only valid if it is found in a block comment at the very
278+
// start of the file.
279+
if (pragma) {
280+
// ESLint 3.x reports the shebang as a "Line" node, while ESLint 4.x
281+
// reports it as a "Shebang" node. This works for both versions:
282+
const hasShebang = source.startsWith('#!');
283+
const allComments = sourceCode.getAllComments();
284+
const firstComment = hasShebang ? allComments[1] : allComments[0];
285+
if (
286+
!(firstComment &&
287+
firstComment.type === 'Block' &&
288+
firstComment.loc.start.line === (hasShebang ? 2 : 1) &&
289+
firstComment.loc.start.column === 0)
290+
) {
291+
return {};
292+
}
293+
const parsed = docblock.parse(firstComment.value);
294+
if (parsed[pragma] !== '') {
295+
return {};
296+
}
297+
}
298+
299+
return {
300+
Program() {
301+
if (!prettier) {
302+
// Prettier is expensive to load, so only load it if needed.
303+
prettier = require('prettier');
304+
}
305+
const prettierSource = prettier.format(source, prettierOptions);
306+
if (source !== prettierSource) {
307+
reportDifferences(context, prettierSource);
308+
}
309+
}
310+
};
311+
}
312+
}
313+
};

‎lib/index.js

-18
This file was deleted.

‎lib/rules/prettier.js

-75
This file was deleted.

‎package.json

+13-8
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,29 @@
55
"keywords": [
66
"eslint",
77
"eslintplugin",
8-
"eslint-plugin"
8+
"eslint-plugin",
9+
"prettier"
910
],
1011
"author": "Teddy Katz",
11-
"main": "lib/index.js",
12+
"files": [
13+
"eslint-plugin-prettier.js"
14+
],
15+
"main": "eslint-plugin-prettier.js",
1216
"scripts": {
13-
"lint": "eslint .eslintrc.js lib/ tests/ --ignore-pattern !.eslintrc.js",
14-
"test": "npm run lint && mocha tests --recursive"
17+
"lint": "eslint .",
18+
"test": "npm run lint && mocha"
1519
},
1620
"repository": {
1721
"type": "git",
18-
"url": "git+https://github.com/not-an-aardvark/eslint-plugin-prettier.git"
22+
"url": "git+https://github.com/prettier/eslint-plugin-prettier.git"
1923
},
2024
"bugs": {
21-
"url": "https://github.com/not-an-aardvark/eslint-plugin-prettier/issues"
25+
"url": "https://github.com/prettier/eslint-plugin-prettier/issues"
2226
},
23-
"homepage": "https://github.com/not-an-aardvark/eslint-plugin-prettier#readme",
27+
"homepage": "https://github.com/prettier/eslint-plugin-prettier#readme",
2428
"dependencies": {
25-
"requireindex": "~1.1.0"
29+
"fast-diff": "^1.1.1",
30+
"jest-docblock": "^20.0.1"
2631
},
2732
"peerDependencies": {
2833
"eslint": "^3.14.1",

‎test/invalid/01.txt

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
CODE:
2+
a();;;;;;
3+
4+
OUTPUT:
5+
a();
6+
7+
OPTIONS:
8+
[]
9+
10+
ERRORS:
11+
[
12+
{
13+
message: 'Delete `;;;;;`',
14+
line: 1, column: 5, endLine: 1, endColumn: 10,
15+
},
16+
]

‎test/invalid/02.txt

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
CODE:
2+
a();;;
3+
;;;
4+
5+
OUTPUT:
6+
a();
7+
8+
OPTIONS:
9+
[]
10+
11+
ERRORS:
12+
[
13+
{
14+
message: 'Delete `;;⏎;;;`',
15+
line: 1, column: 5, endLine: 2, endColumn: 4,
16+
},
17+
]

‎test/invalid/03.txt

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
CODE:
2+
a();;;
3+
;;;
4+
5+
OUTPUT:
6+
a();
7+
8+
OPTIONS:
9+
[]
10+
11+
ERRORS:
12+
[
13+
{
14+
message: 'Replace `··a();;;⏎;;` with `a()`',
15+
line: 1, column: 1, endLine: 2, endColumn: 3,
16+
},
17+
]

‎test/invalid/04.txt

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
CODE:
2+
var foo= "";
3+
4+
OUTPUT:
5+
var foo = "";
6+
7+
OPTIONS:
8+
[]
9+
10+
ERRORS:
11+
[
12+
{
13+
message: 'Insert `·`',
14+
line: 1, column: 8, endLine: 1, endColumn: 8,
15+
},
16+
]

‎test/invalid/05.txt

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
CODE:
2+
var foo="";
3+
4+
OUTPUT:
5+
var foo = "";
6+
7+
OPTIONS:
8+
[]
9+
10+
ERRORS:
11+
[
12+
{
13+
message: 'Replace `=` with `·=·`',
14+
line: 1, column: 8, endLine: 1, endColumn: 9,
15+
},
16+
]

‎test/invalid/06.txt

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
CODE:
2+
var foo='';;;
3+
4+
OUTPUT:
5+
var foo = "";
6+
7+
OPTIONS:
8+
[]
9+
10+
ERRORS:
11+
[
12+
{
13+
message: 'Replace `=\'\';;` with `·=·""`',
14+
line: 1, column: 8, endLine: 1, endColumn: 13,
15+
},
16+
]

‎test/invalid/07.txt

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
CODE:
2+
var foo='';;
3+
;;
4+
5+
OUTPUT:
6+
var foo = "";
7+
8+
OPTIONS:
9+
[]
10+
11+
ERRORS:
12+
[
13+
{
14+
message: 'Replace `=\'\';;⏎;` with `·=·""`',
15+
line: 1, column: 8, endLine: 2, endColumn: 2,
16+
},
17+
]

‎test/invalid/08.txt

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
CODE:
2+
var foo ='';
3+
4+
OUTPUT:
5+
var foo = "";
6+
7+
OPTIONS:
8+
[]
9+
10+
ERRORS:
11+
[
12+
{
13+
message: 'Replace `\'\'` with `·""`',
14+
line: 1, column: 10, endLine: 1, endColumn: 12,
15+
},
16+
]

‎test/invalid/09.txt

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
CODE:
2+
var foo ="";
3+
4+
OUTPUT:
5+
var foo = '';
6+
7+
OPTIONS:
8+
[{singleQuote: true}]
9+
10+
ERRORS:
11+
[
12+
{
13+
message: 'Replace `""` with `·\'\'`',
14+
line: 1, column: 10, endLine: 1, endColumn: 12,
15+
},
16+
]

‎test/invalid/10.txt

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
CODE:
2+
var a = {
3+
b: 1
4+
};
5+
6+
OUTPUT:
7+
var a = {
8+
b: 1
9+
};
10+
11+
OPTIONS:
12+
[{useTabs: true}]
13+
14+
ERRORS:
15+
[
16+
{
17+
message: 'Insert `↹`',
18+
line: 2, column: 1, endLine: 2, endColumn: 1,
19+
},
20+
]

‎test/invalid/11-a.txt

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
CODE:
2+
var a = {
3+
b: '',
4+
};
5+
6+
OUTPUT:
7+
var a = {
8+
b: ""
9+
};
10+
11+
OPTIONS:
12+
[]
13+
14+
ERRORS:
15+
[
16+
{
17+
message: 'Replace `\'\',` with `""`',
18+
line: 2, column: 6, endLine: 2, endColumn: 9,
19+
},
20+
]

‎test/invalid/11-b.txt

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
CODE:
2+
var a = {
3+
b: '',
4+
};
5+
6+
OUTPUT:
7+
var a = {
8+
b: ""
9+
};
10+
11+
OPTIONS:
12+
[null]
13+
14+
ERRORS:
15+
[
16+
{
17+
message: 'Replace `\'\',` with `""`',
18+
line: 2, column: 6, endLine: 2, endColumn: 9,
19+
},
20+
]

‎test/invalid/11-c.txt

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
CODE:
2+
/** @format */
3+
var a = {
4+
b: ""
5+
};
6+
7+
OUTPUT:
8+
/** @format */
9+
var a = {
10+
b: '',
11+
};
12+
13+
OPTIONS:
14+
['fb']
15+
16+
ERRORS:
17+
[
18+
{
19+
message: 'Replace `""` with `\'\',`',
20+
line: 3, column: 6, endLine: 3, endColumn: 8,
21+
},
22+
]

‎test/invalid/12.txt

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
CODE:
2+
/** @format */
3+
var foo = '';
4+
5+
OUTPUT:
6+
/** @format */
7+
var foo = "";
8+
9+
OPTIONS:
10+
[null, "@format"]
11+
12+
ERRORS:
13+
[
14+
{
15+
message: 'Replace `\'\'` with `""`',
16+
line: 2, column: 11, endLine: 2, endColumn: 13,
17+
},
18+
]

‎test/invalid/13.txt

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
CODE:
2+
var foo ='';var bar ='';var baz ='';
3+
4+
OUTPUT:
5+
var foo = "";
6+
var bar = "";
7+
var baz = "";
8+
9+
OPTIONS:
10+
[]
11+
12+
ERRORS:
13+
[
14+
{
15+
message: 'Replace `\'\';var·bar·=\'\';var·baz·=\'\'` with `·"";⏎var·bar·=·"";⏎var·baz·=·""`',
16+
line: 1, column: 10, endLine: 1, endColumn: 36,
17+
},
18+
]

‎test/invalid/14.txt

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
CODE:
2+
var foo ='';var bar ='';
3+
var baz ='';
4+
5+
OUTPUT:
6+
var foo = "";
7+
var bar = "";
8+
var baz = "";
9+
10+
OPTIONS:
11+
[]
12+
13+
ERRORS:
14+
[
15+
{
16+
message: 'Replace `\'\';var·bar·=\'\'` with `·"";⏎var·bar·=·""`',
17+
line: 1, column: 10, endLine: 1, endColumn: 24,
18+
},
19+
{
20+
message: 'Replace `\'\'` with `·""`',
21+
line: 2, column: 10, endLine: 2, endColumn: 12,
22+
},
23+
]

‎test/invalid/15.txt

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
CODE:
2+
var foo = { "bar": "", "baz": "" };
3+
4+
OUTPUT:
5+
var foo = { bar: "", baz: "" };
6+
7+
OPTIONS:
8+
[]
9+
10+
ERRORS:
11+
[
12+
{
13+
message: 'Replace `"bar":·"",·"baz"` with `bar:·"",·baz`',
14+
line: 1, column: 13, endLine: 1, endColumn: 29,
15+
},
16+
]

‎test/invalid/16.txt

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
CODE:
2+
var foo = ''
3+
OUTPUT:
4+
var foo = "";
5+
6+
OPTIONS:
7+
[]
8+
9+
ERRORS:
10+
[
11+
{
12+
message: 'Replace `\'\'` with `"";⏎`',
13+
line: 1, column: 11, endLine: 1, endColumn: 13,
14+
},
15+
]

‎test/invalid/17.txt

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
CODE:
2+
var foo = "";
3+
OUTPUT:
4+
var foo = "";
5+
6+
OPTIONS:
7+
[]
8+
9+
ERRORS:
10+
[
11+
{
12+
message: 'Insert `⏎`',
13+
line: 1, column: 14, endLine: 1, endColumn: 14,
14+
},
15+
]

‎test/invalid/18.txt

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
CODE:
2+
3+
var foo = "";
4+
5+
OUTPUT:
6+
var foo = "";
7+
8+
OPTIONS:
9+
[]
10+
11+
ERRORS:
12+
[
13+
{
14+
message: 'Delete `⏎`',
15+
line: 1, column: 1, endLine: 2, endColumn: 1,
16+
},
17+
]

‎test/invalid/19.txt

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
CODE:
2+
#!/usr/bin/env node
3+
/** @format */
4+
var foo = '';
5+
6+
OUTPUT:
7+
#!/usr/bin/env node
8+
/** @format */
9+
var foo = "";
10+
11+
OPTIONS:
12+
[null, '@format']
13+
14+
ERRORS:
15+
[
16+
{
17+
message: 'Replace `\'\'` with `""`',
18+
line: 3, column: 11, endLine: 3, endColumn: 13,
19+
},
20+
]

‎test/prettier.js

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/**
2+
* @fileoverview Runs `prettier` as an ESLint rule.
3+
* @author Andres Suarez
4+
*/
5+
6+
'use strict';
7+
8+
// This test is optimized for debuggability.
9+
// Please do not attempt to DRY this file or dynamically load the fixtures.
10+
11+
// ------------------------------------------------------------------------------
12+
// Requirements
13+
// ------------------------------------------------------------------------------
14+
15+
const fs = require('fs');
16+
const path = require('path');
17+
18+
const rule = require('..').rules.prettier;
19+
const RuleTester = require('eslint').RuleTester;
20+
21+
// ------------------------------------------------------------------------------
22+
// Tests
23+
// ------------------------------------------------------------------------------
24+
25+
const ruleTester = new RuleTester();
26+
27+
ruleTester.run('prettier', rule, {
28+
valid: [
29+
// Correct style.
30+
{ code: '"";\n' },
31+
// No pragma = No prettier check.
32+
{ code: '""\n', options: [null, '@format'] },
33+
// Facebook style uses single quotes.
34+
{ code: `'';\n`, options: ['fb'] },
35+
// Facebook style but missing pragma.
36+
{ code: `"";\n`, options: ['fb', '@format'] },
37+
// Facebook style with pragma.
38+
{ code: `/** @format */\n'';\n`, options: ['fb', '@format'] },
39+
// Shebang with pragma.
40+
{ code: `#!/bin/node\n/** @format */\n"";\n`, options: [null, '@format'] }
41+
],
42+
invalid: [
43+
'01',
44+
'02',
45+
'03',
46+
'04',
47+
'05',
48+
'06',
49+
'07',
50+
'08',
51+
'09',
52+
'10',
53+
'11-a',
54+
'11-b',
55+
'11-c',
56+
'12',
57+
'13',
58+
'14',
59+
'15',
60+
'16',
61+
'17',
62+
'18',
63+
'19'
64+
].map(loadInvalidFixture)
65+
});
66+
67+
// ------------------------------------------------------------------------------
68+
// Helpers
69+
// ------------------------------------------------------------------------------
70+
71+
/**
72+
* Reads a fixture file and returns an "invalid" case for use by RuleTester.
73+
* The fixture format aims to reduce the pain of debugging offsets by keeping
74+
* the lines and columns of the test code as close to what the rule will report
75+
* as possible.
76+
* @param {string} name - Fixture basename.
77+
* @returns {Object} A {code, output, options, errors} test object.
78+
*/
79+
function loadInvalidFixture(name) {
80+
const filename = path.join(__dirname, 'invalid', name + '.txt');
81+
const src = fs.readFileSync(filename, 'utf8');
82+
const sections = src
83+
.split(/^[A-Z]+:\n/m)
84+
.map(x => x.replace(/(?=\n)\n$/, ''));
85+
const item = {
86+
code: sections[1],
87+
output: sections[2],
88+
options: eval(sections[3]), // eslint-disable-line no-eval
89+
errors: eval(sections[4]) // eslint-disable-line no-eval
90+
};
91+
return item;
92+
}

‎tests/lib/rules/prettier.js

-61
This file was deleted.

0 commit comments

Comments
 (0)
Please sign in to comment.