Add option to require @prettier or @format pragma (#2772)
* Add option to require @prettier or @format pragma Fixes #2397. Inspired by `eslint-plugin-prettier` and the discussion in #2397, this implements requiring a special comment pragma to be present in a file's first comment in order to be formatted. This will help large codebases gradually transition to prettier over time without tons of churn or large code reviews. I implemented this as a standard prettier "option", not just a typical `argv` flag, as it is relevant in both the cli and the api. This way it can be provided programmatically, on the command line, or standardized in a prettierrc file so like the style options, every user can use this setting consistently and only apply prettier to relevant files, no mattier their editor integration. This requires the pragma begin with `@` (in fact it's inserted if the user doesn't provide it). Currently the usage implies it must be "prettier" or "format", but it can technically be any value other than "none", which is similar to the `trailingCommas` option. cc @vjeux * Don't quote anything in runPrettier; this is usually handled by a shell * Make --require-pragma a boolean option * Use jest-docblock to find pragmas without parsing the ast * Clarify docs * includes -> indexOf * Move test out of integration
This commit is contained in:
1 parent
fd937ec334
commit
d5e5d66407
13 files changed
+145
-2
No files matched your search
@@ -10,6 +10,7 @@ const normalizeOptions = require("./src/options").normalize;
|
||||
const parser = require("./src/parser");
|
||||
const printDocToDebug = require("./src/doc-debug").printDocToDebug;
|
||||
const config = require("./src/resolve-config");
|
||||
const docblock = require("jest-docblock");
|
||||
|
||||
function guessLineEnding(text) {
|
||||
const index = text.indexOf("\n");
|
||||
@@ -30,6 +31,11 @@ function attachComments(text, ast, opts) {
|
||||
return astComments;
|
||||
}
|
||||
|
||||
function hasPragma(text) {
|
||||
const pragmas = Object.keys(docblock.parse(docblock.extract(text)));
|
||||
return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1;
|
||||
}
|
||||
|
||||
function ensureAllCommentsPrinted(astComments) {
|
||||
if (!astComments) {
|
||||
return;
|
||||
@@ -56,6 +62,10 @@ function ensureAllCommentsPrinted(astComments) {
|
||||
}
|
||||
|
||||
function formatWithCursor(text, opts, addAlignmentSize) {
|
||||
if (opts.requirePragma && !hasPragma(text)) {
|
||||
return { formatted: text };
|
||||
}
|
||||
|
||||
text = stripBom(text);
|
||||
addAlignmentSize = addAlignmentSize || 0;
|
||||
|
||||
|
||||
Reference in new issue
Block a user