diff --git a/commands.md b/commands.md index ea73d56f8..76452e1ef 100644 --- a/commands.md +++ b/commands.md @@ -35,10 +35,10 @@ However, if any of the items inside the array have a hard break, the array will ```js [ 1, - function() { + function () { return 2; }, - 3 + 3, ]; ``` diff --git a/docs/api.md b/docs/api.md index c6422418d..a0f11070d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -44,7 +44,7 @@ If `options.useCache` is `false`, all caching will be bypassed. ```js const text = fs.readFileSync(filePath, "utf8"); -prettier.resolveConfig(filePath).then(options => { +prettier.resolveConfig(filePath).then((options) => { const formatted = prettier.format(text, options); }); ``` @@ -70,8 +70,8 @@ The promise will be rejected if there was an error parsing the configuration fil The search starts at `process.cwd()`, or at `filePath` if provided. Please see the [cosmiconfig docs](https://github.com/davidtheclark/cosmiconfig#explorersearch) for details on how the resolving works. ```js -prettier.resolveConfigFile().then(filePath => { - prettier.resolveConfig(filePath).then(options => { +prettier.resolveConfigFile().then((filePath) => { + prettier.resolveConfig(filePath).then((options) => { const formatted = prettier.format(text, options); }); }); @@ -146,7 +146,7 @@ prettier.format("lodash ( )", { const ast = babel(text); ast.program.body[0].expression.callee.name = "_"; return ast; - } + }, }); // -> "_();\n" ``` diff --git a/docs/browser.md b/docs/browser.md index 50c2c70ec..8ad0ef9fd 100644 --- a/docs/browser.md +++ b/docs/browser.md @@ -21,7 +21,7 @@ See [Usage](#usage) below for examples. ``` @@ -34,7 +34,7 @@ import parserGraphql from "prettier/parser-graphql"; prettier.format("query { }", { parser: "graphql", - plugins: [parserGraphql] + plugins: [parserGraphql], }); ``` @@ -43,7 +43,7 @@ prettier.format("query { }", { ```js define([ "https://unpkg.com/prettier@2.0.0/standalone.js", - "https://unpkg.com/prettier@2.0.0/parser-graphql.js" + "https://unpkg.com/prettier@2.0.0/parser-graphql.js", ], (prettier, ...plugins) => { prettier.format("query { }", { parser: "graphql", plugins }); }); diff --git a/docs/configuration.md b/docs/configuration.md index 772e4c432..5651e690a 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -35,7 +35,7 @@ module.exports = { trailingComma: "es5", tabWidth: 4, semi: false, - singleQuote: true + singleQuote: true, }; ``` @@ -129,7 +129,7 @@ An example configuration repository is available [here](https://github.com/azz/p > ```js > module.exports = { > ...require("@company/prettier-config"), -> semi: false +> semi: false, > }; > ``` diff --git a/docs/plugins.md b/docs/plugins.md index 905dd4f42..3af1b01ff 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -27,7 +27,7 @@ When plugins cannot be found automatically, you can load them with: prettier.format("code", { parser: "foo", pluginSearchDirs: ["./dir-with-plugins"], - plugins: ["./foo-plugin"] + plugins: ["./foo-plugin"], }); ``` @@ -79,8 +79,8 @@ export const languages = [ name: "InterpretedDanceScript", // Parsers that can parse this language. // This can be built-in parsers, or parsers you have contributed via this plugin. - parsers: ["dance-parse"] - } + parsers: ["dance-parse"], + }, ]; ``` @@ -99,8 +99,8 @@ export const parsers = { hasPragma, locStart, locEnd, - preprocess - } + preprocess, + }, }; ``` @@ -139,8 +139,8 @@ export const printers = { "dance-ast": { print, embed, - insertPragma - } + insertPragma, + }, }; ``` @@ -264,7 +264,7 @@ const prettier = require("prettier"); const code = "(add 1 2)"; prettier.format(code, { parser: "lisp", - plugins: ["."] + plugins: ["."], }); ``` diff --git a/docs/rationale.md b/docs/rationale.md index 8ae87b11b..af9cba2e2 100644 --- a/docs/rationale.md +++ b/docs/rationale.md @@ -36,7 +36,7 @@ By default, Prettier’s printing algorithm prints expressions on a single line ```js const user = { name: "John Doe", - age: 30 + age: 30, }; ``` @@ -68,7 +68,7 @@ const user = { ```js const user = { name: "John Doe", - age: 30 + age: 30, }; ``` @@ -84,7 +84,7 @@ Just like with objects, decorators are used for a lot of different things. Somet ```js @Component({ selector: "hero-button", - template: `` + template: ``, }) class HeroButtonComponent { // These decorators were written inline and fit on the line so they stay @@ -198,7 +198,7 @@ Prettier can break long `import` statements across several lines: ```js import { CollectionDashboard, - DashboardPlaceholder + DashboardPlaceholder, } from "../components/collections/collection-dashboard/main"; ``` diff --git a/jest.config.js b/jest.config.js index 6a57763c9..336caa345 100644 --- a/jest.config.js +++ b/jest.config.js @@ -8,7 +8,7 @@ module.exports = { setupFiles: ["/tests_config/run_spec.js"], snapshotSerializers: [ "jest-snapshot-serializer-raw", - "jest-snapshot-serializer-ansi" + "jest-snapshot-serializer-ansi", ], testRegex: "jsfmt\\.spec\\.js$|__tests__/.*\\.js$", testPathIgnorePatterns: ["tests/new_react", "tests/more_react"], @@ -17,7 +17,7 @@ module.exports = { coveragePathIgnorePatterns: [ "/standalone.js", "/src/doc/doc-debug.js", - "/src/main/massage-ast.js" + "/src/main/massage-ast.js", ], coverageReporters: ["text", "html", "cobertura"], moduleNameMapper: { @@ -28,13 +28,13 @@ module.exports = { "graceful-fs": "/tests_config/fs.js", "prettier/local": "/tests_config/require_prettier.js", - "prettier/standalone": "/tests_config/require_standalone.js" + "prettier/standalone": "/tests_config/require_standalone.js", }, testEnvironment: "node", transform: {}, watchPlugins: [ "jest-watch-typeahead/filename", - "jest-watch-typeahead/testname" + "jest-watch-typeahead/testname", ], - reporters: ["default"].concat(ENABLE_TEST_RESULTS ? "jest-junit" : []) + reporters: ["default"].concat(ENABLE_TEST_RESULTS ? "jest-junit" : []), }; diff --git a/package.json b/package.json index 5376dcd79..f17760935 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "prettier", - "version": "2.0.0", + "version": "2.1.0-dev", "description": "Prettier is an opinionated code formatter", "bin": "./bin/prettier.js", "repository": "prettier/prettier", @@ -97,7 +97,7 @@ "jest-snapshot-serializer-ansi": "1.0.0", "jest-snapshot-serializer-raw": "1.1.0", "jest-watch-typeahead": "0.4.2", - "prettier": "1.19.1", + "prettier": "2.0.0", "rimraf": "3.0.2", "rollup": "2.1.0", "rollup-plugin-babel": "4.4.0", diff --git a/scripts/build/babel-plugins/transform-custom-require.js b/scripts/build/babel-plugins/transform-custom-require.js index ae2273880..2092bcc69 100644 --- a/scripts/build/babel-plugins/transform-custom-require.js +++ b/scripts/build/babel-plugins/transform-custom-require.js @@ -12,7 +12,7 @@ // require.cache // -module.exports = function(babel) { +module.exports = function (babel) { const t = babel.types; return { @@ -40,8 +40,8 @@ module.exports = function(babel) { ) ); } - } - } + }, + }, }; function isEvalRequire(node) { diff --git a/scripts/build/build.js b/scripts/build/build.js index 4f6517601..b4089f27d 100644 --- a/scripts/build/build.js +++ b/scripts/build/build.js @@ -13,7 +13,7 @@ const Cache = require("./cache"); // Errors in promises should be fatal. const loggedErrors = new Set(); -process.on("unhandledRejection", err => { +process.on("unhandledRejection", (err) => { // No need to print it twice. if (!loggedErrors.has(err)) { console.error(err); @@ -39,11 +39,11 @@ async function createBundle(bundleConfig, cache) { process.stdout.write(fitTerminal(output)); return bundler(bundleConfig, cache) - .catch(error => { + .catch((error) => { console.log(FAIL + "\n"); handleError(error); }) - .then(result => { + .then((result) => { if (result.cached) { console.log(CACHED); } else { @@ -66,7 +66,7 @@ async function cacheFiles() { for (const bundleConfig of bundleConfigs) { await execa("cp", [ path.join("dist", bundleConfig.output), - path.join(".cache", "files") + path.join(".cache", "files"), ]); } } catch (err) { @@ -81,7 +81,7 @@ async function preparePackage() { delete pkg.devDependencies; pkg.scripts = { prepublishOnly: - "node -e \"assert.equal(require('.').version, require('..').version)\"" + "node -e \"assert.equal(require('.').version, require('..').version)\"", }; pkg.files = ["*.js"]; await util.writeJson("dist/package.json", pkg); @@ -114,6 +114,6 @@ async function run(params) { run( minimist(process.argv.slice(2), { - boolean: ["purge-cache"] + boolean: ["purge-cache"], }) ); diff --git a/scripts/build/bundler.js b/scripts/build/bundler.js index 47c289772..871e7c439 100644 --- a/scripts/build/bundler.js +++ b/scripts/build/bundler.js @@ -34,14 +34,14 @@ const EXTERNALS = [ "tty", // See comment in jest.config.js - "graceful-fs" + "graceful-fs", ]; function getBabelConfig(bundle) { const config = { babelrc: false, plugins: bundle.babelPlugins || [], - compact: bundle.type === "plugin" ? false : "auto" + compact: bundle.type === "plugin" ? false : "auto", }; if (bundle.type === "core") { config.plugins.push( @@ -54,7 +54,7 @@ function getBabelConfig(bundle) { ">0.5%", "not ie 11", "not safari 5.1", - "not op_mini all" + "not op_mini all", ]; } config.presets = [ @@ -63,13 +63,13 @@ function getBabelConfig(bundle) { { targets, exclude: ["transform-async-to-generator"], - modules: false - } - ] + modules: false, + }, + ], ]; config.plugins.push([ require.resolve("@babel/plugin-proposal-object-rest-spread"), - { loose: true, useBuiltIns: true } + { loose: true, useBuiltIns: true }, ]); return config; } @@ -102,12 +102,12 @@ function getRollupConfig(bundle) { } console.warn(warning); - } + }, }; const replaceStrings = { "process.env.PRETTIER_TARGET": JSON.stringify(bundle.target), - "process.env.NODE_ENV": JSON.stringify("production") + "process.env.NODE_ENV": JSON.stringify("production"), }; if (bundle.target === "universal") { // We can't reference `process` in UMD bundles and this is @@ -121,7 +121,7 @@ function getRollupConfig(bundle) { config.plugins = [ replace({ values: replaceStrings, - delimiters: ["", ""] + delimiters: ["", ""], }), executable(), evaluate(), @@ -131,16 +131,16 @@ function getRollupConfig(bundle) { nativeShims(path.resolve(__dirname, "shims")), resolve({ extensions: [".js", ".json"], - preferBuiltins: bundle.target === "node" + preferBuiltins: bundle.target === "node", }), commonjs({ ignoreGlobal: bundle.target === "node", - ...bundle.commonjs + ...bundle.commonjs, }), externals(bundle.externals), bundle.target === "universal" && nodeGlobals(), babelConfig && babel(babelConfig), - bundle.type === "plugin" && terser() + bundle.type === "plugin" && terser(), ].filter(Boolean); if (bundle.target === "node") { @@ -154,7 +154,7 @@ function getRollupOutputOptions(bundle) { const options = { file: `dist/${bundle.output}`, strict: typeof bundle.strict === "undefined" ? true : bundle.strict, - paths: [{ "graceful-fs": "fs" }] + paths: [{ "graceful-fs": "fs" }], }; if (bundle.target === "node") { @@ -181,10 +181,10 @@ function getWebpackConfig(bundle) { test: /\.js$/, use: { loader: "babel-loader", - options: getBabelConfig(bundle) - } - } - ] + options: getBabelConfig(bundle), + }, + }, + ], }, output: { path: path.resolve(root, "dist"), @@ -192,15 +192,15 @@ function getWebpackConfig(bundle) { library: ["prettierPlugins", bundle.name], libraryTarget: "umd", // https://github.com/webpack/webpack/issues/6642 - globalObject: 'new Function("return this")()' - } + globalObject: 'new Function("return this")()', + }, }; if (bundle.terserOptions) { const TerserPlugin = require("terser-webpack-plugin"); config.optimization = { - minimizer: [new TerserPlugin(bundle.terserOptions)] + minimizer: [new TerserPlugin(bundle.terserOptions)], }; } @@ -209,7 +209,7 @@ function getWebpackConfig(bundle) { function runWebpack(config) { return new Promise((resolve, reject) => { - webpack(config, err => { + webpack(config, (err) => { if (err) { reject(err); } else { @@ -232,7 +232,7 @@ module.exports = async function createBundle(bundle, cache) { try { await execa("cp", [ path.join(cache.cacheDir, "files", bundle.output), - "dist" + "dist", ]); return { cached: true }; } catch (err) { diff --git a/scripts/build/cache.js b/scripts/build/cache.js index ead896fb5..1bcb061a9 100644 --- a/scripts/build/cache.js +++ b/scripts/build/cache.js @@ -21,12 +21,12 @@ function Cache(cacheDir, version) { this.updated = { version: this.version, checksums: {}, - files: {} + files: {}, }; } // Loads the manifest.json file with the information from the last build -Cache.prototype.load = async function() { +Cache.prototype.load = async function () { // This should never throw, if it does, let it fail the build const lockfile = await readFile("yarn.lock", "utf-8"); const lockfileHash = hashString(lockfile); @@ -60,7 +60,7 @@ Cache.prototype.load = async function() { // any (or the list itself) have changed. // This takes the same rollup config used for bundling to include files that are // resolved by specific plugins. -Cache.prototype.checkBundle = async function(id, inputOptions, outputOptions) { +Cache.prototype.checkBundle = async function (id, inputOptions, outputOptions) { const files = new Set(this.files[id]); const newFiles = (this.updated.files[id] = []); @@ -70,8 +70,8 @@ Cache.prototype.checkBundle = async function(id, inputOptions, outputOptions) { const { output } = await bundle.generate(outputOptions); const modules = output - .filter(mod => !/\0/.test(mod.facadeModuleId)) - .map(mod => [path.relative(ROOT, mod.facadeModuleId), mod.code]); + .filter((mod) => !/\0/.test(mod.facadeModuleId)) + .map((mod) => [path.relative(ROOT, mod.facadeModuleId), mod.code]); for (const [id, code] of modules) { newFiles.push(id); @@ -96,7 +96,7 @@ Cache.prototype.checkBundle = async function(id, inputOptions, outputOptions) { return !dirty && files.size === 0; }; -Cache.prototype.save = async function() { +Cache.prototype.save = async function () { try { await writeFile(this.manifest, JSON.stringify(this.updated, null, 2)); } catch (err) { @@ -109,10 +109,7 @@ function required(name) { } function hashString(string) { - return crypto - .createHash("md5") - .update(string) - .digest("hex"); + return crypto.createHash("md5").update(string).digest("hex"); } function getRollupConfig(rollupConfig) { @@ -120,12 +117,12 @@ function getRollupConfig(rollupConfig) { ...rollupConfig, onwarn() {}, plugins: rollupConfig.plugins.filter( - plugin => + (plugin) => // We're not interested in dependencies, we already check `yarn.lock` plugin.name !== "node-resolve" && // This is really slow, we need this "preflight" to be fast plugin.name !== "babel" - ) + ), }; } diff --git a/scripts/build/config.js b/scripts/build/config.js index 80d358b33..3aa7b7455 100644 --- a/scripts/build/config.js +++ b/scripts/build/config.js @@ -25,17 +25,17 @@ const PROJECT_ROOT = path.resolve(__dirname, "../.."); /** @type {Bundle[]} */ const parsers = [ { - input: "src/language-js/parser-babel.js" + input: "src/language-js/parser-babel.js", }, { input: "src/language-js/parser-flow.js", - strict: false + strict: false, }, { input: "src/language-js/parser-typescript.js", replace: { - 'require("@microsoft/typescript-etw")': "undefined" - } + 'require("@microsoft/typescript-etw")': "undefined", + }, }, { input: "src/language-js/parser-angular.js", @@ -45,16 +45,16 @@ const parsers = [ entries: [ { find: "lines-and-columns", - replacement: require.resolve("lines-and-columns") + replacement: require.resolve("lines-and-columns"), }, { find: "@angular/compiler/src", replacement: path.resolve( `${PROJECT_ROOT}/node_modules/@angular/compiler/esm2015/src` - ) - } - ] - } + ), + }, + ], + }, }, { input: "src/language-css/parser-postcss.js", @@ -68,16 +68,16 @@ const parsers = [ // postcss need keep_fnames when minify keep_fnames: true, // we don't transform class anymore, so we need keep_classnames too - keep_classnames: true - } - } - } + keep_classnames: true, + }, + }, + }, }, { - input: "src/language-graphql/parser-graphql.js" + input: "src/language-graphql/parser-graphql.js", }, { - input: "src/language-markdown/parser-markdown.js" + input: "src/language-markdown/parser-markdown.js", }, { input: "src/language-handlebars/parser-glimmer.js", @@ -89,25 +89,25 @@ const parsers = [ // https://github.com/prettier/prettier/issues/6656 { find: "handlebars", - replacement: require.resolve("handlebars/dist/cjs/handlebars.js") - } - ] + replacement: require.resolve("handlebars/dist/cjs/handlebars.js"), + }, + ], }, commonjs: { namedExports: { [require.resolve("handlebars/dist/cjs/handlebars.js")]: [ "parse", - "parseWithoutProcessing" + "parseWithoutProcessing", ], [require.resolve( "@glimmer/syntax/dist/modules/es2017/index.js" - )]: "default" + )]: "default", }, - ignore: ["source-map"] - } + ignore: ["source-map"], + }, }, { - input: "src/language-html/parser-html.js" + input: "src/language-html/parser-html.js", }, { input: "src/language-yaml/parser-yaml.js", @@ -117,18 +117,16 @@ const parsers = [ entries: [ { find: "lines-and-columns", - replacement: require.resolve("lines-and-columns") - } - ] - } - } -].map(parser => ({ + replacement: require.resolve("lines-and-columns"), + }, + ], + }, + }, +].map((parser) => ({ type: "plugin", target: "universal", - name: getFileOutput(parser) - .replace(/\.js$/, "") - .split("-")[1], - ...parser + name: getFileOutput(parser).replace(/\.js$/, "").split("-")[1], + ...parser, })); /** @type {Bundle[]} */ @@ -140,28 +138,28 @@ const coreBundles = [ externals: [path.resolve("src/common/third-party.js")], replace: { // from @iarna/toml/parse-string - "eval(\"require('util').inspect\")": "require('util').inspect" - } + "eval(\"require('util').inspect\")": "require('util').inspect", + }, }, { input: "src/document/index.js", name: "doc", type: "core", output: "doc.js", - target: "universal" + target: "universal", }, { input: "standalone.js", name: "prettier", type: "core", - target: "universal" + target: "universal", }, { input: "bin/prettier.js", type: "core", output: "bin-prettier.js", target: "node", - externals: [path.resolve("src/common/third-party.js")] + externals: [path.resolve("src/common/third-party.js")], }, { input: "src/common/third-party.js", @@ -173,16 +171,16 @@ const coreBundles = [ "require(filePath)": "eval('require')(filePath)", "require.cache": "eval('require').cache", // cosmiconfig@6 -> import-fresh can't find parentModule, since module is bundled - "parentModule(__filename)": "__filename" - } - } + "parentModule(__filename)": "__filename", + }, + }, ]; function getFileOutput(bundle) { return bundle.output || path.basename(bundle.input); } -module.exports = coreBundles.concat(parsers).map(bundle => ({ +module.exports = coreBundles.concat(parsers).map((bundle) => ({ ...bundle, - output: getFileOutput(bundle) + output: getFileOutput(bundle), })); diff --git a/scripts/build/rollup-plugins/evaluate.js b/scripts/build/rollup-plugins/evaluate.js index 46042e1a5..835422c5b 100644 --- a/scripts/build/rollup-plugins/evaluate.js +++ b/scripts/build/rollup-plugins/evaluate.js @@ -1,6 +1,6 @@ "use strict"; -module.exports = function() { +module.exports = function () { return { name: "evaluate", @@ -21,8 +21,8 @@ module.exports = function() { return { code: `var json = ${json}; export default json;`, - map: { mappings: "" } + map: { mappings: "" }, }; - } + }, }; }; diff --git a/scripts/build/rollup-plugins/executable.js b/scripts/build/rollup-plugins/executable.js index c643c4042..7505c8ee6 100644 --- a/scripts/build/rollup-plugins/executable.js +++ b/scripts/build/rollup-plugins/executable.js @@ -3,7 +3,7 @@ const fs = require("fs"); const path = require("path"); -module.exports = function() { +module.exports = function () { let banner; let entry; let file; @@ -44,6 +44,6 @@ module.exports = function() { if (banner && file) { fs.chmodSync(file, 0o755 & ~process.umask()); } - } + }, }; }; diff --git a/scripts/build/rollup-plugins/externals.js b/scripts/build/rollup-plugins/externals.js index 3fa716209..24b1b51b4 100644 --- a/scripts/build/rollup-plugins/externals.js +++ b/scripts/build/rollup-plugins/externals.js @@ -2,7 +2,7 @@ const path = require("path"); -module.exports = function(modules = []) { +module.exports = function (modules = []) { const requires = modules.reduce((obj, mod) => { obj[mod] = path.basename(mod).replace(/\.js$/, ""); return obj; @@ -15,6 +15,6 @@ module.exports = function(modules = []) { if (requires[importee]) { return `export default eval("require")("./${requires[importee]}");`; } - } + }, }; }; diff --git a/scripts/build/rollup-plugins/native-shims.js b/scripts/build/rollup-plugins/native-shims.js index 1c817d8fb..bb931a54c 100644 --- a/scripts/build/rollup-plugins/native-shims.js +++ b/scripts/build/rollup-plugins/native-shims.js @@ -7,7 +7,7 @@ const path = require("path"); const EMPTY = "export default {};"; const PREFIX = "\0shim:"; -module.exports = function(dir) { +module.exports = function (dir) { return { resolveId(importee) { if (importee.startsWith(PREFIX)) { @@ -29,6 +29,6 @@ module.exports = function(dir) { if (id.startsWith(PREFIX)) { return EMPTY; } - } + }, }; }; diff --git a/scripts/build/util.js b/scripts/build/util.js index 57a2a3fae..3776858bc 100644 --- a/scripts/build/util.js +++ b/scripts/build/util.js @@ -26,5 +26,5 @@ module.exports = { writeJson, copyFile, readFile, - writeFile + writeFile, }; diff --git a/scripts/check-deps.js b/scripts/check-deps.js index 08f46a918..85bfc539b 100644 --- a/scripts/check-deps.js +++ b/scripts/check-deps.js @@ -7,7 +7,7 @@ validateDependencyObject(pkg.dependencies); validateDependencyObject(pkg.devDependencies); function validateDependencyObject(object) { - Object.keys(object).forEach(key => { + Object.keys(object).forEach((key) => { if (object[key][0] === "^" || object[key][0] === "~") { console.error( chalk.red("error"), diff --git a/scripts/generate-schema.js b/scripts/generate-schema.js index 03a066bf3..55fe54190 100755 --- a/scripts/generate-schema.js +++ b/scripts/generate-schema.js @@ -23,8 +23,8 @@ function generateSchema(options) { optionsDefinition: { type: "object", properties: fromPairs( - options.map(option => [option.name, optionToSchema(option)]) - ) + options.map((option) => [option.name, optionToSchema(option)]) + ), }, overridesDefinition: { type: "object", @@ -41,40 +41,40 @@ function generateSchema(options) { description: "Include these files in this override.", oneOf: [ { type: "string" }, - { type: "array", items: { type: "string" } } - ] + { type: "array", items: { type: "string" } }, + ], }, excludeFiles: { description: "Exclude these files from this override.", oneOf: [ { type: "string" }, - { type: "array", items: { type: "string" } } - ] + { type: "array", items: { type: "string" } }, + ], }, options: { type: "object", description: "The options to apply for this override.", - $ref: "#/definitions/optionsDefinition" - } + $ref: "#/definitions/optionsDefinition", + }, }, - additionalProperties: false - } - } - } - } + additionalProperties: false, + }, + }, + }, + }, }, oneOf: [ { type: "object", allOf: [ { $ref: "#/definitions/optionsDefinition" }, - { $ref: "#/definitions/overridesDefinition" } - ] + { $ref: "#/definitions/overridesDefinition" }, + ], }, { - type: "string" - } - ] + type: "string", + }, + ], }; } @@ -86,7 +86,7 @@ function optionToSchema(option) { option.type === "choice" ? { oneOf: option.choices.map(choiceToSchema) } : { type: optionTypeToSchemaType(option.type) } - ) + ), }; } diff --git a/scripts/lint-changelog.js b/scripts/lint-changelog.js index 54cd2600f..cffddcc49 100644 --- a/scripts/lint-changelog.js +++ b/scripts/lint-changelog.js @@ -22,10 +22,10 @@ const CHANGELOG_CATEGORIES = [ "scss", "typescript", "vue", - "yaml" + "yaml", ]; const CHANGELOG_ROOT = path.join(__dirname, `../${CHANGELOG_DIR}`); -const showErrorMessage = message => { +const showErrorMessage = (message) => { console.error(message); process.exitCode = 1; }; @@ -106,10 +106,7 @@ for (const category of CHANGELOG_CATEGORIES) { continue; } const [, title] = titleMatch; - const categoryInTitle = title - .split(":") - .shift() - .trim(); + const categoryInTitle = title.split(":").shift().trim(); if (CHANGELOG_CATEGORIES.includes(categoryInTitle.toLowerCase())) { showErrorMessage( `[${displayPath}]: Please remove "${categoryInTitle}:" in title.` diff --git a/scripts/release/release.js b/scripts/release/release.js index 6e376e197..c6ca1c8ad 100644 --- a/scripts/release/release.js +++ b/scripts/release/release.js @@ -15,7 +15,7 @@ async function run() { const params = minimist(process.argv.slice(2), { string: ["version"], boolean: ["dry"], - alias: { v: "version" } + alias: { v: "version" }, }); const previousVersion = execSync("git describe --tags --abbrev=0") @@ -40,7 +40,7 @@ async function run() { require("./steps/push-to-git"), require("./steps/publish-to-npm"), require("./steps/bump-prettier"), - require("./steps/post-publish-steps") + require("./steps/post-publish-steps"), ]; try { @@ -58,10 +58,10 @@ async function run() { exec( [ "git fetch --tags", // Fetch git tags to get the previous version number (i.e. the latest tag) - "yarn install" // Install script's dependencies before any require + "yarn install", // Install script's dependencies before any require ].join(" && "), { cwd: __dirname }, - error => { + (error) => { if (error) { console.error(error); process.exit(1); diff --git a/scripts/release/steps/bump-prettier.js b/scripts/release/steps/bump-prettier.js index a8dfb314c..679e57149 100644 --- a/scripts/release/steps/bump-prettier.js +++ b/scripts/release/steps/bump-prettier.js @@ -13,7 +13,7 @@ async function commit(version) { await execa("git", [ "commit", "-am", - `Bump Prettier dependency to ${version}` + `Bump Prettier dependency to ${version}`, ]); await execa("git", ["push"]); } @@ -28,7 +28,7 @@ async function bump({ version, previousVersion, previousVersionOnMaster }) { await writeJson("package.json", pkg, { spaces: 2 }); } -module.exports = async function(params) { +module.exports = async function (params) { const { dry, version } = params; if (dry) { diff --git a/scripts/release/steps/check-git-status.js b/scripts/release/steps/check-git-status.js index 94f27da3c..7607a931e 100644 --- a/scripts/release/steps/check-git-status.js +++ b/scripts/release/steps/check-git-status.js @@ -2,7 +2,7 @@ const execa = require("execa"); -module.exports = async function() { +module.exports = async function () { const status = await execa.stdout("git", ["status", "--porcelain"]); if (status) { diff --git a/scripts/release/steps/generate-bundles.js b/scripts/release/steps/generate-bundles.js index 16051f512..c2dd2c260 100644 --- a/scripts/release/steps/generate-bundles.js +++ b/scripts/release/steps/generate-bundles.js @@ -3,7 +3,7 @@ const chalk = require("chalk"); const { runYarn, logPromise, readJson } = require("../utils"); -module.exports = async function({ version }) { +module.exports = async function ({ version }) { await logPromise("Generating bundles", runYarn(["build", "--purge-cache"])); const builtPkg = await readJson("dist/package.json"); diff --git a/scripts/release/steps/install-dependencies.js b/scripts/release/steps/install-dependencies.js index 89453c081..375b91bb6 100644 --- a/scripts/release/steps/install-dependencies.js +++ b/scripts/release/steps/install-dependencies.js @@ -15,6 +15,6 @@ async function install() { } } -module.exports = function() { +module.exports = function () { return logPromise("Installing NPM dependencies", install()); }; diff --git a/scripts/release/steps/post-publish-steps.js b/scripts/release/steps/post-publish-steps.js index de9c11cd7..a9c70775b 100644 --- a/scripts/release/steps/post-publish-steps.js +++ b/scripts/release/steps/post-publish-steps.js @@ -18,8 +18,8 @@ async function checkSchema() { const remoteSchema = await logPromise( "Checking current schema in SchemaStore", fetch(RAW_URL) - .then(r => r.text()) - .then(t => t.trim()) + .then((r) => r.text()) + .then((t) => t.trim()) ); if (schema === remoteSchema) { @@ -44,7 +44,7 @@ function twitterAnnouncement() { `); } -module.exports = async function() { +module.exports = async function () { const steps = [await checkSchema(), twitterAnnouncement()].filter(Boolean); console.log(chalk.bold.green("The script has finished!\n")); diff --git a/scripts/release/steps/publish-to-npm.js b/scripts/release/steps/publish-to-npm.js index 141ad788f..141d9e742 100644 --- a/scripts/release/steps/publish-to-npm.js +++ b/scripts/release/steps/publish-to-npm.js @@ -5,7 +5,7 @@ const dedent = require("dedent"); const execa = require("execa"); const { logPromise, waitForEnter } = require("../utils"); -module.exports = async function({ dry, version }) { +module.exports = async function ({ dry, version }) { if (dry) { return; } @@ -14,7 +14,7 @@ module.exports = async function({ dry, version }) { "Publishing to npm", execa("npm", ["publish"], { cwd: "./dist", - stdio: "inherit" // we need to input OTP if 2FA enabled + stdio: "inherit", // we need to input OTP if 2FA enabled }) ); diff --git a/scripts/release/steps/push-to-git.js b/scripts/release/steps/push-to-git.js index 9a3bd5020..659951715 100644 --- a/scripts/release/steps/push-to-git.js +++ b/scripts/release/steps/push-to-git.js @@ -10,7 +10,7 @@ async function pushGit({ version }) { await execa("git", ["push", "--tags"]); } -module.exports = function(params) { +module.exports = function (params) { if (params.dry) { return; } diff --git a/scripts/release/steps/run-tests.js b/scripts/release/steps/run-tests.js index 5aeb5bdf6..d768cf1b2 100644 --- a/scripts/release/steps/run-tests.js +++ b/scripts/release/steps/run-tests.js @@ -2,7 +2,7 @@ const { runYarn, logPromise } = require("../utils"); -module.exports = async function() { +module.exports = async function () { await logPromise("Running linter", runYarn("lint:eslint")); await logPromise("Running linter on docs", runYarn("lint:prettier")); await logPromise("Running tests", runYarn("test")); diff --git a/scripts/release/steps/update-changelog.js b/scripts/release/steps/update-changelog.js index 9cd23bf49..2f661fa09 100644 --- a/scripts/release/steps/update-changelog.js +++ b/scripts/release/steps/update-changelog.js @@ -15,7 +15,7 @@ function getBlogPostInfo(version) { return { file: `website/blog/${year}-${month}-${day}-${version}.md`, - path: `blog/${year}/${month}/${day}/${version}.html` + path: `blog/${year}/${month}/${day}/${version}.html`, }; } @@ -31,7 +31,7 @@ function writeChangelog({ version, previousVersion, releaseNotes }) { fs.writeFileSync("CHANGELOG.md", newEntry + "\n\n" + changelog); } -module.exports = async function({ version, previousVersion }) { +module.exports = async function ({ version, previousVersion }) { const semverDiff = semver.diff(version, previousVersion); if (semverDiff !== "patch") { @@ -39,7 +39,7 @@ module.exports = async function({ version, previousVersion }) { writeChangelog({ version, previousVersion, - releaseNotes: `🔗 [Release Notes](https://prettier.io/${blogPost.path})` + releaseNotes: `🔗 [Release Notes](https://prettier.io/${blogPost.path})`, }); if (fs.existsSync(blogPost.file)) { // Everything is fine, this step is finished diff --git a/scripts/release/steps/update-version.js b/scripts/release/steps/update-version.js index 32723b44b..f244e3f61 100644 --- a/scripts/release/steps/update-version.js +++ b/scripts/release/steps/update-version.js @@ -9,23 +9,23 @@ async function bump({ version }) { await writeJson("package.json", pkg, { spaces: 2 }); // Update github issue templates - processFile(".github/ISSUE_TEMPLATE/formatting.md", content => + processFile(".github/ISSUE_TEMPLATE/formatting.md", (content) => content.replace(/^(\*\*Prettier ).*?(\*\*)$/m, `$1${version}$2`) ); - processFile(".github/ISSUE_TEMPLATE/integration.md", content => + processFile(".github/ISSUE_TEMPLATE/integration.md", (content) => content.replace(/^(- Prettier Version: ).*?$/m, `$1${version}`) ); // Update unpkg link in docs - processFile("docs/browser.md", content => + processFile("docs/browser.md", (content) => content.replace(/(\/\/unpkg\.com\/prettier@)(?:.*?)\//g, `$1${version}/`) ); await execa("yarn", ["update-stable-docs"], { - cwd: "./website" + cwd: "./website", }); } -module.exports = async function(params) { +module.exports = async function (params) { await logPromise("Bumping version", bump(params)); }; diff --git a/scripts/release/steps/validate-new-version.js b/scripts/release/steps/validate-new-version.js index 6fb86f027..96de8c92e 100644 --- a/scripts/release/steps/validate-new-version.js +++ b/scripts/release/steps/validate-new-version.js @@ -3,7 +3,7 @@ const chalk = require("chalk"); const semver = require("semver"); -module.exports = async function({ version, previousVersion }) { +module.exports = async function ({ version, previousVersion }) { if (!semver.valid(version)) { throw new Error("Invalid version specified"); } diff --git a/scripts/release/utils.js b/scripts/release/utils.js index 274452708..66f35fee7 100644 --- a/scripts/release/utils.js +++ b/scripts/release/utils.js @@ -23,11 +23,11 @@ function logPromise(name, promise) { process.stdout.write(fitTerminal(name)); return promise - .then(result => { + .then((result) => { process.stdout.write(`${OK}\n`); return result; }) - .catch(err => { + .catch((err) => { process.stdout.write(`${FAIL}\n`); throw err; }); @@ -37,7 +37,7 @@ function runYarn(script) { if (typeof script === "string") { script = [script]; } - return execa("yarn", ["--silent"].concat(script)).catch(error => { + return execa("yarn", ["--silent"].concat(script)).catch((error) => { throw new Error(`\`yarn ${script}\` failed\n${error.stdout}`); }); } @@ -81,5 +81,5 @@ module.exports = { processFile, readJson, writeJson, - waitForEnter + waitForEnter, }; diff --git a/scripts/run-external-tests.js b/scripts/run-external-tests.js index 14ae12bc6..a318bee71 100644 --- a/scripts/run-external-tests.js +++ b/scripts/run-external-tests.js @@ -12,7 +12,7 @@ function tryFormat(file) { // Allow specifying the parser via an environment variable: parser: process.env.PARSER, // Use file extension detection otherwise: - filepath: file + filepath: file, }); } catch (error) { return error; @@ -30,10 +30,10 @@ function runExternalTests(patterns) { const results = { good: [], skipped: [], - bad: [] + bad: [], }; - testFiles.forEach(file => { + testFiles.forEach((file) => { const error = tryFormat(file); if (error instanceof SyntaxError) { @@ -60,7 +60,7 @@ function run(argv) { "Examples:", ' node scripts/run-external-tests.js "../TypeScript/tests/**/*.ts"', ' node scripts/run-external-tests.js "../flow/tests/**/*.js"', - ' PARSER=flow node scripts/run-external-tests.js "../flow/tests/**/*.js"' + ' PARSER=flow node scripts/run-external-tests.js "../flow/tests/**/*.js"', ].join("\n") ); return 1; @@ -77,7 +77,7 @@ function run(argv) { console.log(""); console.log( - results.bad.map(data => `${data.file}\n${data.error}`).join("\n\n\n") + results.bad.map((data) => `${data.file}\n${data.error}`).join("\n\n\n") ); return 0; diff --git a/scripts/sync-flow-tests.js b/scripts/sync-flow-tests.js index 579f54115..94c29fddf 100644 --- a/scripts/sync-flow-tests.js +++ b/scripts/sync-flow-tests.js @@ -14,7 +14,7 @@ function tryParse(file, content) { const ast = flowParser.parse(content, { esproposal_class_instance_fields: true, esproposal_class_static_fields: true, - esproposal_export_star_as: true + esproposal_export_star_as: true, }); if (ast.errors.length > 0) { @@ -36,7 +36,7 @@ function syncTests(syncDir) { throw new Error( [ "Couldn't find any files to copy.", - `Please make sure that \`${syncDir}\` exists and contains the flow tests.` + `Please make sure that \`${syncDir}\` exists and contains the flow tests.`, ].join("\n") ); } @@ -50,7 +50,7 @@ function syncTests(syncDir) { rimraf.sync(FLOW_TESTS_DIR); - filesToCopy.forEach(file => { + filesToCopy.forEach((file) => { const content = fs.readFileSync(file, "utf8"); const parseError = tryParse(file, content); @@ -77,7 +77,7 @@ function run(argv) { console.error( [ "You must provide the path to a flow tests directory to sync from!", - "Example: node scripts/sync-flow-tests.js ../flow/tests/" + "Example: node scripts/sync-flow-tests.js ../flow/tests/", ].join("\n") ); return 1; @@ -100,7 +100,7 @@ function run(argv) { "This is expected since flow tests for handling invalid code,", "but that's not interesting for Prettier's tests.", "This is the skipped stuff:", - "" + "", ] .concat(skipped, "") .join("\n") @@ -114,7 +114,7 @@ function run(argv) { `1. Optional: Adjust some ${SPEC_FILE_NAME} files.`, "2. Run `jest -u` to create snapshots.", "3. Run `git diff` to check how tests and snapshots have changed", - "4. Take a look at new snapshots to see if they're OK." + "4. Take a look at new snapshots to see if they're OK.", ].join("\n") ); diff --git a/scripts/test-dist.js b/scripts/test-dist.js index cd165162a..a9a8c41ac 100644 --- a/scripts/test-dist.js +++ b/scripts/test-dist.js @@ -30,9 +30,9 @@ const { code } = shell.exec(cmd, { ...process.env, NODE_ENV: "production", AST_COMPARE: "1", - PRETTIER_DIR: path.join(tmpDir, "node_modules/prettier") + PRETTIER_DIR: path.join(tmpDir, "node_modules/prettier"), }, - shell: true + shell: true, }); process.exit(code); diff --git a/src/cli/constant.js b/src/cli/constant.js index c4f9c2efb..b50b0d699 100644 --- a/src/cli/constant.js +++ b/src/cli/constant.js @@ -8,7 +8,7 @@ const categoryOrder = [ coreOptions.CATEGORY_FORMAT, coreOptions.CATEGORY_CONFIG, coreOptions.CATEGORY_EDITOR, - coreOptions.CATEGORY_OTHER + coreOptions.CATEGORY_OTHER, ]; /** @@ -77,7 +77,7 @@ const options = { description: dedent` Check if the given files are formatted, print a human-friendly summary message and paths to unformatted files (see also --list-different). - ` + `, }, color: { // The supports-color package (a sub sub dependency) looks directly at @@ -87,7 +87,7 @@ const options = { type: "boolean", default: true, description: "Colorize error messages.", - oppositeDescription: "Do not colorize error messages." + oppositeDescription: "Do not colorize error messages.", }, config: { type: "path", @@ -95,7 +95,7 @@ const options = { description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).", oppositeDescription: "Do not look for a configuration file.", - exception: value => value === false + exception: (value) => value === false, }, "config-precedence": { type: "choice", @@ -104,38 +104,38 @@ const options = { choices: [ { value: "cli-override", - description: "CLI options take precedence over config file" + description: "CLI options take precedence over config file", }, { value: "file-override", - description: "Config file take precedence over CLI options" + description: "Config file take precedence over CLI options", }, { value: "prefer-file", description: dedent` If a config file is found will evaluate it and ignore other CLI options. If no config file is found CLI options will evaluate as normal. - ` - } + `, + }, ], description: - "Define in which order config files and CLI options should be evaluated." + "Define in which order config files and CLI options should be evaluated.", }, "debug-benchmark": { // Run the formatting benchmarks. Requires 'benchmark' module to be installed. - type: "boolean" + type: "boolean", }, "debug-check": { // Run the formatting once again on the formatted output, throw if different. - type: "boolean" + type: "boolean", }, "debug-print-doc": { - type: "boolean" + type: "boolean", }, "debug-repeat": { // Repeat the formatting a few times and measure the average duration. type: "int", - default: 0 + default: 0, }, editorconfig: { type: "boolean", @@ -143,13 +143,13 @@ const options = { description: "Take .editorconfig into account when parsing configuration.", oppositeDescription: "Don't take .editorconfig into account when parsing configuration.", - default: true + default: true, }, "find-config-path": { type: "path", category: coreOptions.CATEGORY_CONFIG, description: - "Find and print the path to a configuration file for the given input file." + "Find and print the path to a configuration file for the given input file.", }, "file-info": { type: "path", @@ -157,7 +157,7 @@ const options = { Extract the following info (as JSON) for a given file path. Reported fields: * ignored (boolean) - true if file path is filtered by --ignore-path * inferredParser (string | null) - name of parser inferred from file path - ` + `, }, help: { type: "flag", @@ -166,46 +166,46 @@ const options = { Show CLI usage, or details about the given flag. Example: --help write `, - exception: value => value === "" + exception: (value) => value === "", }, "ignore-path": { type: "path", category: coreOptions.CATEGORY_CONFIG, default: ".prettierignore", - description: "Path to a file with patterns describing files to ignore." + description: "Path to a file with patterns describing files to ignore.", }, "list-different": { type: "boolean", category: coreOptions.CATEGORY_OUTPUT, alias: "l", description: - "Print the names of files that are different from Prettier's formatting (see also --check)." + "Print the names of files that are different from Prettier's formatting (see also --check).", }, loglevel: { type: "choice", description: "What level of logs to report.", default: "log", - choices: ["silent", "error", "warn", "log", "debug"] + choices: ["silent", "error", "warn", "log", "debug"], }, "support-info": { type: "boolean", - description: "Print support information as JSON." + description: "Print support information as JSON.", }, version: { type: "boolean", alias: "v", - description: "Print Prettier version." + description: "Print Prettier version.", }, "with-node-modules": { type: "boolean", category: coreOptions.CATEGORY_CONFIG, - description: "Process files inside 'node_modules' directory." + description: "Process files inside 'node_modules' directory.", }, write: { type: "boolean", category: coreOptions.CATEGORY_OUTPUT, - description: "Edit files in-place. (Beware!)" - } + description: "Edit files in-place. (Beware!)", + }, }; const usageSummary = dedent` @@ -218,5 +218,5 @@ const usageSummary = dedent` module.exports = { categoryOrder, options, - usageSummary + usageSummary, }; diff --git a/src/cli/expand-patterns.js b/src/cli/expand-patterns.js index cf361ddc0..846f831e7 100644 --- a/src/cli/expand-patterns.js +++ b/src/cli/expand-patterns.js @@ -36,7 +36,7 @@ function* expandPatterns(context) { if (noResults) { // If there was no files and no other errors, let's yield a general error. yield { - error: `No matching files. Patterns: ${context.filePatterns.join(" ")}` + error: `No matching files. Patterns: ${context.filePatterns.join(" ")}`, }; } } @@ -50,14 +50,14 @@ function* expandPatternsInternal(context) { ".git": true, ".svn": true, ".hg": true, - node_modules: context.argv["with-node-modules"] !== true + node_modules: context.argv["with-node-modules"] !== true, }; const globOptions = { dot: true, ignore: Object.keys(silentlyIgnoredDirs) - .filter(dir => silentlyIgnoredDirs[dir]) - .map(dir => "**/" + dir) + .filter((dir) => silentlyIgnoredDirs[dir]) + .map((dir) => "**/" + dir), }; let supportedFilesGlob; @@ -79,7 +79,7 @@ function* expandPatternsInternal(context) { entries.push({ type: "file", glob: escapePathForGlob(fixWindowsSlashes(pattern)), - input: pattern + input: pattern, }); } else if (stat.isDirectory()) { entries.push({ @@ -88,7 +88,7 @@ function* expandPatternsInternal(context) { escapePathForGlob(fixWindowsSlashes(pattern)) + "/" + getSupportedFilesGlob(), - input: pattern + input: pattern, }); } } else if (pattern[0] === "!") { @@ -98,7 +98,7 @@ function* expandPatternsInternal(context) { entries.push({ type: "glob", glob: fixWindowsSlashes(pattern), - input: pattern + input: pattern, }); } } @@ -123,13 +123,13 @@ function* expandPatternsInternal(context) { function getSupportedFilesGlob() { if (!supportedFilesGlob) { const extensions = flat( - context.languages.map(lang => lang.extensions || []) + context.languages.map((lang) => lang.extensions || []) ); const filenames = flat( - context.languages.map(lang => lang.filenames || []) + context.languages.map((lang) => lang.filenames || []) ); supportedFilesGlob = `**/{${extensions - .map(ext => "*" + (ext[0] === "." ? ext : "." + ext)) + .map((ext) => "*" + (ext[0] === "." ? ext : "." + ext)) .concat(filenames)}}`; } return supportedFilesGlob; @@ -140,13 +140,13 @@ const errorMessages = { globError: { file: "Unable to resolve file", dir: "Unable to expand directory", - glob: "Unable to expand glob pattern" + glob: "Unable to expand glob pattern", }, emptyResults: { file: "Explicitly specified file was ignored due to negative glob patterns", dir: "No supported files were found in the directory", - glob: "No files matching the pattern were found" - } + glob: "No files matching the pattern were found", + }, }; /** @@ -158,7 +158,7 @@ function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) { return path .relative(cwd, absolutePath) .split(path.sep) - .some(dir => ignoredDirectories[dir]); + .some((dir) => ignoredDirectories[dir]); } /** diff --git a/src/cli/index.js b/src/cli/index.js index 2bcecf1c4..ed5871def 100644 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -49,7 +49,7 @@ function run(args) { if (context.argv["support-info"]) { context.logger.log( prettier.format(stringify(prettier.getSupportInfo()), { - parser: "json" + parser: "json", }) ); process.exit(0); @@ -79,5 +79,5 @@ function run(args) { } module.exports = { - run + run, }; diff --git a/src/cli/minimist.js b/src/cli/minimist.js index a66cad2d9..500bc9639 100644 --- a/src/cli/minimist.js +++ b/src/cli/minimist.js @@ -8,14 +8,14 @@ const PLACEHOLDER = null; /** * unspecified boolean flag without default value is parsed as `undefined` instead of `false` */ -module.exports = function(args, options) { +module.exports = function (args, options) { const boolean = options.boolean || []; const defaults = options.default || {}; - const booleanWithoutDefault = boolean.filter(key => !(key in defaults)); + const booleanWithoutDefault = boolean.filter((key) => !(key in defaults)); const newDefaults = { ...defaults, - ...fromPairs(booleanWithoutDefault.map(key => [key, PLACEHOLDER])) + ...fromPairs(booleanWithoutDefault.map((key) => [key, PLACEHOLDER])), }; const parsed = minimist(args, { ...options, default: newDefaults }); diff --git a/src/cli/util.js b/src/cli/util.js index 6f25bed2e..6bb6b46c1 100644 --- a/src/cli/util.js +++ b/src/cli/util.js @@ -50,7 +50,7 @@ function cliifyOptions(object, apiDetailedOptionMap) { function diff(a, b) { return require("diff").createTwoFilesPatch("", "", a, b, "", "", { - context: 2 + context: 2, }); } @@ -111,7 +111,7 @@ function logFileInfoOrDie(context) { ignorePath: context.argv["ignore-path"], withNodeModules: context.argv["with-node-modules"], plugins: context.argv.plugin, - pluginSearchDirs: context.argv["plugin-search-dir"] + pluginSearchDirs: context.argv["plugin-search-dir"], }; context.logger.log( prettier.format( @@ -176,7 +176,7 @@ function format(context, input, opt) { "prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp) ); } else { - const stringify = obj => JSON.stringify(obj, null, 2); + const stringify = (obj) => JSON.stringify(obj, null, 2); const ast = stringify( prettier.__debug.parse(input, opt, /* massage */ true).ast ); @@ -221,11 +221,11 @@ function format(context, input, opt) { .add("format", () => { prettier.formatWithCursor(input, opt); }) - .on("cycle", event => { + .on("cycle", (event) => { const results = { benchmark: String(event.target), hz: event.target.hz, - ms: event.target.times.cycle * 1000 + ms: event.target.times.cycle * 1000, }; context.logger.debug( "'--debug-benchmark' measurements for formatWithCursor: " + @@ -252,7 +252,7 @@ function format(context, input, opt) { const results = { repeat, hz: 1000 / averageMs, - ms: averageMs + ms: averageMs, }; context.logger.debug( "'--debug-repeat' measurements for formatWithCursor: " + @@ -280,7 +280,7 @@ function getOptionsOrDie(context, filePath) { const options = prettier.resolveConfig.sync(filePath, { editorconfig: context.argv.editorconfig, - config: context.argv.config + config: context.argv.config, }); context.logger.debug("loaded options `" + JSON.stringify(options) + "`"); @@ -307,9 +307,9 @@ function getOptionsForFile(context, filepath) { context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, { - logger: context.logger + logger: context.logger, }) - ) + ), }; context.logger.debug( @@ -334,7 +334,7 @@ function parseArgsToOptions(context, overrideDefaults) { minimist(context.args, { string: minimistOptions.string, boolean: minimistOptions.boolean, - default: cliifyOptions(overrideDefaults, apiDetailedOptionMap) + default: cliifyOptions(overrideDefaults, apiDetailedOptionMap), }), context.detailedOptions, { logger: false } @@ -373,7 +373,7 @@ function formatStdin(context) { thirdParty .getStream(process.stdin) - .then(input => { + .then((input) => { if (relativeFilepath && ignorer.filter([relativeFilepath]).length === 0) { writeOutput(context, { formatted: input }); return; @@ -387,7 +387,7 @@ function formatStdin(context) { writeOutput(context, format(context, input, options), options); }) - .catch(error => { + .catch((error) => { handleError(context, relativeFilepath || "stdin", error); }); } @@ -442,7 +442,7 @@ function formatFiles(context) { const options = { ...getOptionsForFile(context, filename), - filepath: filename + filepath: filename, }; if (isTTY()) { @@ -550,16 +550,16 @@ function formatFiles(context) { function getOptionsWithOpposites(options) { // Add --no-foo after --foo. - const optionsWithOpposites = options.map(option => [ + const optionsWithOpposites = options.map((option) => [ option.description ? option : null, option.oppositeDescription ? { ...option, name: `no-${option.name}`, type: "boolean", - description: option.oppositeDescription + description: option.oppositeDescription, } - : null + : null, ]); return flat(optionsWithOpposites).filter(Boolean); } @@ -567,7 +567,7 @@ function getOptionsWithOpposites(options) { function createUsage(context) { const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help - option => + (option) => !( option.type === "boolean" && option.oppositeDescription && @@ -575,22 +575,24 @@ function createUsage(context) { ) ); - const groupedOptions = groupBy(options, option => option.category); + const groupedOptions = groupBy(options, (option) => option.category); const firstCategories = constant.categoryOrder.slice(0, -1); const lastCategories = constant.categoryOrder.slice(-1); const restCategories = Object.keys(groupedOptions).filter( - category => !constant.categoryOrder.includes(category) + (category) => !constant.categoryOrder.includes(category) ); const allCategories = [ ...firstCategories, ...restCategories, - ...lastCategories + ...lastCategories, ]; - const optionsUsage = allCategories.map(category => { + const optionsUsage = allCategories.map((category) => { const categoryOptions = groupedOptions[category] - .map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)) + .map((option) => + createOptionUsage(context, option, OPTION_USAGE_THRESHOLD) + ) .join("\n"); return `${category} options:\n\n${indent(categoryOptions, 2)}`; }); @@ -642,8 +644,8 @@ function createOptionUsageType(option) { return null; case "choice": return `<${option.choices - .filter(choice => !choice.deprecated && choice.since !== null) - .map(choice => choice.value) + .filter((choice) => !choice.deprecated && choice.since !== null) + .map((choice) => choice.value) .join("|")}>`; default: return `<${option.type}>`; @@ -652,13 +654,13 @@ function createOptionUsageType(option) { function createChoiceUsages(choices, margin, indentation) { const activeChoices = choices.filter( - choice => !choice.deprecated && choice.since !== null + (choice) => !choice.deprecated && choice.since !== null ); const threshold = activeChoices - .map(choice => choice.value.length) + .map((choice) => choice.value.length) .reduce((current, length) => Math.max(current, length), 0) + margin; - return activeChoices.map(choice => + return activeChoices.map((choice) => indent( createOptionUsageRow(choice.value, choice.description, threshold), indentation @@ -668,7 +670,7 @@ function createChoiceUsages(choices, margin, indentation) { function createDetailedUsage(context, flag) { const option = getOptionsWithOpposites(context.detailedOptions).find( - option => option.name === flag || option.alias === flag + (option) => option.name === flag || option.alias === flag ); const header = createOptionUsageHeader(option); @@ -692,7 +694,7 @@ function createDetailedUsage(context, flag) { const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map( - key => + (key) => `\n* ${key}: ${createDefaultValueDisplay( option.pluginDefaults[key] )}` @@ -730,7 +732,7 @@ function createLogger(logLevel) { warn: createLogFunc("warn", "yellow"), error: createLogFunc("error", "red"), debug: createLogFunc("debug", "blue"), - log: createLogFunc("log") + log: createLogFunc("log"), }; function createLogFunc(loggerName, color) { @@ -739,7 +741,7 @@ function createLogger(logLevel) { } const prefix = color ? `[${chalk[color](loggerName)}] ` : ""; - return function(message, opts) { + return function (message, opts) { opts = { newline: true, ...opts }; const stream = process[loggerName === "log" ? "stdout" : "stderr"]; stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : "")); @@ -779,17 +781,17 @@ function normalizeDetailedOption(name, option) { ...option, choices: option.choices && - option.choices.map(choice => { + option.choices.map((choice) => { const newChoice = { description: "", deprecated: false, - ...(typeof choice === "object" ? choice : { value: choice }) + ...(typeof choice === "object" ? choice : { value: choice }), }; if (newChoice.value === true) { newChoice.value = ""; // backward compatibility for original boolean option } return newChoice; - }) + }), }; } @@ -806,16 +808,16 @@ function createMinimistOptions(detailedOptions) { // we use vnopts' AliasSchema to handle aliases for better error messages alias: {}, boolean: detailedOptions - .filter(option => option.type === "boolean") - .map(option => [option.name].concat(option.alias || [])) + .filter((option) => option.type === "boolean") + .map((option) => [option.name].concat(option.alias || [])) .reduce((a, b) => a.concat(b)), string: detailedOptions - .filter(option => option.type !== "boolean") - .map(option => [option.name].concat(option.alias || [])) + .filter((option) => option.type !== "boolean") + .map((option) => [option.name].concat(option.alias || [])) .reduce((a, b) => a.concat(b)), default: detailedOptions .filter( - option => + (option) => !option.deprecated && (!option.forwardToApi || option.name === "plugin" || @@ -825,7 +827,7 @@ function createMinimistOptions(detailedOptions) { .reduce( (current, option) => ({ [option.name]: option.default, ...current }), {} - ) + ), }; } @@ -833,21 +835,21 @@ function createApiDetailedOptionMap(detailedOptions) { return fromPairs( detailedOptions .filter( - option => option.forwardToApi && option.forwardToApi !== option.name + (option) => option.forwardToApi && option.forwardToApi !== option.name ) - .map(option => [option.forwardToApi, option]) + .map((option) => [option.forwardToApi, option]) ); } function createDetailedOptionMap(supportOptions) { return fromPairs( - supportOptions.map(option => { + supportOptions.map((option) => { const newOption = { ...option, name: option.cliName || dashify(option.name), description: option.cliDescription || option.description, category: option.cliCategory || coreOptions.CATEGORY_FORMAT, - forwardToApi: option.name + forwardToApi: option.name, }; if (option.deprecated) { @@ -911,12 +913,12 @@ function updateContextOptions(context, plugins, pluginSearchDirs) { showUnreleased: true, showInternal: true, plugins, - pluginSearchDirs + pluginSearchDirs, }); const detailedOptionMap = normalizeDetailedOptionMap({ ...createDetailedOptionMap(supportOptions), - ...constant.options + ...constant.options, }); const detailedOptions = arrayify(detailedOptionMap, "name"); @@ -926,8 +928,8 @@ function updateContextOptions(context, plugins, pluginSearchDirs) { ...fromPairs( supportOptions .filter(({ deprecated }) => !deprecated) - .map(option => [option.name, option.default]) - ) + .map((option) => [option.name, option.default]) + ), }; Object.assign(context, { @@ -935,7 +937,7 @@ function updateContextOptions(context, plugins, pluginSearchDirs) { detailedOptions, detailedOptionMap, apiDefaultOptions, - languages + languages, }); } @@ -951,7 +953,7 @@ function pushContextPlugins(context, plugins, pluginSearchDirs) { "detailedOptions", "detailedOptionMap", "apiDefaultOptions", - "languages" + "languages", ]) ); updateContextOptions(context, plugins, pluginSearchDirs); @@ -977,11 +979,11 @@ function updateContextArgv(context, plugins, pluginSearchDirs) { function normalizeContextArgv(context, keys) { const detailedOptions = !keys ? context.detailedOptions - : context.detailedOptions.filter(option => keys.includes(option.name)); + : context.detailedOptions.filter((option) => keys.includes(option.name)); const argv = !keys ? context.argv : pick(context.argv, keys); context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, { - logger: context.logger + logger: context.logger, }); } //------------------------------context-util-end-------------------------------- @@ -997,5 +999,5 @@ module.exports = { initContext, logResolvedConfigPathOrDie, logFileInfoOrDie, - normalizeDetailedOptionMap + normalizeDetailedOptionMap, }; diff --git a/src/common/common-options.js b/src/common/common-options.js index f2ddcb2c9..c81add613 100644 --- a/src/common/common-options.js +++ b/src/common/common-options.js @@ -10,14 +10,14 @@ module.exports = { type: "boolean", default: true, description: "Print spaces between brackets.", - oppositeDescription: "Do not print spaces between brackets." + oppositeDescription: "Do not print spaces between brackets.", }, singleQuote: { since: "0.0.0", category: CATEGORY_COMMON, type: "boolean", default: false, - description: "Use single quotes instead of double quotes." + description: "Use single quotes instead of double quotes.", }, proseWrap: { since: "1.8.2", @@ -25,25 +25,25 @@ module.exports = { type: "choice", default: [ { since: "1.8.2", value: true }, - { since: "1.9.0", value: "preserve" } + { since: "1.9.0", value: "preserve" }, ], description: "How to wrap prose.", choices: [ { since: "1.9.0", value: "always", - description: "Wrap prose if it exceeds the print width." + description: "Wrap prose if it exceeds the print width.", }, { since: "1.9.0", value: "never", - description: "Do not wrap prose." + description: "Do not wrap prose.", }, { since: "1.9.0", value: "preserve", - description: "Wrap prose as-is." - } - ] - } + description: "Wrap prose as-is.", + }, + ], + }, }; diff --git a/src/common/create-ignorer.js b/src/common/create-ignorer.js index 8996b71d9..1fdae0944 100644 --- a/src/common/create-ignorer.js +++ b/src/common/create-ignorer.js @@ -20,7 +20,7 @@ async function createIgnorer(ignorePath, withNodeModules) { * @param {undefined | string} ignorePath * @param {undefined | boolean} withNodeModules */ -createIgnorer.sync = function(ignorePath, withNodeModules) { +createIgnorer.sync = function (ignorePath, withNodeModules) { const ignoreContent = !ignorePath ? null : getFileContentOrNull.sync(path.resolve(ignorePath)); diff --git a/src/common/end-of-line.js b/src/common/end-of-line.js index a9a565cb5..a2bd05cb4 100644 --- a/src/common/end-of-line.js +++ b/src/common/end-of-line.js @@ -21,5 +21,5 @@ function convertEndOfLineToChars(value) { module.exports = { guessEndOfLine, - convertEndOfLineToChars + convertEndOfLineToChars, }; diff --git a/src/common/errors.js b/src/common/errors.js index 056b790b8..d856b47d0 100644 --- a/src/common/errors.js +++ b/src/common/errors.js @@ -7,5 +7,5 @@ class UndefinedParserError extends Error {} module.exports = { ConfigError, DebugError, - UndefinedParserError + UndefinedParserError, }; diff --git a/src/common/get-file-info.js b/src/common/get-file-info.js index 688a98252..5c5f2b20d 100644 --- a/src/common/get-file-info.js +++ b/src/common/get-file-info.js @@ -32,7 +32,7 @@ async function getFileInfo(filePath, opts) { filePath: normalizeFilePath(filePath, opts.ignorePath), plugins: opts.plugins, resolveConfig: opts.resolveConfig, - sync: false + sync: false, }); } @@ -41,7 +41,7 @@ async function getFileInfo(filePath, opts) { * @param {FileInfoOptions} opts * @returns {FileInfoResult} */ -getFileInfo.sync = function(filePath, opts) { +getFileInfo.sync = function (filePath, opts) { if (typeof filePath !== "string") { throw new TypeError( `expect \`filePath\` to be a string, got \`${typeof filePath}\`` @@ -54,7 +54,7 @@ getFileInfo.sync = function(filePath, opts) { filePath: normalizeFilePath(filePath, opts.ignorePath), plugins: opts.plugins, resolveConfig: opts.resolveConfig, - sync: true + sync: true, }); }; @@ -63,16 +63,16 @@ function _getFileInfo({ filePath, plugins, resolveConfig = false, - sync = false + sync = false, }) { const fileInfo = { ignored: ignorer.ignores(filePath), - inferredParser: options.inferParser(filePath, plugins) || null + inferredParser: options.inferParser(filePath, plugins) || null, }; if (!fileInfo.inferredParser && resolveConfig) { if (!sync) { - return config.resolveConfig(filePath).then(resolvedConfig => { + return config.resolveConfig(filePath).then((resolvedConfig) => { if (resolvedConfig && resolvedConfig.parser) { fileInfo.inferredParser = resolvedConfig.parser; } diff --git a/src/common/internal-plugins.js b/src/common/internal-plugins.js index 323f094ff..16ed6da3c 100644 --- a/src/common/internal-plugins.js +++ b/src/common/internal-plugins.js @@ -75,8 +75,8 @@ module.exports = [ get __ng_directive() { return eval("require")("../language-js/parser-angular").parsers .__ng_directive; - } - } + }, + }, }, // CSS @@ -92,8 +92,8 @@ module.exports = [ }, get scss() { return eval("require")("../language-css/parser-postcss").parsers.css; - } - } + }, + }, }, // Handlebars @@ -103,8 +103,8 @@ module.exports = [ get glimmer() { return eval("require")("../language-handlebars/parser-glimmer").parsers .glimmer; - } - } + }, + }, }, // GraphQL @@ -114,8 +114,8 @@ module.exports = [ get graphql() { return eval("require")("../language-graphql/parser-graphql").parsers .graphql; - } - } + }, + }, }, // Markdown @@ -133,8 +133,8 @@ module.exports = [ get mdx() { return eval("require")("../language-markdown/parser-markdown").parsers .mdx; - } - } + }, + }, }, require("../language-html"), @@ -155,8 +155,8 @@ module.exports = [ // Lightning Web Components get lwc() { return eval("require")("../language-html/parser-html").parsers.lwc; - } - } + }, + }, }, // YAML @@ -165,7 +165,7 @@ module.exports = [ parsers: { get yaml() { return eval("require")("../language-yaml/parser-yaml").parsers.yaml; - } - } - } + }, + }, + }, ]; diff --git a/src/common/load-plugins.js b/src/common/load-plugins.js index 085a8154b..86042fa8a 100644 --- a/src/common/load-plugins.js +++ b/src/common/load-plugins.js @@ -34,31 +34,33 @@ function load(plugins, pluginSearchDirs) { const [externalPluginNames, externalPluginInstances] = partition( plugins, - plugin => typeof plugin === "string" + (plugin) => typeof plugin === "string" ); - const externalManualLoadPluginInfos = externalPluginNames.map(pluginName => { - let requirePath; - try { - // try local files - requirePath = eval("require").resolve( - path.resolve(process.cwd(), pluginName) - ); - } catch (_) { - // try node modules - requirePath = eval("require").resolve(pluginName, { - paths: [process.cwd()] - }); - } + const externalManualLoadPluginInfos = externalPluginNames.map( + (pluginName) => { + let requirePath; + try { + // try local files + requirePath = eval("require").resolve( + path.resolve(process.cwd(), pluginName) + ); + } catch (_) { + // try node modules + requirePath = eval("require").resolve(pluginName, { + paths: [process.cwd()], + }); + } - return { - name: pluginName, - requirePath - }; - }); + return { + name: pluginName, + requirePath, + }; + } + ); const externalAutoLoadPluginInfos = pluginSearchDirs - .map(pluginSearchDir => { + .map((pluginSearchDir) => { const resolvedPluginSearchDir = path.resolve( process.cwd(), pluginSearchDir @@ -81,11 +83,11 @@ function load(plugins, pluginSearchDirs) { ); } - return memoizedSearch(nodeModulesDir).map(pluginName => ({ + return memoizedSearch(nodeModulesDir).map((pluginName) => ({ name: pluginName, requirePath: eval("require").resolve(pluginName, { - paths: [resolvedPluginSearchDir] - }) + paths: [resolvedPluginSearchDir], + }), })); }) .reduce((a, b) => a.concat(b), []); @@ -94,9 +96,9 @@ function load(plugins, pluginSearchDirs) { externalManualLoadPluginInfos.concat(externalAutoLoadPluginInfos), "requirePath" ) - .map(externalPluginInfo => ({ + .map((externalPluginInfo) => ({ name: externalPluginInfo.name, - ...eval("require")(externalPluginInfo.requirePath) + ...eval("require")(externalPluginInfo.requirePath), })) .concat(externalPluginInstances); @@ -108,11 +110,11 @@ function findPluginsInNodeModules(nodeModulesDir) { [ "prettier-plugin-*/package.json", "@*/prettier-plugin-*/package.json", - "@prettier/plugin-*/package.json" + "@prettier/plugin-*/package.json", ], { cwd: nodeModulesDir, - expandDirectories: false + expandDirectories: false, } ); return pluginPackageJsonPaths.map(path.dirname); @@ -128,5 +130,5 @@ function isDirectory(dir) { module.exports = { loadPlugins: memoizedLoad, - clearCache + clearCache, }; diff --git a/src/common/parser-include-shebang.js b/src/common/parser-include-shebang.js index f337a1dff..b1423113a 100644 --- a/src/common/parser-include-shebang.js +++ b/src/common/parser-include-shebang.js @@ -14,13 +14,13 @@ function includeShebang(text, ast) { loc: { start: { line: 1, - column: 0 + column: 0, }, end: { line: 1, - column: index - } - } + column: index, + }, + }, }; ast.comments = [comment].concat(ast.comments); diff --git a/src/common/third-party.js b/src/common/third-party.js index ea8d4386f..0f139cc72 100644 --- a/src/common/third-party.js +++ b/src/common/third-party.js @@ -5,5 +5,5 @@ module.exports = { cosmiconfigSync: require("cosmiconfig").cosmiconfigSync, findParentDir: require("find-parent-dir").sync, getStream: require("get-stream"), - isCI: () => require("ci-info").isCI + isCI: () => require("ci-info").isCI, }; diff --git a/src/common/util-shared.js b/src/common/util-shared.js index 2c252e0c1..05120acdd 100644 --- a/src/common/util-shared.js +++ b/src/common/util-shared.js @@ -23,7 +23,7 @@ const { makeString, addLeadingComment, addDanglingComment, - addTrailingComment + addTrailingComment, } = require("./util"); module.exports = { @@ -49,5 +49,5 @@ module.exports = { makeString, addLeadingComment, addDanglingComment, - addTrailingComment + addTrailingComment, }; diff --git a/src/common/util.js b/src/common/util.js index bcc203a48..18cab0454 100644 --- a/src/common/util.js +++ b/src/common/util.js @@ -332,9 +332,9 @@ const PRECEDENCE = {}; [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], - ["**"] + ["**"], ].forEach((tier, i) => { - tier.forEach(op => { + tier.forEach((op) => { PRECEDENCE[op] = i; }); }); @@ -347,17 +347,17 @@ const equalityOperators = { "==": true, "!=": true, "===": true, - "!==": true + "!==": true, }; const multiplicativeOperators = { "*": true, "/": true, - "%": true + "%": true, }; const bitshiftOperators = { ">>": true, ">>>": true, - "<<": true + "<<": true, }; function shouldFlatten(parentOp, nodeOp) { @@ -751,7 +751,7 @@ function hasNodeIgnoreComment(node) { node && node.comments && node.comments.length > 0 && - node.comments.some(comment => comment.value.trim() === "prettier-ignore") + node.comments.some((comment) => comment.value.trim() === "prettier-ignore") ); } @@ -854,5 +854,5 @@ module.exports = { addLeadingComment, addDanglingComment, addTrailingComment, - isWithinParentArrayProperty + isWithinParentArrayProperty, }; diff --git a/src/config/resolve-config-editorconfig.js b/src/config/resolve-config-editorconfig.js index 7844d6a61..c026efd11 100644 --- a/src/config/resolve-config-editorconfig.js +++ b/src/config/resolve-config-editorconfig.js @@ -8,7 +8,7 @@ const mem = require("mem"); const editorConfigToPrettier = require("editorconfig-to-prettier"); const findProjectRoot = require("find-project-root"); -const jsonStringifyMem = fn => mem(fn, { cacheKey: JSON.stringify }); +const jsonStringifyMem = (fn) => mem(fn, { cacheKey: JSON.stringify }); const maybeParse = (filePath, parse) => { // findProjectRoot will throw an error if we pass a nonexistent directory to @@ -24,13 +24,13 @@ const maybeParse = (filePath, parse) => { return filePath && parse(filePath, { root }); }; -const editorconfigAsyncNoCache = async filePath => { +const editorconfigAsyncNoCache = async (filePath) => { const editorConfig = await maybeParse(filePath, editorconfig.parse); return editorConfigToPrettier(editorConfig); }; const editorconfigAsyncWithCache = jsonStringifyMem(editorconfigAsyncNoCache); -const editorconfigSyncNoCache = filePath => { +const editorconfigSyncNoCache = (filePath) => { return editorConfigToPrettier(maybeParse(filePath, editorconfig.parseSync)); }; const editorconfigSyncWithCache = jsonStringifyMem(editorconfigSyncNoCache); @@ -54,5 +54,5 @@ function clearCache() { module.exports = { getLoadFunction, - clearCache + clearCache, }; diff --git a/src/config/resolve-config.js b/src/config/resolve-config.js index 60abc6a36..5c851ecc5 100644 --- a/src/config/resolve-config.js +++ b/src/config/resolve-config.js @@ -9,17 +9,17 @@ const resolveEditorConfig = require("./resolve-config-editorconfig"); const loadToml = require("../utils/load-toml"); const getExplorerMemoized = mem( - opts => { + (opts) => { const cosmiconfig = thirdParty["cosmiconfig" + (opts.sync ? "Sync" : "")]; const explorer = cosmiconfig("prettier", { cache: opts.cache, - transform: result => { + transform: (result) => { if (result && result.config) { if (typeof result.config === "string") { const dir = path.dirname(result.filepath); try { const modulePath = eval("require").resolve(result.config, { - paths: [dir] + paths: [dir], }); result.config = eval("require")(modulePath); } catch (error) { @@ -48,11 +48,11 @@ const getExplorerMemoized = mem( ".prettierrc.yml", ".prettierrc.js", "prettier.config.js", - ".prettierrc.toml" + ".prettierrc.toml", ], loaders: { - ".toml": loadToml - } + ".toml": loadToml, + }, }); return explorer; @@ -72,24 +72,24 @@ function _resolveConfig(filePath, opts, sync) { const loadOpts = { cache: !!opts.useCache, sync: !!sync, - editorconfig: !!opts.editorconfig + editorconfig: !!opts.editorconfig, }; const { load, search } = getExplorer(loadOpts); const loadEditorConfig = resolveEditorConfig.getLoadFunction(loadOpts); const arr = [ opts.config ? load(opts.config) : search(filePath), - loadEditorConfig(filePath) + loadEditorConfig(filePath), ]; const unwrapAndMerge = ([result, editorConfigured]) => { const merged = { ...editorConfigured, - ...mergeOverrides(result, filePath) + ...mergeOverrides(result, filePath), }; - ["plugins", "pluginSearchDirs"].forEach(optionName => { + ["plugins", "pluginSearchDirs"].forEach((optionName) => { if (Array.isArray(merged[optionName])) { - merged[optionName] = merged[optionName].map(value => + merged[optionName] = merged[optionName].map((value) => typeof value === "string" && value.startsWith(".") // relative path ? path.resolve(path.dirname(result.filepath), value) : value @@ -126,7 +126,7 @@ async function resolveConfigFile(filePath) { return result ? result.filepath : null; } -resolveConfigFile.sync = filePath => { +resolveConfigFile.sync = (filePath) => { const { search } = getExplorer({ sync: true }); const result = search(filePath); return result ? result.filepath : null; @@ -160,8 +160,8 @@ function pathMatchesGlobs(filePath, patterns, excludedPatterns) { const opts = { matchBase: true, dot: true }; return ( - patternList.some(pattern => minimatch(filePath, pattern, opts)) && - !excludedPatternList.some(excludedPattern => + patternList.some((pattern) => minimatch(filePath, pattern, opts)) && + !excludedPatternList.some((excludedPattern) => minimatch(filePath, excludedPattern, opts) ) ); @@ -170,5 +170,5 @@ function pathMatchesGlobs(filePath, patterns, excludedPatterns) { module.exports = { resolveConfig, resolveConfigFile, - clearCache + clearCache, }; diff --git a/src/document/doc-builders.js b/src/document/doc-builders.js index ca814d601..c4cb1af80 100644 --- a/src/document/doc-builders.js +++ b/src/document/doc-builders.js @@ -85,7 +85,7 @@ function group(contents, opts) { id: opts.id, contents, break: !!opts.shouldBreak, - expandedStates: opts.expandedStates + expandedStates: opts.expandedStates, }; } @@ -157,7 +157,7 @@ function ifBreak(breakContents, flatContents, opts) { type: "if-break", breakContents, flatContents, - groupId: opts.groupId + groupId: opts.groupId, }; } @@ -180,7 +180,7 @@ const softline = { type: "line", soft: true }; const hardline = concat([{ type: "line", hard: true }, breakParent]); const literalline = concat([ { type: "line", hard: true, literal: true }, - breakParent + breakParent, ]); const cursor = { type: "cursor", placeholder: Symbol("cursor") }; @@ -245,5 +245,5 @@ module.exports = { addAlignmentToDoc, markAsRoot, dedentToRoot, - dedent + dedent, }; diff --git a/src/document/doc-debug.js b/src/document/doc-debug.js index bce1b34fa..3d29a39a6 100644 --- a/src/document/doc-debug.js +++ b/src/document/doc-debug.js @@ -23,7 +23,7 @@ function flattenDoc(doc) { breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null, flatContents: - doc.flatContents != null ? flattenDoc(doc.flatContents) : null + doc.flatContents != null ? flattenDoc(doc.flatContents) : null, }; } else if (doc.type === "group") { return { @@ -31,7 +31,7 @@ function flattenDoc(doc) { contents: flattenDoc(doc.contents), expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) - : doc.expandedStates + : doc.expandedStates, }; } else if (doc.contents) { return { ...doc, contents: flattenDoc(doc.contents) }; @@ -128,5 +128,5 @@ function printDoc(doc) { module.exports = { printDocToDebug(doc) { return printDoc(flattenDoc(doc)); - } + }, }; diff --git a/src/document/doc-printer.js b/src/document/doc-printer.js index 62fbe0b80..800e44e1c 100644 --- a/src/document/doc-printer.js +++ b/src/document/doc-printer.js @@ -287,7 +287,7 @@ function printDocToString(doc, options) { cmds.push([ ind, doc.break ? MODE_BREAK : MODE_FLAT, - doc.contents + doc.contents, ]); break; @@ -418,7 +418,7 @@ function printDocToString(doc, options) { const firstAndSecondContentFlatCmd = [ ind, MODE_FLAT, - concat([content, whitespace, secondContent]) + concat([content, whitespace, secondContent]), ]; const firstAndSecondContentFits = fits( firstAndSecondContentFlatCmd, @@ -532,7 +532,7 @@ function printDocToString(doc, options) { return { formatted: beforeCursor + aroundCursor + afterCursor, cursorNodeStart: beforeCursor.length, - cursorNodeText: aroundCursor + cursorNodeText: aroundCursor, }; } diff --git a/src/document/doc-utils.js b/src/document/doc-utils.js index ea5afd128..27afc174b 100644 --- a/src/document/doc-utils.js +++ b/src/document/doc-utils.js @@ -59,7 +59,7 @@ function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { function mapDoc(doc, cb) { if (doc.type === "concat" || doc.type === "fill") { - const parts = doc.parts.map(part => mapDoc(part, cb)); + const parts = doc.parts.map((part) => mapDoc(part, cb)); return cb({ ...doc, parts }); } else if (doc.type === "if-break") { const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb); @@ -197,7 +197,7 @@ function stripTrailingHardline(doc) { return { type: "concat", - parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart)) + parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart)), }; } } @@ -214,5 +214,5 @@ module.exports = { mapDoc, propagateBreaks, removeLines, - stripTrailingHardline + stripTrailingHardline, }; diff --git a/src/document/index.js b/src/document/index.js index ef40ddc3d..4020cf063 100644 --- a/src/document/index.js +++ b/src/document/index.js @@ -4,5 +4,5 @@ module.exports = { builders: require("./doc-builders"), printer: require("./doc-printer"), utils: require("./doc-utils"), - debug: require("./doc-debug") + debug: require("./doc-debug"), }; diff --git a/src/index.js b/src/index.js index 30a1706cf..cf9abe856 100644 --- a/src/index.js +++ b/src/index.js @@ -18,7 +18,7 @@ function _withPlugins( const opts = args[optsArgIdx] || {}; args[optsArgIdx] = { ...opts, - plugins: plugins.loadPlugins(opts.plugins, opts.pluginSearchDirs) + plugins: plugins.loadPlugins(opts.plugins, opts.pluginSearchDirs), }; return fn(...args); }; @@ -72,6 +72,6 @@ module.exports = { formatAST: withPlugins(core.formatAST), formatDoc: withPlugins(core.formatDoc), printToDoc: withPlugins(core.printToDoc), - printDocToString: withPlugins(core.printDocToString) - } + printDocToString: withPlugins(core.printDocToString), + }, }; diff --git a/src/language-css/clean.js b/src/language-css/clean.js index fcfee341b..0bc1016c4 100644 --- a/src/language-css/clean.js +++ b/src/language-css/clean.js @@ -8,8 +8,8 @@ function clean(ast, newObj, parent) { "source", "before", "after", - "trailingComma" - ].forEach(name => { + "trailingComma", + ].forEach((name) => { delete newObj[name]; }); diff --git a/src/language-css/embed.js b/src/language-css/embed.js index 67cc472fd..626d71f52 100644 --- a/src/language-css/embed.js +++ b/src/language-css/embed.js @@ -2,7 +2,7 @@ const { builders: { hardline, literalline, concat, markAsRoot }, - utils: { mapDoc } + utils: { mapDoc }, } = require("../document"); function embed(path, print, textToDoc /*, options */) { @@ -19,7 +19,7 @@ function embed(path, print, textToDoc /*, options */) { ) : "", "---", - hardline + hardline, ]) ); } @@ -27,7 +27,7 @@ function embed(path, print, textToDoc /*, options */) { return null; function replaceNewlinesWithLiterallines(doc) { - return mapDoc(doc, currentDoc => + return mapDoc(doc, (currentDoc) => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat( currentDoc diff --git a/src/language-css/index.js b/src/language-css/index.js index 786143fc2..3e91afc61 100644 --- a/src/language-css/index.js +++ b/src/language-css/index.js @@ -8,31 +8,31 @@ const languages = [ createLanguage(require("linguist-languages/data/CSS"), () => ({ since: "1.4.0", parsers: ["css"], - vscodeLanguageIds: ["css"] + vscodeLanguageIds: ["css"], })), createLanguage(require("linguist-languages/data/PostCSS"), () => ({ since: "1.4.0", parsers: ["css"], - vscodeLanguageIds: ["postcss"] + vscodeLanguageIds: ["postcss"], })), createLanguage(require("linguist-languages/data/Less"), () => ({ since: "1.4.0", parsers: ["less"], - vscodeLanguageIds: ["less"] + vscodeLanguageIds: ["less"], })), createLanguage(require("linguist-languages/data/SCSS"), () => ({ since: "1.4.0", parsers: ["scss"], - vscodeLanguageIds: ["scss"] - })) + vscodeLanguageIds: ["scss"], + })), ]; const printers = { - postcss: printer + postcss: printer, }; module.exports = { languages, options, - printers + printers, }; diff --git a/src/language-css/loc.js b/src/language-css/loc.js index b3bad38db..b5d95784a 100644 --- a/src/language-css/loc.js +++ b/src/language-css/loc.js @@ -157,10 +157,7 @@ function replaceQuotesInInlineComments(text) { for (const [start, end] of inlineCommentsToReplace) { text = text.slice(0, start) + - text - .slice(start, end) - .replace(/'/g, "\ufffe") - .replace(/"/g, "\uffff") + + text.slice(start, end).replace(/'/g, "\ufffe").replace(/"/g, "\uffff") + text.slice(end); } @@ -174,5 +171,5 @@ function restoreQuotesInInlineComments(text) { module.exports = { calculateLoc, replaceQuotesInInlineComments, - restoreQuotesInInlineComments + restoreQuotesInInlineComments, }; diff --git a/src/language-css/options.js b/src/language-css/options.js index 37c3649a2..b84b11071 100644 --- a/src/language-css/options.js +++ b/src/language-css/options.js @@ -4,5 +4,5 @@ const commonOptions = require("../common/common-options"); // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js module.exports = { - singleQuote: commonOptions.singleQuote + singleQuote: commonOptions.singleQuote, }; diff --git a/src/language-css/parser-postcss.js b/src/language-css/parser-postcss.js index dedbed4fa..ae679d691 100644 --- a/src/language-css/parser-postcss.js +++ b/src/language-css/parser-postcss.js @@ -11,13 +11,13 @@ function parseValueNodes(nodes) { open: null, close: null, groups: [], - type: "paren_group" + type: "paren_group", }; const parenGroupStack = [parenGroup]; const rootParenGroup = parenGroup; let commaGroup = { groups: [], - type: "comma_group" + type: "comma_group", }; const commaGroupStack = [commaGroup]; @@ -45,13 +45,13 @@ function parseValueNodes(nodes) { open: node, close: null, groups: [], - type: "paren_group" + type: "paren_group", }; parenGroupStack.push(parenGroup); commaGroup = { groups: [], - type: "comma_group" + type: "comma_group", }; commaGroupStack.push(commaGroup); } else if (node.type === "paren" && node.value === ")") { @@ -74,7 +74,7 @@ function parseValueNodes(nodes) { parenGroup.groups.push(commaGroup); commaGroup = { groups: [], - type: "comma_group" + type: "comma_group", }; commaGroupStack[commaGroupStack.length - 1] = commaGroup; } else { @@ -185,7 +185,7 @@ function parseValue(value) { } catch (e) { return { type: "value-unknown", - value + value, }; } @@ -202,7 +202,7 @@ function parseSelector(selector) { if (/\/\/|\/\*/.test(selector)) { return { type: "selector-unknown", - value: selector.trim() + value: selector.trim(), }; } @@ -211,7 +211,7 @@ function parseSelector(selector) { let result = null; try { - selectorParser(result_ => { + selectorParser((result_) => { result = result_; }).process(selector); } catch (e) { @@ -223,7 +223,7 @@ function parseSelector(selector) { // https://github.com/postcss/postcss-scss/issues/39 return { type: "selector-unknown", - value: selector + value: selector, }; } @@ -241,7 +241,7 @@ function parseMediaQuery(params) { // Ignore bad media queries return { type: "selector-unknown", - value: params + value: params, }; } @@ -368,7 +368,7 @@ function parseNestedCSS(node, options) { if (value.startsWith("progid:")) { return { type: "value-unknown", - value + value, }; } @@ -440,7 +440,7 @@ function parseNestedCSS(node, options) { if (name === "warn" || name === "error") { node.params = { type: "media-unknown", - value: params + value: params, }; return node; @@ -486,7 +486,7 @@ function parseNestedCSS(node, options) { "function", "return", "define-mixin", - "add-mixin" + "add-mixin", ].includes(name) ) { // Remove unnecessary spaces in SCSS variable arguments @@ -505,7 +505,7 @@ function parseNestedCSS(node, options) { // Workaround for media at rule with scss interpolation return { type: "media-unknown", - value: params + value: params, }; } @@ -559,7 +559,7 @@ function requireParser(isSCSSParser) { return { // Workaround for https://github.com/shellscape/postcss-less/issues/145 // See comments for `replaceQuotesInInlineComments` in `loc.js`. - parse: text => lessParser.parse(replaceQuotesInInlineComments(text)) + parse: (text) => lessParser.parse(replaceQuotesInInlineComments(text)), }; } @@ -598,7 +598,7 @@ const parser = { return node.source.endOffset; } return null; - } + }, }; // Export as a plugin so we can reuse the same bundle for UMD loading @@ -606,6 +606,6 @@ module.exports = { parsers: { css: parser, less: parser, - scss: parser - } + scss: parser, + }, }; diff --git a/src/language-css/pragma.js b/src/language-css/pragma.js index 21f4b2c22..384c9c35f 100644 --- a/src/language-css/pragma.js +++ b/src/language-css/pragma.js @@ -17,5 +17,5 @@ function insertPragma(text) { module.exports = { hasPragma, - insertPragma + insertPragma, }; diff --git a/src/language-css/printer-postcss.js b/src/language-css/printer-postcss.js index 78de43f1c..1ba86631f 100644 --- a/src/language-css/printer-postcss.js +++ b/src/language-css/printer-postcss.js @@ -7,7 +7,7 @@ const { printNumber, printString, hasIgnoreComment, - hasNewline + hasNewline, } = require("../common/util"); const { isNextLineEmpty } = require("../common/util-shared"); const { restoreQuotesInInlineComments } = require("./loc"); @@ -23,9 +23,9 @@ const { fill, indent, dedent, - ifBreak + ifBreak, }, - utils: { removeLines } + utils: { removeLines }, } = require("../document"); const { @@ -71,7 +71,7 @@ const { isColonNode, isMediaAndSupportsKeywords, isColorAdjusterFuncNode, - lastLineHasInlineComment + lastLineHasInlineComment, } = require("./utils"); function shouldPrintComma(options) { @@ -138,9 +138,9 @@ function genericPrint(path, options, print) { : "", hardline, "}", - isDetachedRulesetDeclarationNode(node) ? ";" : "" + isDetachedRulesetDeclarationNode(node) ? ";" : "", ]) - : ";" + : ";", ]); } case "css-decl": { @@ -176,13 +176,13 @@ function genericPrint(path, options, print) { concat([softline, printNodeSequence(path, options, print)]) ), softline, - "}" + "}", ]) : isTemplatePropNode(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" - : ";" + : ";", ]); } case "css-atrule": { @@ -197,7 +197,7 @@ function genericPrint(path, options, print) { return concat([ path.call(print, "selector"), node.important ? " !important" : "", - isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";" + isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";", ]); } @@ -205,7 +205,7 @@ function genericPrint(path, options, print) { return concat([ node.name, concat([path.call(print, "params")]), - isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";" + isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";", ]); } @@ -222,14 +222,14 @@ function genericPrint(path, options, print) { indent( concat([ node.nodes.length > 0 ? softline : "", - printNodeSequence(path, options, print) + printNodeSequence(path, options, print), ]) ), softline, - "}" + "}", ]) : "", - isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";" + isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";", ]); } } @@ -252,7 +252,7 @@ function genericPrint(path, options, print) { ? concat([hardline, hardline]) : hardline : " ", - path.call(print, "params") + path.call(print, "params"), ]) : "", node.selector @@ -267,7 +267,7 @@ function genericPrint(path, options, print) { ? hasParensAroundNode(node) ? " " : line - : "" + : "", ]) ) : node.name === "else" @@ -280,21 +280,21 @@ function genericPrint(path, options, print) { indent( concat([ node.nodes.length > 0 ? softline : "", - printNodeSequence(path, options, print) + printNodeSequence(path, options, print), ]) ), softline, - "}" + "}", ]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" - : ";" + : ";", ]); } // postcss-media-query-parser case "media-query-list": { const parts = []; - path.each(childPath => { + path.each((childPath) => { const node = childPath.getValue(); if (node.type === "media-query" && node.value === "") { return; @@ -307,7 +307,7 @@ function genericPrint(path, options, print) { case "media-query": { return concat([ join(" ", path.map(print, "nodes")), - isLastNode(path, node) ? "" : "," + isLastNode(path, node) ? "" : ",", ]); } case "media-type": { @@ -354,10 +354,10 @@ function genericPrint(path, options, print) { ",", insideAtRuleNode(path, ["extend", "custom-selector", "nest"]) ? line - : hardline + : hardline, ]), path.map(print, "nodes") - ) + ), ]) ); } @@ -385,7 +385,7 @@ function genericPrint(path, options, print) { isKeyframeAtRuleKeywords(path, node.value) ? node.value.toLowerCase() : node.value - ) + ), ]); } case "selector-id": { @@ -409,7 +409,7 @@ function genericPrint(path, options, print) { ) : "", node.insensitive ? " i" : "", - "]" + "]", ]); } case "selector-combinator": { @@ -440,7 +440,7 @@ function genericPrint(path, options, print) { node.namespace ? concat([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", - node.value + node.value, ]); } case "selector-pseudo": { @@ -448,7 +448,7 @@ function genericPrint(path, options, print) { maybeToLowerCase(node.value), node.nodes && node.nodes.length > 0 ? concat(["(", join(", ", path.map(print, "nodes")), ")"]) - : "" + : "", ]); } case "selector-nesting": { @@ -485,7 +485,7 @@ function genericPrint(path, options, print) { // see replaceQuotesInInlineComments in loc.js // value-* nodes don't have correct location data, so we have to rely on placeholder characters. restoreQuotesInInlineComments(node.value), - node.inline ? "" : "*/" + node.inline ? "" : "*/", ]); } case "value-comma_group": { @@ -775,7 +775,7 @@ function genericPrint(path, options, print) { return concat([ node.open ? path.call(print, "open") : "", join(",", path.map(print, "groups")), - node.close ? path.call(print, "close") : "" + node.close ? path.call(print, "close") : "", ]); } @@ -806,7 +806,7 @@ function genericPrint(path, options, print) { softline, join( concat([",", line]), - path.map(childPath => { + path.map((childPath) => { const node = childPath.getValue(); const printed = print(childPath); @@ -827,7 +827,7 @@ function genericPrint(path, options, print) { return printed; }, "groups") - ) + ), ]) ), ifBreak( @@ -839,10 +839,10 @@ function genericPrint(path, options, print) { : "" ), softline, - node.close ? path.call(print, "close") : "" + node.close ? path.call(print, "close") : "", ]), { - shouldBreak: isSCSSMapItem + shouldBreak: isSCSSMapItem, } ); } @@ -852,7 +852,7 @@ function genericPrint(path, options, print) { insideAtRuleNode(path, "supports") && isMediaAndSupportsKeywords(node) ? " " : "", - path.call(print, "group") + path.call(print, "group"), ]); } case "value-paren": { @@ -875,7 +875,7 @@ function genericPrint(path, options, print) { return concat([ node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`) - insideValueFunctionNode(path, "url") ? "" : line + insideValueFunctionNode(path, "url") ? "" : line, ]); } case "value-comma": { @@ -906,7 +906,7 @@ function printNodeSequence(path, options, print) { const node = path.getValue(); const parts = []; let i = 0; - path.map(pathChild => { + path.map((pathChild) => { const prevNode = node.nodes[i - 1]; if ( prevNode && @@ -974,7 +974,7 @@ const ADJUST_NUMBERS_REGEX = new RegExp( ); function adjustStrings(value, options) { - return value.replace(STRING_REGEX, match => printString(match, options)); + return value.replace(STRING_REGEX, (match) => printString(match, options)); } function quoteAttributeValue(value, options) { @@ -1007,5 +1007,5 @@ module.exports = { embed, insertPragma, hasPrettierIgnore: hasIgnoreComment, - massageAstNode: clean + massageAstNode: clean, }; diff --git a/src/language-css/utils.js b/src/language-css/utils.js index cb688d5a8..4f77d5f56 100644 --- a/src/language-css/utils.js +++ b/src/language-css/utils.js @@ -25,7 +25,7 @@ const colorAdjusterFunctions = [ "hsl", "hsla", "hwb", - "hwba" + "hwba", ]; function getAncestorCounter(path, typeOrTypes) { @@ -435,5 +435,5 @@ module.exports = { isColonNode, isMediaAndSupportsKeywords, isColorAdjusterFuncNode, - lastLineHasInlineComment + lastLineHasInlineComment, }; diff --git a/src/language-graphql/index.js b/src/language-graphql/index.js index c6033893f..be64a9e2c 100644 --- a/src/language-graphql/index.js +++ b/src/language-graphql/index.js @@ -8,16 +8,16 @@ const languages = [ createLanguage(require("linguist-languages/data/GraphQL"), () => ({ since: "1.5.0", parsers: ["graphql"], - vscodeLanguageIds: ["graphql"] - })) + vscodeLanguageIds: ["graphql"], + })), ]; const printers = { - graphql: printer + graphql: printer, }; module.exports = { languages, options, - printers + printers, }; diff --git a/src/language-graphql/options.js b/src/language-graphql/options.js index c50eb3743..c0ff84541 100644 --- a/src/language-graphql/options.js +++ b/src/language-graphql/options.js @@ -4,5 +4,5 @@ const commonOptions = require("../common/common-options"); // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js module.exports = { - bracketSpacing: commonOptions.bracketSpacing + bracketSpacing: commonOptions.bracketSpacing, }; diff --git a/src/language-graphql/parser-graphql.js b/src/language-graphql/parser-graphql.js index 86631aa9f..d92d39b9f 100644 --- a/src/language-graphql/parser-graphql.js +++ b/src/language-graphql/parser-graphql.js @@ -12,7 +12,7 @@ function parseComments(ast) { Object.assign(next, { // The Comment token's column starts _after_ the `#`, // but we need to make sure the node captures the `#` - column: next.column - 1 + column: next.column - 1, }); comments.push(next); } @@ -38,7 +38,7 @@ function removeTokens(node) { function fallbackParser(parse, source) { const parserOptions = { allowLegacySDLImplementsInterfaces: false, - experimentalFragmentVariables: true + experimentalFragmentVariables: true, }; try { return parse(source, parserOptions); @@ -62,8 +62,8 @@ function parse(text /*, parsers, opts*/) { throw createError(error.message, { start: { line: error.locations[0].line, - column: error.locations[0].column - } + column: error.locations[0].column, + }, }); } else { throw error; @@ -88,7 +88,7 @@ module.exports = { return node.end; } return node.loc && node.loc.end; - } - } - } + }, + }, + }, }; diff --git a/src/language-graphql/pragma.js b/src/language-graphql/pragma.js index d3b512b39..d41219dc7 100644 --- a/src/language-graphql/pragma.js +++ b/src/language-graphql/pragma.js @@ -10,5 +10,5 @@ function insertPragma(text) { module.exports = { hasPragma, - insertPragma + insertPragma, }; diff --git a/src/language-graphql/printer-graphql.js b/src/language-graphql/printer-graphql.js index 37c705ed0..6d9fcea11 100644 --- a/src/language-graphql/printer-graphql.js +++ b/src/language-graphql/printer-graphql.js @@ -8,7 +8,7 @@ const { softline, group, indent, - ifBreak + ifBreak, } = require("../document").builders; const { hasIgnoreComment } = require("../common/util"); const { isNextLineEmpty } = require("../common/util-shared"); @@ -60,17 +60,17 @@ function genericPrint(path, options, print) { join( concat([ifBreak("", ", "), softline]), path.map(print, "variableDefinitions") - ) + ), ]) ), softline, - ")" + ")", ]) ) : "", printDirectives(path, print, n), n.selectionSet ? (!hasOperation && !hasName ? "" : " ") : "", - path.call(print, "selectionSet") + path.call(print, "selectionSet"), ]); } case "FragmentDefinition": { @@ -87,11 +87,11 @@ function genericPrint(path, options, print) { join( concat([ifBreak("", ", "), softline]), path.map(print, "variableDefinitions") - ) + ), ]) ), softline, - ")" + ")", ]) ) : "", @@ -99,7 +99,7 @@ function genericPrint(path, options, print) { path.call(print, "typeCondition"), printDirectives(path, print, n), " ", - path.call(print, "selectionSet") + path.call(print, "selectionSet"), ]); } case "SelectionSet": { @@ -111,14 +111,15 @@ function genericPrint(path, options, print) { join( hardline, path.call( - selectionsPath => printSequence(selectionsPath, options, print), + (selectionsPath) => + printSequence(selectionsPath, options, print), "selections" ) - ) + ), ]) ), hardline, - "}" + "}", ]); } case "Field": { @@ -136,20 +137,20 @@ function genericPrint(path, options, print) { join( concat([ifBreak("", ", "), softline]), path.call( - argsPath => printSequence(argsPath, options, print), + (argsPath) => printSequence(argsPath, options, print), "arguments" ) - ) + ), ]) ), softline, - ")" + ")", ]) ) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", - path.call(print, "selectionSet") + path.call(print, "selectionSet"), ]) ); } @@ -163,13 +164,13 @@ function genericPrint(path, options, print) { hardline, join(hardline, n.value.replace(/"""/g, "\\$&").split("\n")), hardline, - '"""' + '"""', ]); } return concat([ '"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), - '"' + '"', ]); } case "IntValue": @@ -196,11 +197,11 @@ function genericPrint(path, options, print) { join( concat([ifBreak("", ", "), softline]), path.map(print, "values") - ) + ), ]) ), softline, - "]" + "]", ]) ); } @@ -215,12 +216,12 @@ function genericPrint(path, options, print) { join( concat([ifBreak("", ", "), softline]), path.map(print, "fields") - ) + ), ]) ), softline, ifBreak("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), - "}" + "}", ]) ); } @@ -229,7 +230,7 @@ function genericPrint(path, options, print) { return concat([ path.call(print, "name"), ": ", - path.call(print, "value") + path.call(print, "value"), ]); } @@ -247,17 +248,17 @@ function genericPrint(path, options, print) { join( concat([ifBreak("", ", "), softline]), path.call( - argsPath => printSequence(argsPath, options, print), + (argsPath) => printSequence(argsPath, options, print), "arguments" ) - ) + ), ]) ), softline, - ")" + ")", ]) ) - : "" + : "", ]); } @@ -271,7 +272,7 @@ function genericPrint(path, options, print) { ": ", path.call(print, "type"), n.defaultValue ? concat([" = ", path.call(print, "defaultValue")]) : "", - printDirectives(path, print, n) + printDirectives(path, print, n), ]); } @@ -290,7 +291,7 @@ function genericPrint(path, options, print) { n.interfaces.length > 0 ? concat([ " implements ", - concat(printInterfaces(path, options, print)) + concat(printInterfaces(path, options, print)), ]) : "", printDirectives(path, print, n), @@ -303,16 +304,16 @@ function genericPrint(path, options, print) { join( hardline, path.call( - fieldsPath => printSequence(fieldsPath, options, print), + (fieldsPath) => printSequence(fieldsPath, options, print), "fields" ) - ) + ), ]) ), hardline, - "}" + "}", ]) - : "" + : "", ]); } @@ -331,20 +332,20 @@ function genericPrint(path, options, print) { join( concat([ifBreak("", ", "), softline]), path.call( - argsPath => printSequence(argsPath, options, print), + (argsPath) => printSequence(argsPath, options, print), "arguments" ) - ) + ), ]) ), softline, - ")" + ")", ]) ) : "", ": ", path.call(print, "type"), - printDirectives(path, print, n) + printDirectives(path, print, n), ]); } @@ -365,19 +366,19 @@ function genericPrint(path, options, print) { join( concat([ifBreak("", ", "), softline]), path.call( - argsPath => printSequence(argsPath, options, print), + (argsPath) => printSequence(argsPath, options, print), "arguments" ) - ) + ), ]) ), softline, - ")" + ")", ]) ) : "", n.repeatable ? " repeatable" : "", - concat([" on ", join(" | ", path.map(print, "locations"))]) + concat([" on ", join(" | ", path.map(print, "locations"))]), ]); } @@ -400,16 +401,16 @@ function genericPrint(path, options, print) { join( hardline, path.call( - valuesPath => printSequence(valuesPath, options, print), + (valuesPath) => printSequence(valuesPath, options, print), "values" ) - ) + ), ]) ), hardline, - "}" + "}", ]) - : "" + : "", ]); } @@ -418,7 +419,7 @@ function genericPrint(path, options, print) { path.call(print, "description"), n.description ? hardline : "", path.call(print, "name"), - printDirectives(path, print, n) + printDirectives(path, print, n), ]); } @@ -430,7 +431,7 @@ function genericPrint(path, options, print) { ": ", path.call(print, "type"), n.defaultValue ? concat([" = ", path.call(print, "defaultValue")]) : "", - printDirectives(path, print, n) + printDirectives(path, print, n), ]); } @@ -452,16 +453,16 @@ function genericPrint(path, options, print) { join( hardline, path.call( - fieldsPath => printSequence(fieldsPath, options, print), + (fieldsPath) => printSequence(fieldsPath, options, print), "fields" ) - ) + ), ]) ), hardline, - "}" + "}", ]) - : "" + : "", ]); } @@ -477,15 +478,15 @@ function genericPrint(path, options, print) { join( hardline, path.call( - opsPath => printSequence(opsPath, options, print), + (opsPath) => printSequence(opsPath, options, print), "operationTypes" ) - ) + ), ]) ) : "", hardline, - "}" + "}", ]); } @@ -493,7 +494,7 @@ function genericPrint(path, options, print) { return concat([ path.call(print, "operation"), ": ", - path.call(print, "type") + path.call(print, "type"), ]); } @@ -516,16 +517,16 @@ function genericPrint(path, options, print) { join( hardline, path.call( - fieldsPath => printSequence(fieldsPath, options, print), + (fieldsPath) => printSequence(fieldsPath, options, print), "fields" ) - ) + ), ]) ), hardline, - "}" + "}", ]) - : "" + : "", ]); } @@ -533,7 +534,7 @@ function genericPrint(path, options, print) { return concat([ "...", path.call(print, "name"), - printDirectives(path, print, n) + printDirectives(path, print, n), ]); } @@ -545,7 +546,7 @@ function genericPrint(path, options, print) { : "", printDirectives(path, print, n), " ", - path.call(print, "selectionSet") + path.call(print, "selectionSet"), ]); } @@ -568,13 +569,13 @@ function genericPrint(path, options, print) { indent( concat([ ifBreak(concat([line, " "])), - join(concat([line, "| "]), path.map(print, "types")) + join(concat([line, "| "]), path.map(print, "types")), ]) - ) + ), ]) - : "" + : "", ]) - ) + ), ]) ); } @@ -587,7 +588,7 @@ function genericPrint(path, options, print) { n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), - printDirectives(path, print, n) + printDirectives(path, print, n), ]); } @@ -619,10 +620,10 @@ function printDirectives(path, print, n) { join( concat([ifBreak("", " "), softline]), path.map(print, "directives") - ) + ), ]) ) - ) + ), ]); } @@ -668,7 +669,7 @@ function printInterfaces(path, options, print) { const node = path.getNode(); const parts = []; const { interfaces } = node; - const printed = path.map(node => print(node), "interfaces"); + const printed = path.map((node) => print(node), "interfaces"); for (let index = 0; index < interfaces.length; index++) { const interfaceNode = interfaces[index]; @@ -698,5 +699,5 @@ module.exports = { hasPrettierIgnore: hasIgnoreComment, insertPragma, printComment, - canAttachComment + canAttachComment, }; diff --git a/src/language-handlebars/clean.js b/src/language-handlebars/clean.js index d05797d59..9abcac2d2 100644 --- a/src/language-handlebars/clean.js +++ b/src/language-handlebars/clean.js @@ -1,6 +1,6 @@ "use strict"; -module.exports = function(ast, newNode) { +module.exports = function (ast, newNode) { delete newNode.loc; delete newNode.selfClosing; diff --git a/src/language-handlebars/index.js b/src/language-handlebars/index.js index 12b8ab9d0..966ae6ba3 100644 --- a/src/language-handlebars/index.js +++ b/src/language-handlebars/index.js @@ -7,15 +7,15 @@ const languages = [ createLanguage(require("linguist-languages/data/Handlebars"), () => ({ since: null, // unreleased parsers: ["glimmer"], - vscodeLanguageIds: ["handlebars"] - })) + vscodeLanguageIds: ["handlebars"], + })), ]; const printers = { - glimmer: printer + glimmer: printer, }; module.exports = { languages, - printers + printers, }; diff --git a/src/language-handlebars/parser-glimmer.js b/src/language-handlebars/parser-glimmer.js index 5da9c0c36..ae282d9e0 100644 --- a/src/language-handlebars/parser-glimmer.js +++ b/src/language-handlebars/parser-glimmer.js @@ -11,7 +11,7 @@ function parse(text) { const matches = error.message.match(/on line (\d+)/); if (matches) { throw createError(error.message, { - start: { line: Number(matches[1]), column: 0 } + start: { line: Number(matches[1]), column: 0 }, }); } else { throw error; @@ -33,7 +33,7 @@ module.exports = { }, locEnd(node) { return node.loc && node.loc.end; - } - } - } + }, + }, + }, }; diff --git a/src/language-handlebars/printer-glimmer.js b/src/language-handlebars/printer-glimmer.js index 66fae4d57..ef52147ba 100644 --- a/src/language-handlebars/printer-glimmer.js +++ b/src/language-handlebars/printer-glimmer.js @@ -10,7 +10,7 @@ const { line, group, indent, - ifBreak + ifBreak, } = require("../document").builders; const { @@ -21,7 +21,7 @@ const { isNextNodeOfSomeType, isParentOfSomeType, isPreviousNodeOfSomeType, - isWhitespaceNode + isWhitespaceNode, } = require("./utils"); // http://w3c.github.io/html/single-page.html#void-elements @@ -39,7 +39,7 @@ const voidTags = [ "param", "source", "track", - "wbr" + "wbr", ]; // Formatter based on @glimmerjs/syntax's built-in test formatter: @@ -79,7 +79,7 @@ function print(path, options, print) { const hasChildren = n.children.length > 0; const hasNonWhitespaceChildren = n.children.some( - n => !isWhitespaceNode(n) + (n) => !isWhitespaceNode(n) ); const isVoid = @@ -98,7 +98,7 @@ function print(path, options, print) { join(line, path.map(print, "modifiers")), n.comments.length ? line : "", - join(line, path.map(print, "comments")) + join(line, path.map(print, "comments")), ]) ); @@ -112,7 +112,7 @@ function print(path, options, print) { printParams(path, print), n.blockParams.length ? ` as |${n.blockParams.join(" ")}|` : "", ifBreak(softline, ""), - ifBreak(closeTagForBreak, closeTagForNoBreak) + ifBreak(closeTagForBreak, closeTagForNoBreak), ]) ), !isVoid @@ -122,11 +122,11 @@ function print(path, options, print) { ? indent(printChildren(path, options, print)) : "", ifBreak(hasChildren ? hardline : "", ""), - concat([""]) + concat([""]), ]) ) : "", - nextNode && nextNode.type === "ElementNode" ? hardline : "" + nextNode && nextNode.type === "ElementNode" ? hardline : "", ]); } case "BlockStatement": { @@ -142,7 +142,7 @@ function print(path, options, print) { n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if"; - const indentElse = hasElseIf ? a => a : indent; + const indentElse = hasElseIf ? (a) => a : indent; const inverseElseStatement = (n.inverseStrip.open ? "{{~" : "{{") + "else" + @@ -153,7 +153,7 @@ function print(path, options, print) { ? concat([ n.openStrip.open ? "{{~else " : "{{else ", printPathParams(path, print), - n.openStrip.close ? "~}}" : "}}" + n.openStrip.close ? "~}}" : "}}", ]) : printOpenBlock(path, print, n.openStrip), indent(concat([hardline, path.call(print, "program")])), @@ -165,21 +165,21 @@ function print(path, options, print) { : "", isElseIf ? "" - : concat([hardline, printCloseBlock(path, print, n.closeStrip)]) + : concat([hardline, printCloseBlock(path, print, n.closeStrip)]), ]); } else if (isElseIf) { return concat([ concat([ n.openStrip.open ? "{{~else" : "{{else ", printPathParams(path, print), - n.openStrip.close ? "~}}" : "}}" + n.openStrip.close ? "~}}" : "}}", ]), - indent(concat([hardline, path.call(print, "program")])) + indent(concat([hardline, path.call(print, "program")])), ]); } const hasNonWhitespaceChildren = n.program.body.some( - n => !isWhitespaceNode(n) + (n) => !isWhitespaceNode(n) ); return concat([ @@ -188,9 +188,9 @@ function print(path, options, print) { concat([ indent(concat([softline, path.call(print, "program")])), hasNonWhitespaceChildren ? hardline : softline, - printCloseBlock(path, print, n.closeStrip) + printCloseBlock(path, print, n.closeStrip), ]) - ) + ), ]); } case "ElementModifierStatement": { @@ -207,7 +207,7 @@ function print(path, options, print) { const leading = isParentOfSomeType(path, [ "AttrNode", "ConcatStatement", - "ElementNode" + "ElementNode", ]) ? [opening, indent(softline)] : [opening]; @@ -249,9 +249,11 @@ function print(path, options, print) { return concat([ '"', concat( - path.map(partPath => print(partPath), "parts").filter(a => a !== "") + path + .map((partPath) => print(partPath), "parts") + .filter((a) => a !== "") ), - '"' + '"', ]); } case "Hash": { @@ -359,7 +361,10 @@ function print(path, options, print) { n.chars .replace(/^[\s ]+/g, leadingSpace) .replace(/[\s ]+$/, trailingSpace), - ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve) + ...generateHardlines( + trailingLineBreaksCount, + maxLineBreaksToPreserve + ), ].filter(Boolean) ); } @@ -457,7 +462,7 @@ function printStringLiteral(stringLiteral, options) { return concat([ enclosingQuote.quote, escapedStringLiteral, - enclosingQuote.quote + enclosingQuote.quote, ]); } @@ -507,7 +512,7 @@ function printOpenBlock( printPathParams(path, print), printBlockParams(path), softline, - isCloseStrip ? "~}}" : "}}" + isCloseStrip ? "~}}" : "}}", ]) ); } @@ -520,7 +525,7 @@ function printCloseBlock( return concat([ isOpenStrip ? "{{~/" : "{{/", path.call(print, "path"), - isCloseStrip ? "~}}" : "}}" + isCloseStrip ? "~}}" : "}}", ]); } @@ -581,5 +586,5 @@ function locationToOffset(source, line, column) { module.exports = { print, - massageAstNode: clean + massageAstNode: clean, }; diff --git a/src/language-handlebars/utils.js b/src/language-handlebars/utils.js index f75853bc7..9cd6dfd08 100644 --- a/src/language-handlebars/utils.js +++ b/src/language-handlebars/utils.js @@ -17,7 +17,7 @@ function isWhitespaceNode(node) { } function isNodeOfSomeType(node, types) { - return node && types.some(type => node.type === type); + return node && types.some((type) => node.type === type); } function isParentOfSomeType(path, types) { @@ -76,5 +76,5 @@ module.exports = { isNodeOfSomeType, isParentOfSomeType, isPreviousNodeOfSomeType, - isWhitespaceNode + isWhitespaceNode, }; diff --git a/src/language-html/ast.js b/src/language-html/ast.js index b5668520d..85279d5c2 100644 --- a/src/language-html/ast.js +++ b/src/language-html/ast.js @@ -2,7 +2,7 @@ const NODES_KEYS = { attrs: true, - children: true + children: true, }; class Node { @@ -25,7 +25,7 @@ class Node { attrMap: this[key].reduce((reduced, attr) => { reduced[attr.fullName] = attr.value; return reduced; - }, Object.create(null)) + }, Object.create(null)), }); } } @@ -37,7 +37,7 @@ class Node { for (const NODES_KEY in NODES_KEYS) { const nodes = this[NODES_KEY]; if (nodes) { - const mappedNodes = mapNodesIfChanged(nodes, node => node.map(fn)); + const mappedNodes = mapNodesIfChanged(nodes, (node) => node.map(fn)); if (newNode !== nodes) { if (!newNode) { newNode = new Node(); @@ -59,7 +59,7 @@ class Node { siblings, prev, next, - parent + parent, }); } @@ -99,7 +99,7 @@ function mapNodesIfChanged(nodes, fn) { } function cloneAndUpdateNodes(nodes, parent) { - const siblings = nodes.map(node => + const siblings = nodes.map((node) => node instanceof Node ? node.clone() : new Node(node) ); @@ -113,7 +113,7 @@ function cloneAndUpdateNodes(nodes, parent) { siblings, prev, next, - parent + parent, }); prev = current; current = next; @@ -132,5 +132,5 @@ function setNonEnumerableProperties(obj, props) { } module.exports = { - Node + Node, }; diff --git a/src/language-html/clean.js b/src/language-html/clean.js index c14bb094b..100bd9777 100644 --- a/src/language-html/clean.js +++ b/src/language-html/clean.js @@ -1,6 +1,6 @@ "use strict"; -module.exports = function(ast, newNode) { +module.exports = function (ast, newNode) { delete newNode.sourceSpan; delete newNode.startSourceSpan; delete newNode.endSourceSpan; diff --git a/src/language-html/conditional-comment.js b/src/language-html/conditional-comment.js index 3071d310d..55199c87b 100644 --- a/src/language-html/conditional-comment.js +++ b/src/language-html/conditional-comment.js @@ -12,7 +12,7 @@ const IE_CONDITIONAL_END_COMMENT_REGEX = /^ +const getCssStyleTags = (property) => fromPairs( flat( htmlStyles - .filter(htmlStyle => htmlStyle.style[property]) - .map(htmlStyle => + .filter((htmlStyle) => htmlStyle.style[property]) + .map((htmlStyle) => htmlStyle.selectorText .split(",") - .map(selector => selector.trim()) - .filter(selector => /^[a-zA-Z0-9]+$/.test(selector)) - .map(tagName => [tagName, htmlStyle.style[property]]) + .map((selector) => selector.trim()) + .filter((selector) => /^[a-zA-Z0-9]+$/.test(selector)) + .map((tagName) => [tagName, htmlStyle.style[property]]) ) ) ); @@ -34,7 +34,7 @@ const CSS_DISPLAY_TAGS = { // there's no css display for these elements but they behave these ways video: "inline-block", - audio: "inline-block" + audio: "inline-block", }; const CSS_DISPLAY_DEFAULT = "inline"; const CSS_WHITE_SPACE_TAGS = getCssStyleTags("white-space"); @@ -44,5 +44,5 @@ module.exports = { CSS_DISPLAY_TAGS, CSS_DISPLAY_DEFAULT, CSS_WHITE_SPACE_TAGS, - CSS_WHITE_SPACE_DEFAULT + CSS_WHITE_SPACE_DEFAULT, }; diff --git a/src/language-html/index.js b/src/language-html/index.js index bda067b24..3fcfb3ea2 100644 --- a/src/language-html/index.js +++ b/src/language-html/index.js @@ -11,15 +11,15 @@ const languages = [ parsers: ["angular"], vscodeLanguageIds: ["html"], extensions: [".component.html"], - filenames: [] + filenames: [], })), - createLanguage(require("linguist-languages/data/HTML"), data => ({ + createLanguage(require("linguist-languages/data/HTML"), (data) => ({ since: "1.15.0", parsers: ["html"], vscodeLanguageIds: ["html"], extensions: data.extensions.concat([ - ".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML - ]) + ".mjml", // MJML is considered XML in Linguist but it should be formatted as HTML + ]), })), createLanguage(require("linguist-languages/data/HTML"), () => ({ name: "Lightning Web Components", @@ -27,21 +27,21 @@ const languages = [ parsers: ["lwc"], vscodeLanguageIds: ["html"], extensions: [], - filenames: [] + filenames: [], })), createLanguage(require("linguist-languages/data/Vue"), () => ({ since: "1.10.0", parsers: ["vue"], - vscodeLanguageIds: ["vue"] - })) + vscodeLanguageIds: ["vue"], + })), ]; const printers = { - html: printer + html: printer, }; module.exports = { languages, printers, - options + options, }; diff --git a/src/language-html/options.js b/src/language-html/options.js index 62362c6b4..f0e290a4a 100644 --- a/src/language-html/options.js +++ b/src/language-html/options.js @@ -13,23 +13,23 @@ module.exports = { choices: [ { value: "css", - description: "Respect the default value of CSS display property." + description: "Respect the default value of CSS display property.", }, { value: "strict", - description: "Whitespaces are considered sensitive." + description: "Whitespaces are considered sensitive.", }, { value: "ignore", - description: "Whitespaces are considered insensitive." - } - ] + description: "Whitespaces are considered insensitive.", + }, + ], }, vueIndentScriptAndStyle: { since: "1.19.0", category: CATEGORY_HTML, type: "boolean", default: false, - description: "Indent script and style tags in Vue files." - } + description: "Indent script and style tags in Vue files.", + }, }; diff --git a/src/language-html/parser-html.js b/src/language-html/parser-html.js index 9320f1e19..ad9207cf3 100644 --- a/src/language-html/parser-html.js +++ b/src/language-html/parser-html.js @@ -4,7 +4,7 @@ const parseFrontMatter = require("../utils/front-matter"); const { HTML_ELEMENT_ATTRIBUTES, HTML_TAGS, - isUnknownNamespace + isUnknownNamespace, } = require("./utils"); const { hasPragma } = require("./pragma"); const createError = require("../common/parser-create-error"); @@ -18,7 +18,7 @@ function ngHtmlParser( normalizeTagName, normalizeAttributeName, allowHtmComponentClosingTags, - isTagNameCaseSensitive + isTagNameCaseSensitive, } ) { const parser = require("angular-html-parser"); @@ -30,19 +30,19 @@ function ngHtmlParser( Comment, DocType, Element, - Text + Text, } = require("angular-html-parser/lib/compiler/src/ml_parser/ast"); const { - ParseSourceSpan + ParseSourceSpan, } = require("angular-html-parser/lib/compiler/src/parse_util"); const { - getHtmlTagDefinition + getHtmlTagDefinition, } = require("angular-html-parser/lib/compiler/src/ml_parser/html_tags"); const { rootNodes, errors } = parser.parse(input, { canSelfClose: recognizeSelfClosing, allowHtmComponentClosingTags, - isTagNameCaseSensitive + isTagNameCaseSensitive, }); if (errors.length !== 0) { @@ -51,7 +51,7 @@ function ngHtmlParser( throw createError(msg, { start: { line: line + 1, column: col + 1 } }); } - const addType = node => { + const addType = (node) => { if (node instanceof Attribute) { node.type = "attribute"; } else if (node instanceof CDATA) { @@ -69,7 +69,7 @@ function ngHtmlParser( } }; - const restoreName = node => { + const restoreName = (node) => { const namespace = node.name.startsWith(":") ? node.name.slice(1).split(":")[0] : null; @@ -84,10 +84,10 @@ function ngHtmlParser( node.hasExplicitNamespace = hasExplicitNamespace; }; - const restoreNameAndValue = node => { + const restoreNameAndValue = (node) => { if (node instanceof Element) { restoreName(node); - node.attrs.forEach(attr => { + node.attrs.forEach((attr) => { restoreName(attr); if (!attr.valueSpan) { attr.value = null; @@ -111,7 +111,7 @@ function ngHtmlParser( const lowerCasedText = text.toLowerCase(); return fn(lowerCasedText) ? lowerCasedText : text; }; - const normalizeName = node => { + const normalizeName = (node) => { if (node instanceof Element) { if ( normalizeTagName && @@ -121,18 +121,18 @@ function ngHtmlParser( ) { node.name = lowerCaseIfFn( node.name, - lowerCasedName => lowerCasedName in HTML_TAGS + (lowerCasedName) => lowerCasedName in HTML_TAGS ); } if (normalizeAttributeName) { const CURRENT_HTML_ELEMENT_ATTRIBUTES = HTML_ELEMENT_ATTRIBUTES[node.name] || Object.create(null); - node.attrs.forEach(attr => { + node.attrs.forEach((attr) => { if (!attr.namespace) { attr.name = lowerCaseIfFn( attr.name, - lowerCasedAttrName => + (lowerCasedAttrName) => node.name in HTML_ELEMENT_ATTRIBUTES && (lowerCasedAttrName in HTML_ELEMENT_ATTRIBUTES["*"] || lowerCasedAttrName in CURRENT_HTML_ELEMENT_ATTRIBUTES) @@ -143,7 +143,7 @@ function ngHtmlParser( } }; - const fixSourceSpan = node => { + const fixSourceSpan = (node) => { if (node.sourceSpan && node.endSourceSpan) { node.sourceSpan = new ParseSourceSpan( node.sourceSpan.start, @@ -152,7 +152,7 @@ function ngHtmlParser( } }; - const addTagDefinition = node => { + const addTagDefinition = (node) => { if (node instanceof Element) { const tagDefinition = getHtmlTagDefinition( isTagNameCaseSensitive ? node.name : node.name.toLowerCase() @@ -193,7 +193,7 @@ function _parse(text, options, parserOptions, shouldParseFrontMatter = true) { const rawAst = { type: "root", sourceSpan: { start: { offset: 0 }, end: { offset: text.length } }, - children: ngHtmlParser(content, parserOptions) + children: ngHtmlParser(content, parserOptions), }; if (frontMatter) { @@ -230,7 +230,7 @@ function _parse(text, options, parserOptions, shouldParseFrontMatter = true) { return subAst; }; - return ast.map(node => { + return ast.map((node) => { if (node.type === "comment") { const ieConditionalComment = parseIeConditionalComment( node, @@ -258,7 +258,7 @@ function createParser({ normalizeTagName = false, normalizeAttributeName = false, allowHtmComponentClosingTags = false, - isTagNameCaseSensitive = false + isTagNameCaseSensitive = false, } = {}) { return { parse: (text, parsers, options) => @@ -267,12 +267,12 @@ function createParser({ normalizeTagName, normalizeAttributeName, allowHtmComponentClosingTags, - isTagNameCaseSensitive + isTagNameCaseSensitive, }), hasPragma, astFormat: "html", locStart, - locEnd + locEnd, }; } @@ -282,13 +282,13 @@ module.exports = { recognizeSelfClosing: true, normalizeTagName: true, normalizeAttributeName: true, - allowHtmComponentClosingTags: true + allowHtmComponentClosingTags: true, }), angular: createParser(), vue: createParser({ recognizeSelfClosing: true, - isTagNameCaseSensitive: true + isTagNameCaseSensitive: true, }), - lwc: createParser() - } + lwc: createParser(), + }, }; diff --git a/src/language-html/pragma.js b/src/language-html/pragma.js index 650328d4f..7ab5f441b 100644 --- a/src/language-html/pragma.js +++ b/src/language-html/pragma.js @@ -10,5 +10,5 @@ function insertPragma(text) { module.exports = { hasPragma, - insertPragma + insertPragma, }; diff --git a/src/language-html/preprocess.js b/src/language-html/preprocess.js index ce05bd1a1..537ebd751 100644 --- a/src/language-html/preprocess.js +++ b/src/language-html/preprocess.js @@ -7,7 +7,7 @@ const { isIndentationSensitiveNode, isLeadingSpaceSensitiveNode, isTrailingSpaceSensitiveNode, - isWhitespaceSensitiveNode + isWhitespaceSensitiveNode, } = require("./utils"); const PREPROCESS_PIPELINE = [ @@ -20,7 +20,7 @@ const PREPROCESS_PIPELINE = [ addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, - mergeSimpleElementIntoText + mergeSimpleElementIntoText, ]; function preprocess(ast, options) { @@ -31,7 +31,7 @@ function preprocess(ast, options) { } function removeIgnorableFirstLf(ast /*, options */) { - return ast.map(node => { + return ast.map((node) => { if ( node.type === "element" && node.tagDefinition.ignoreFirstLf && @@ -44,7 +44,7 @@ function removeIgnorableFirstLf(ast /*, options */) { children: text.value.length === 1 ? rest - : [text.clone({ value: text.value.slice(1) }), ...rest] + : [text.clone({ value: text.value.slice(1) }), ...rest], }); } return node; @@ -57,7 +57,7 @@ function mergeIeConditonalStartEndCommentIntoElementOpeningTag( /** * */ - const isTarget = node => + const isTarget = (node) => node.type === "element" && node.prev && node.prev.type === "ieConditionalStartComment" && @@ -65,7 +65,7 @@ function mergeIeConditonalStartEndCommentIntoElementOpeningTag( node.firstChild && node.firstChild.type === "ieConditionalEndComment" && node.firstChild.sourceSpan.start.offset === node.startSourceSpan.end.offset; - return ast.map(node => { + return ast.map((node) => { if (node.children) { const isTargetResults = node.children.map(isTarget); if (isTargetResults.some(Boolean)) { @@ -98,7 +98,7 @@ function mergeIeConditonalStartEndCommentIntoElementOpeningTag( condition: ieConditionalStartComment.condition, sourceSpan, startSourceSpan, - children: child.children.slice(1) + children: child.children.slice(1), }) ); @@ -116,7 +116,7 @@ function mergeIeConditonalStartEndCommentIntoElementOpeningTag( } function mergeNodeIntoText(ast, shouldMerge, getValue) { - return ast.map(node => { + return ast.map((node) => { if (node.children) { const shouldMergeResults = node.children.map(shouldMerge); if (shouldMergeResults.some(Boolean)) { @@ -150,7 +150,7 @@ function mergeNodeIntoText(ast, shouldMerge, getValue) { sourceSpan: new ParseSourceSpan( lastChild.sourceSpan.start, newChild.sourceSpan.end - ) + ), }) ); } @@ -165,13 +165,13 @@ function mergeNodeIntoText(ast, shouldMerge, getValue) { function mergeCdataIntoText(ast /*, options */) { return mergeNodeIntoText( ast, - node => node.type === "cdata", - node => `` + (node) => node.type === "cdata", + (node) => `` ); } function mergeSimpleElementIntoText(ast /*, options */) { - const isSimpleElement = node => + const isSimpleElement = (node) => node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && @@ -188,7 +188,7 @@ function mergeSimpleElementIntoText(ast /*, options */) { node.prev.type === "text" && node.next && node.next.type === "text"; - return ast.map(node => { + return ast.map((node) => { if (node.children) { const isSimpleElementResults = node.children.map(isSimpleElement); if (isSimpleElementResults.some(Boolean)) { @@ -213,7 +213,7 @@ function mergeSimpleElementIntoText(ast /*, options */) { nextChild.sourceSpan.end ), isTrailingSpaceSensitive, - hasTrailingSpaces + hasTrailingSpaces, }) ); } else { @@ -233,7 +233,7 @@ function extractInterpolation(ast, options) { } const interpolationRegex = /\{\{([\s\S]+?)\}\}/g; - return ast.map(node => { + return ast.map((node) => { if (!canHaveInterpolation(node)) { return node; } @@ -264,7 +264,7 @@ function extractInterpolation(ast, options) { newChildren.push({ type: "text", value, - sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan) + sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan), }); } continue; @@ -284,9 +284,9 @@ function extractInterpolation(ast, options) { sourceSpan: new ParseSourceSpan( startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2) - ) - } - ] + ), + }, + ], }); } } @@ -304,7 +304,7 @@ function extractInterpolation(ast, options) { */ function extractWhitespaces(ast /*, options*/) { const TYPE_WHITESPACE = "whitespace"; - return ast.map(node => { + return ast.map((node) => { if (!node.children) { return node; } @@ -317,7 +317,7 @@ function extractWhitespaces(ast /*, options*/) { ) { return node.clone({ children: [], - hasDanglingSpaces: node.children.length !== 0 + hasDanglingSpaces: node.children.length !== 0, }); } @@ -353,7 +353,7 @@ function extractWhitespaces(ast /*, options*/) { sourceSpan: new ParseSourceSpan( child.sourceSpan.start.moveBy(leadingSpaces.length), child.sourceSpan.end.moveBy(-trailingSpaces.length) - ) + ), }); } @@ -378,28 +378,28 @@ function extractWhitespaces(ast /*, options*/) { return newChildren.concat({ ...child, hasLeadingSpaces, - hasTrailingSpaces + hasTrailingSpaces, }); - }, []) + }, []), }); }); } function addIsSelfClosing(ast /*, options */) { - return ast.map(node => + return ast.map((node) => Object.assign(node, { isSelfClosing: !node.children || (node.type === "element" && (node.tagDefinition.isVoid || // self-closing - node.startSourceSpan === node.endSourceSpan)) + node.startSourceSpan === node.endSourceSpan)), }) ); } function addHasHtmComponentClosingTag(ast, options) { - return ast.map(node => + return ast.map((node) => node.type !== "element" ? node : Object.assign(node, { @@ -410,13 +410,13 @@ function addHasHtmComponentClosingTag(ast, options) { node.endSourceSpan.start.offset, node.endSourceSpan.end.offset ) - ) + ), }) ); } function addCssDisplay(ast, options) { - return ast.map(node => + return ast.map((node) => Object.assign(node, { cssDisplay: getNodeCssStyleDisplay(node, options) }) ); } @@ -427,24 +427,24 @@ function addCssDisplay(ast, options) { * - add `isDanglingSpaceSensitive` field for parent nodes */ function addIsSpaceSensitive(ast /*, options */) { - return ast.map(node => { + return ast.map((node) => { if (!node.children) { return node; } if (node.children.length === 0) { return node.clone({ - isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode(node) + isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode(node), }); } return node.clone({ children: node.children - .map(child => { + .map((child) => { return { ...child, isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode(child), - isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode(child) + isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode(child), }; }) .map((child, index, children) => ({ @@ -458,8 +458,8 @@ function addIsSpaceSensitive(ast /*, options */) { index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && - child.isTrailingSpaceSensitive - })) + child.isTrailingSpaceSensitive, + })), }); }); } diff --git a/src/language-html/printer-html.js b/src/language-html/printer-html.js index 777f515f0..5451c1be5 100644 --- a/src/language-html/printer-html.js +++ b/src/language-html/printer-html.js @@ -3,7 +3,7 @@ const clean = require("./clean"); const { builders, - utils: { stripTrailingHardline, mapDoc } + utils: { stripTrailingHardline, mapDoc }, } = require("../document"); const { breakParent, @@ -17,7 +17,7 @@ const { line, literalline, markAsRoot, - softline + softline, } = builders; const { countChars, @@ -36,7 +36,7 @@ const { preferHardlineAsLeadingSpaces, shouldNotPrintClosingTag, shouldPreserveContent, - unescapeQuoteEntities + unescapeQuoteEntities, } = require("./utils"); const { replaceEndOfLineWith } = require("../common/util"); const preprocess = require("./preprocess"); @@ -45,7 +45,7 @@ const { insertPragma } = require("./pragma"); const { printVueFor, printVueSlotScope, - isVueEventBindingExpression + isVueEventBindingExpression, } = require("./syntax-vue"); const { printImgSrcset, printClassNames } = require("./syntax-attribute"); @@ -74,8 +74,8 @@ function embed(path, print, textToDoc, options) { breakParent, printOpeningTagPrefix(node, options), stripTrailingHardline(textToDoc(value, { parser })), - printClosingTagSuffix(node, options) - ]) + printClosingTagSuffix(node, options), + ]), ]); } } else if (node.parent.type === "interpolation") { @@ -89,14 +89,14 @@ function embed(path, print, textToDoc, options) { ? { parser: "__ng_interpolation", trailingComma: "none" } : options.parser === "vue" ? { parser: "__vue_expression" } - : { parser: "__js_expression" }) - }) + : { parser: "__js_expression" }), + }), ]) ), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " - : line + : line, ]); } break; @@ -145,11 +145,11 @@ function embed(path, print, textToDoc, options) { node.rawName, '="', group( - mapDoc(embeddedAttributeValueDoc, doc => + mapDoc(embeddedAttributeValueDoc, (doc) => typeof doc === "string" ? doc.replace(/"/g, """) : doc ) ), - '"' + '"', ]); } break; @@ -162,7 +162,7 @@ function embed(path, print, textToDoc, options) { node.value.trim().length === 0 ? "" : textToDoc(node.value, { parser: "yaml" }), - "---" + "---", ]) ); } @@ -178,7 +178,7 @@ function genericPrint(path, options, print) { // use original concat to not break stripTrailingHardline return builders.concat([ group(printChildren(path, options, print)), - hardline + hardline, ]); case "element": case "ieConditionalComment": { @@ -220,10 +220,10 @@ function genericPrint(path, options, print) { : "" : concat([ forceBreakContent(node) ? breakParent : "", - (childrenDoc => + ((childrenDoc) => shouldHugContent ? ifBreak(indent(childrenDoc), childrenDoc, { - groupId: attrGroupId + groupId: attrGroupId, }) : isScriptLikeTag(node) && node.parent.type === "root" && @@ -242,12 +242,14 @@ function genericPrint(path, options, print) { node.isIndentationSensitive ? dedentToRoot(softline) : softline, - printChildren(path, options, print) + printChildren(path, options, print), ]) ), - (node.next - ? needsToBorrowPrevClosingTagEndMarker(node.next) - : needsToBorrowLastChildClosingTagEndMarker(node.parent)) + ( + node.next + ? needsToBorrowPrevClosingTagEndMarker(node.next) + : needsToBorrowLastChildClosingTagEndMarker(node.parent) + ) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " @@ -262,11 +264,13 @@ function genericPrint(path, options, print) { node.isWhitespaceSensitive && node.isIndentationSensitive)) && new RegExp( - `\\n\\s{${options.tabWidth * + `\\n\\s{${ + options.tabWidth * countParents( path, - n => n.parent && n.parent.type !== "root" - )}}$` + (n) => n.parent && n.parent.type !== "root" + ) + }}$` ).test(node.lastChild.value) ? /** *
@@ -277,11 +281,11 @@ function genericPrint(path, options, print) { *
*/ "" - : softline - ]) + : softline, + ]), ]) ), - printClosingTag(node, options) + printClosingTag(node, options), ]); } case "ieConditionalStartComment": @@ -291,7 +295,7 @@ function genericPrint(path, options, print) { return concat([ printOpeningTagStart(node, options), concat(path.map(print, "children")), - printClosingTagEnd(node, options) + printClosingTagEnd(node, options), ]); case "text": { if (node.parent.type === "interpolation") { @@ -303,7 +307,7 @@ function genericPrint(path, options, print) { : node.value; return concat([ concat(replaceEndOfLineWith(value, literalline)), - hasTrailingNewline ? hardline : "" + hasTrailingNewline ? hardline : "", ]); } return fill( @@ -322,10 +326,10 @@ function genericPrint(path, options, print) { concat([ printOpeningTagStart(node, options), " ", - node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ") + node.value.replace(/^html\b/i, "html").replace(/\s+/g, " "), ]) ), - printClosingTagEnd(node, options) + printClosingTagEnd(node, options), ]); case "comment": { return concat([ @@ -339,7 +343,7 @@ function genericPrint(path, options, print) { literalline ) ), - printClosingTagSuffix(node, options) + printClosingTagSuffix(node, options), ]); } case "attribute": { @@ -363,8 +367,8 @@ function genericPrint(path, options, print) { literalline ) ), - quote - ]) + quote, + ]), ]); } case "yaml": @@ -382,7 +386,7 @@ function printChildren(path, options, print) { return concat([ breakParent, concat( - path.map(childPath => { + path.map((childPath) => { const childNode = childPath.getValue(); const prevBetweenLine = !childNode.prev ? "" @@ -392,12 +396,12 @@ function printChildren(path, options, print) { ? "" : concat([ prevBetweenLine, - forceNextEmptyLine(childNode.prev) ? hardline : "" + forceNextEmptyLine(childNode.prev) ? hardline : "", ]), - printChild(childPath) + printChild(childPath), ]); }, "children") - ) + ), ]); } @@ -443,7 +447,7 @@ function printChildren(path, options, print) { } else { leadingParts.push( ifBreak("", softline, { - groupId: groupIds[childIndex - 1] + groupId: groupIds[childIndex - 1], }) ); } @@ -471,8 +475,8 @@ function printChildren(path, options, print) { concat([ concat(leadingParts), group(concat([printChild(childPath), concat(trailingParts)]), { - id: groupIds[childIndex] - }) + id: groupIds[childIndex], + }), ]) ), nextParts @@ -624,14 +628,14 @@ function printOpeningTag(path, options, print) { forceNotToBreakAttrContent ? " " : line, join( line, - (ignoreAttributeData => { + ((ignoreAttributeData) => { const hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? () => ignoreAttributeData : Array.isArray(ignoreAttributeData) - ? attr => ignoreAttributeData.includes(attr.rawName) + ? (attr) => ignoreAttributeData.includes(attr.rawName) : () => false; - return path.map(attrPath => { + return path.map((attrPath) => { const attr = attrPath.getValue(); return hasPrettierIgnoreAttribute(attr) ? concat( @@ -650,7 +654,7 @@ function printOpeningTag(path, options, print) { node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData(node.prev.value) ) - ) + ), ]) ), /** @@ -678,9 +682,9 @@ function printOpeningTag(path, options, print) { : line : forceNotToBreakAttrContent ? "" - : softline + : softline, ]), - node.isSelfClosing ? "" : printOpeningTagEnd(node) + node.isSelfClosing ? "" : printOpeningTagEnd(node), ]); } @@ -689,7 +693,7 @@ function printOpeningTagStart(node, options) { ? "" : concat([ printOpeningTagPrefix(node, options), - printOpeningTagStartMarker(node) + printOpeningTagStartMarker(node), ]); } @@ -703,7 +707,7 @@ function printOpeningTagEnd(node) { function printClosingTag(node, options) { return concat([ node.isSelfClosing ? "" : printClosingTagStart(node, options), - printClosingTagEnd(node, options) + printClosingTagEnd(node, options), ]); } @@ -713,18 +717,20 @@ function printClosingTagStart(node, options) { ? "" : concat([ printClosingTagPrefix(node, options), - printClosingTagStartMarker(node, options) + printClosingTagStartMarker(node, options), ]); } function printClosingTagEnd(node, options) { - return (node.next - ? needsToBorrowPrevClosingTagEndMarker(node.next) - : needsToBorrowLastChildClosingTagEndMarker(node.parent)) + return ( + node.next + ? needsToBorrowPrevClosingTagEndMarker(node.next) + : needsToBorrowLastChildClosingTagEndMarker(node.parent) + ) ? "" : concat([ printClosingTagEndMarker(node, options), - printClosingTagSuffix(node, options) + printClosingTagSuffix(node, options), ]); } @@ -921,7 +927,7 @@ function getTextValueParts(node, value = node.value) { } function printEmbeddedAttributeValue(node, originalTextToDoc, options) { - const isKeyMatched = patterns => + const isKeyMatched = (patterns) => new RegExp(patterns.join("|")).test(node.fullName); const getValue = () => unescapeQuoteEntities(node.value); @@ -950,15 +956,15 @@ function printEmbeddedAttributeValue(node, originalTextToDoc, options) { } }; - const printHug = doc => group(doc); + const printHug = (doc) => group(doc); const printExpand = (doc, canHaveTrailingWhitespace = true) => group( concat([ indent(concat([softline, doc])), - canHaveTrailingWhitespace ? softline : "" + canHaveTrailingWhitespace ? softline : "", ]) ); - const printMaybeHug = doc => (shouldHug ? printHug(doc) : printExpand(doc)); + const printMaybeHug = (doc) => (shouldHug ? printHug(doc) : printExpand(doc)); const textToDoc = (code, opts) => originalTextToDoc(code, { __onHtmlBindingRoot, ...opts }); @@ -983,7 +989,7 @@ function printEmbeddedAttributeValue(node, originalTextToDoc, options) { return printExpand( textToDoc(value, { parser: "css", - __isHTMLStyleAttribute: true + __isHTMLStyleAttribute: true, }) ); } @@ -1063,7 +1069,7 @@ function printEmbeddedAttributeValue(node, originalTextToDoc, options) { "^\\[.+\\]$", "^bind(on)?-", // Unofficial rudimentary support for some of the most used directives of AngularJS 1.x - "^ng-(if|show|hide|class|style)$" + "^ng-(if|show|hide|class|style)$", ]; /** * i18n="longDescription" @@ -1111,12 +1117,12 @@ function printEmbeddedAttributeValue(node, originalTextToDoc, options) { line, ngTextToDoc(part, { parser: "__ng_interpolation", - __isInHtmlInterpolation: true // to avoid unexpected `}}` - }) + __isInHtmlInterpolation: true, // to avoid unexpected `}}` + }), ]) ), line, - "}}" + "}}", ]) ) ); @@ -1141,5 +1147,5 @@ module.exports = { print: genericPrint, insertPragma, massageAstNode: clean, - embed + embed, }; diff --git a/src/language-html/syntax-attribute.js b/src/language-html/syntax-attribute.js index 8d1b32936..c3a63d49a 100644 --- a/src/language-html/syntax-attribute.js +++ b/src/language-html/syntax-attribute.js @@ -1,16 +1,16 @@ "use strict"; const { - builders: { concat, ifBreak, join, line } + builders: { concat, ifBreak, join, line }, } = require("../document"); const parseSrcset = require("srcset").parse; function printImgSrcset(value) { const srcset = parseSrcset(value); - const hasW = srcset.some(src => src.width); - const hasH = srcset.some(src => src.height); - const hasX = srcset.some(src => src.density); + const hasW = srcset.some((src) => src.width); + const hasH = srcset.some((src) => src.height); + const hasX = srcset.some((src) => src.density); if (hasW + hasH + hasX > 1) { throw new Error("Mixed descriptor in srcset is not supported"); @@ -19,15 +19,15 @@ function printImgSrcset(value) { const key = hasW ? "width" : hasH ? "height" : "density"; const unit = hasW ? "w" : hasH ? "h" : "x"; - const getMax = values => Math.max(...values); + const getMax = (values) => Math.max(...values); - const urls = srcset.map(src => src.url); - const maxUrlLength = getMax(urls.map(url => url.length)); + const urls = srcset.map((src) => src.url); + const maxUrlLength = getMax(urls.map((url) => url.length)); const descriptors = srcset - .map(src => src[key]) - .map(descriptor => (descriptor ? descriptor.toString() : "")); - const descriptorLeftLengths = descriptors.map(descriptor => { + .map((src) => src[key]) + .map((descriptor) => (descriptor ? descriptor.toString() : "")); + const descriptorLeftLengths = descriptors.map((descriptor) => { const index = descriptor.indexOf("."); return index === -1 ? descriptor.length : index; }); @@ -54,13 +54,10 @@ function printImgSrcset(value) { } function printClassNames(value) { - return value - .trim() - .split(/\s+/) - .join(" "); + return value.trim().split(/\s+/).join(" "); } module.exports = { printImgSrcset, - printClassNames + printClassNames, }; diff --git a/src/language-html/syntax-vue.js b/src/language-html/syntax-vue.js index 2509b16a0..4d5e44e2e 100644 --- a/src/language-html/syntax-vue.js +++ b/src/language-html/syntax-vue.js @@ -1,7 +1,7 @@ "use strict"; const { - builders: { concat, group } + builders: { concat, group }, } = require("../document"); /** @@ -16,13 +16,13 @@ function printVueFor(value, textToDoc) { group( textToDoc(`function _(${left}) {}`, { parser: "babel", - __isVueForBindingLeft: true + __isVueForBindingLeft: true, }) ), " ", operator, " ", - textToDoc(right, { parser: "__js_expression" }) + textToDoc(right, { parser: "__js_expression" }), ]); } @@ -55,14 +55,14 @@ function parseVueFor(value) { .filter(Boolean) .join(",")}`, operator: inMatch[2], - right: res.for + right: res.for, }; } function printVueSlotScope(value, textToDoc) { return textToDoc(`function _(${value}) {}`, { parser: "babel", - __isVueSlotScope: true + __isVueSlotScope: true, }); } @@ -82,5 +82,5 @@ function isVueEventBindingExpression(eventBindingValue) { module.exports = { isVueEventBindingExpression, printVueFor, - printVueSlotScope + printVueSlotScope, }; diff --git a/src/language-html/utils.js b/src/language-html/utils.js index eaa8f0b5d..978c69785 100644 --- a/src/language-html/utils.js +++ b/src/language-html/utils.js @@ -4,7 +4,7 @@ const { CSS_DISPLAY_TAGS, CSS_DISPLAY_DEFAULT, CSS_WHITE_SPACE_TAGS, - CSS_WHITE_SPACE_DEFAULT + CSS_WHITE_SPACE_DEFAULT, } = require("./constants.evaluate"); const htmlTagNames = require("html-tag-names"); @@ -71,7 +71,7 @@ function shouldPreserveContent(node, options) { "style", "script", // vue parser can be used for vue dom template as well, so we should still format top-level - "html" + "html", ].includes(node.fullName) ) { return true; @@ -81,7 +81,7 @@ function shouldPreserveContent(node, options) { if ( isPreLikeNode(node) && node.children.some( - child => child.type !== "text" && child.type !== "interpolation" + (child) => child.type !== "text" && child.type !== "interpolation" ) ) { return true; @@ -279,7 +279,7 @@ function forceBreakContent(node) { (node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].includes(node.name) || - node.children.some(child => hasNonTextChild(child)))) || + node.children.some((child) => hasNonTextChild(child)))) || (node.firstChild && node.firstChild === node.lastChild && hasLeadingLineBreak(node.firstChild) && @@ -356,7 +356,7 @@ function getLastDescendant(node) { } function hasNonTextChild(node) { - return node.children && node.children.some(child => child.type !== "text"); + return node.children && node.children.some((child) => child.type !== "text"); } function inferScriptParser(node) { @@ -490,7 +490,7 @@ function getNodeCssStyleDisplay(node, options) { let isInSvgForeignObject = false; if (node.type === "element" && node.namespace === "svg") { - if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) { + if (hasParent(node, (parent) => parent.fullName === "svg:foreignObject")) { isInSvgForeignObject = true; } else { return node.name === "svg" ? "inline-block" : "block"; @@ -562,7 +562,7 @@ function dedentString(text, minIndent = getMinIndentation(text)) { ? text : text .split("\n") - .map(lineText => lineText.slice(minIndent)) + .map((lineText) => lineText.slice(minIndent)) .join("\n"); } @@ -655,5 +655,5 @@ module.exports = { preferHardlineAsTrailingSpaces, shouldNotPrintClosingTag, shouldPreserveContent, - unescapeQuoteEntities + unescapeQuoteEntities, }; diff --git a/src/language-js/clean.js b/src/language-js/clean.js index ca95cbb4f..f7b04e53f 100644 --- a/src/language-js/clean.js +++ b/src/language-js/clean.js @@ -12,8 +12,8 @@ function clean(ast, newObj, parent) { "start", "end", "flags", - "errors" - ].forEach(name => { + "errors", + ].forEach((name) => { delete newObj[name]; }); @@ -53,7 +53,7 @@ function clean(ast, newObj, parent) { type: "Identifier", name: ast.parameter.name, typeAnnotation: newObj.parameter.typeAnnotation, - decorators: newObj.decorators + decorators: newObj.decorators, }; } @@ -101,22 +101,22 @@ function clean(ast, newObj, parent) { if ( ast.type === "JSXElement" && ast.openingElement.name.name === "style" && - ast.openingElement.attributes.some(attr => attr.name.name === "jsx") + ast.openingElement.attributes.some((attr) => attr.name.name === "jsx") ) { const templateLiterals = newObj.children .filter( - child => + (child) => child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral" ) - .map(container => container.expression); + .map((container) => container.expression); const quasis = templateLiterals.reduce( (quasis, templateLiteral) => quasis.concat(templateLiteral.quasis), [] ); - quasis.forEach(q => delete q.value); + quasis.forEach((q) => delete q.value); } // CSS template literals in css prop @@ -126,7 +126,7 @@ function clean(ast, newObj, parent) { ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral" ) { - newObj.value.expression.quasis.forEach(q => delete q.value); + newObj.value.expression.quasis.forEach((q) => delete q.value); } // Angular Components: Inline HTML template and Inline CSS styles @@ -155,7 +155,7 @@ function clean(ast, newObj, parent) { } if (templateLiteral) { - templateLiteral.quasis.forEach(q => delete q.value); + templateLiteral.quasis.forEach((q) => delete q.value); } }); } @@ -173,7 +173,7 @@ function clean(ast, newObj, parent) { ast.tag.name === "html")) || ast.tag.type === "CallExpression") ) { - newObj.quasi.quasis.forEach(quasi => delete quasi.value); + newObj.quasi.quasis.forEach((quasi) => delete quasi.value); } if (ast.type === "TemplateLiteral") { // This checks for a leading comment that is exactly `/* GraphQL */` @@ -184,17 +184,17 @@ function clean(ast, newObj, parent) { const hasLanguageComment = ast.leadingComments && ast.leadingComments.some( - comment => + (comment) => comment.type === "CommentBlock" && ["GraphQL", "HTML"].some( - languageName => comment.value === ` ${languageName} ` + (languageName) => comment.value === ` ${languageName} ` ) ); if ( hasLanguageComment || (parent.type === "CallExpression" && parent.callee.name === "graphql") ) { - newObj.quasis.forEach(quasi => delete quasi.value); + newObj.quasis.forEach((quasi) => delete quasi.value); } } } diff --git a/src/language-js/comments.js b/src/language-js/comments.js index 627498d29..fcc9f8a34 100644 --- a/src/language-js/comments.js +++ b/src/language-js/comments.js @@ -5,7 +5,7 @@ const { addLeadingComment, addTrailingComment, addDanglingComment, - getNextNonSpaceNonCommentCharacterIndex + getNextNonSpaceNonCommentCharacterIndex, } = require("../common/util-shared"); function handleOwnLineComment(comment, text, options, ast, isLastComment) { @@ -184,7 +184,7 @@ function handleRemainingComment(comment, text, options, ast, isLastComment) { } function addBlockStatementFirstComment(node, comment) { - const body = node.body.filter(n => n.type !== "EmptyStatement"); + const body = node.body.filter((n) => n.type !== "EmptyStatement"); if (body.length === 0) { addDanglingComment(node, comment); } else { @@ -902,7 +902,7 @@ function hasLeadingComment(node, fn = () => true) { return node.leadingComments.some(fn); } if (node.comments) { - return node.comments.some(comment => comment.leading && fn(comment)); + return node.comments.some((comment) => comment.leading && fn(comment)); } return false; } @@ -978,5 +978,5 @@ module.exports = { isBlockComment, isTypeCastComment, getGapRegex, - getCommentChildNodes + getCommentChildNodes, }; diff --git a/src/language-js/embed.js b/src/language-js/embed.js index 263e134d8..64ef0d39d 100644 --- a/src/language-js/embed.js +++ b/src/language-js/embed.js @@ -12,9 +12,9 @@ const { literalline, concat, group, - dedentToRoot + dedentToRoot, }, - utils: { mapDoc, stripTrailingHardline } + utils: { mapDoc, stripTrailingHardline }, } = require("../document"); function embed(path, print, textToDoc, options) { @@ -28,12 +28,12 @@ function embed(path, print, textToDoc, options) { isStyledJsx, isStyledComponents, isCssProp, - isAngularComponentStyles - ].some(isIt => isIt(path)); + isAngularComponentStyles, + ].some((isIt) => isIt(path)); if (isCss) { // Get full template literal with expressions replaced by placeholders - const rawQuasis = node.quasis.map(q => q.value.raw); + const rawQuasis = node.quasis.map((q) => q.value.raw); let placeholderID = 0; const text = rawQuasis.reduce((prevVal, currVal, idx) => { return idx === 0 @@ -93,7 +93,7 @@ function embed(path, print, textToDoc, options) { lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === ""; - const commentsAndWhitespaceOnly = lines.every(line => + const commentsAndWhitespaceOnly = lines.every((line) => /^\s*(?:#[^\r\n]*)?$/.test(line) ); @@ -132,7 +132,7 @@ function embed(path, print, textToDoc, options) { "`", indent(concat([hardline, join(hardline, parts)])), hardline, - "`" + "`", ]); } @@ -180,11 +180,11 @@ function embed(path, print, textToDoc, options) { softline, printMarkdown( text.replace(new RegExp(`^${indentation}`, "gm"), "") - ) + ), ]) ) : concat([literalline, dedentToRoot(printMarkdown(text))]), - softline + softline, ]); } @@ -208,14 +208,14 @@ function uncook(cookedValue) { } function escapeTemplateCharacters(doc, raw) { - return mapDoc(doc, currentDoc => { + return mapDoc(doc, (currentDoc) => { if (!currentDoc.parts) { return currentDoc; } const parts = []; - currentDoc.parts.forEach(part => { + currentDoc.parts.forEach((part) => { if (typeof part === "string") { parts.push(raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part)); } else { @@ -248,7 +248,7 @@ function transformCssDoc(quasisDoc, path, print) { "`", indent(concat([hardline, stripTrailingHardline(newDoc)])), softline, - "`" + "`", ]); } @@ -263,7 +263,7 @@ function replacePlaceholders(quasisDoc, expressionDocs) { const expressions = expressionDocs.slice(); let replaceCounter = 0; - const newDoc = mapDoc(quasisDoc, doc => { + const newDoc = mapDoc(quasisDoc, (doc) => { if (!doc || !doc.parts || !doc.parts.length) { return doc; } @@ -285,7 +285,7 @@ function replacePlaceholders(quasisDoc, expressionDocs) { .concat(rest); } const atPlaceholderIndex = parts.findIndex( - part => + (part) => typeof part === "string" && part.startsWith("@prettier-placeholder") ); if (atPlaceholderIndex > -1) { @@ -317,7 +317,7 @@ function printGraphqlComments(lines) { let seenComment = false; lines - .map(textLine => textLine.trim()) + .map((textLine) => textLine.trim()) .forEach((textLine, i, array) => { // Lines are either whitespace only, or a comment (with potential whitespace // around it). Drop whitespace-only lines. @@ -358,7 +358,7 @@ function isStyledJsx(path) { parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some( - attribute => attribute.name.name === "jsx" + (attribute) => attribute.name.name === "jsx" )) || (parent && parent.type === "TaggedTemplateExpression" && @@ -389,7 +389,7 @@ function isStyledJsx(path) { */ function isAngularComponentStyles(path) { return path.match( - node => node.type === "TemplateLiteral", + (node) => node.type === "TemplateLiteral", (node, name) => node.type === "ArrayExpression" && name === "elements", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && @@ -401,7 +401,7 @@ function isAngularComponentStyles(path) { } function isAngularComponentTemplate(path) { return path.match( - node => node.type === "TemplateLiteral", + (node) => node.type === "TemplateLiteral", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && @@ -417,7 +417,7 @@ const angularComponentObjectExpressionPredicates = [ node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments", - (node, name) => node.type === "Decorator" && name === "expression" + (node, name) => node.type === "Decorator" && name === "expression", ]; /** @@ -525,7 +525,8 @@ function hasLanguageComment(node, languageName) { // Also see ./clean.js return hasLeadingComment( node, - comment => isBlockComment(comment) && comment.value === ` ${languageName} ` + (comment) => + isBlockComment(comment) && comment.value === ` ${languageName} ` ); } @@ -537,7 +538,7 @@ function isHtml(path) { return ( hasLanguageComment(path.getValue(), "HTML") || path.match( - node => node.type === "TemplateLiteral", + (node) => node.type === "TemplateLiteral", (node, name) => node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && @@ -556,7 +557,7 @@ function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) { const counter = htmlTemplateLiteralCounter; htmlTemplateLiteralCounter = (htmlTemplateLiteralCounter + 1) >>> 0; - const composePlaceholder = index => + const composePlaceholder = (index) => `PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`; const text = node.quasis @@ -582,10 +583,10 @@ function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) { parser, __onHtmlRoot(root) { topLevelCount = root.children.length; - } + }, }) ), - doc => { + (doc) => { if (typeof doc !== "string") { return doc; } @@ -633,7 +634,7 @@ function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) { "`", indent(concat([linebreak, group(contentDoc)])), linebreak, - "`" + "`", ]) ); } @@ -644,7 +645,7 @@ function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) { leadingWhitespace, topLevelCount > 1 ? indent(group(contentDoc)) : group(contentDoc), trailingWhitespace, - "`" + "`", ]) ); } diff --git a/src/language-js/html-binding.js b/src/language-js/html-binding.js index 0335865e5..c47946f34 100644 --- a/src/language-js/html-binding.js +++ b/src/language-js/html-binding.js @@ -1,7 +1,7 @@ "use strict"; const { - builders: { concat, join, line } + builders: { concat, join, line }, } = require("../document"); function printHtmlBinding(path, options, print) { @@ -17,7 +17,7 @@ function printHtmlBinding(path, options, print) { if (options.__isVueForBindingLeft) { return path.call( - functionDeclarationPath => { + (functionDeclarationPath) => { const { params } = functionDeclarationPath.getValue(); return concat([ params.length > 1 ? "(" : "", @@ -25,7 +25,7 @@ function printHtmlBinding(path, options, print) { concat([",", line]), functionDeclarationPath.map(print, "params") ), - params.length > 1 ? ")" : "" + params.length > 1 ? ")" : "", ]); }, "program", @@ -36,7 +36,7 @@ function printHtmlBinding(path, options, print) { if (options.__isVueSlotScope) { return path.call( - functionDeclarationPath => + (functionDeclarationPath) => join(concat([",", line]), functionDeclarationPath.map(print, "params")), "program", "body", @@ -65,5 +65,5 @@ function isVueEventBindingExpression(node) { module.exports = { isVueEventBindingExpression, - printHtmlBinding + printHtmlBinding, }; diff --git a/src/language-js/index.js b/src/language-js/index.js index 8e4ca448d..380bc5551 100644 --- a/src/language-js/index.js +++ b/src/language-js/index.js @@ -6,11 +6,11 @@ const options = require("./options"); const createLanguage = require("../utils/create-language"); const languages = [ - createLanguage(require("linguist-languages/data/JavaScript"), data => ({ + createLanguage(require("linguist-languages/data/JavaScript"), (data) => ({ since: "0.0.0", parsers: ["babel", "flow"], vscodeLanguageIds: ["javascript", "mongo"], - interpreters: data.interpreters.concat(["nodejs"]) + interpreters: data.interpreters.concat(["nodejs"]), })), createLanguage(require("linguist-languages/data/JavaScript"), () => ({ name: "Flow", @@ -19,22 +19,22 @@ const languages = [ vscodeLanguageIds: ["javascript"], aliases: [], filenames: [], - extensions: [".js.flow"] + extensions: [".js.flow"], })), createLanguage(require("linguist-languages/data/JSX"), () => ({ since: "0.0.0", parsers: ["babel", "flow"], - vscodeLanguageIds: ["javascriptreact"] + vscodeLanguageIds: ["javascriptreact"], })), createLanguage(require("linguist-languages/data/TypeScript"), () => ({ since: "1.4.0", parsers: ["typescript", "babel-ts"], - vscodeLanguageIds: ["typescript"] + vscodeLanguageIds: ["typescript"], })), createLanguage(require("linguist-languages/data/TSX"), () => ({ since: "1.4.0", parsers: ["typescript", "babel-ts"], - vscodeLanguageIds: ["typescriptreact"] + vscodeLanguageIds: ["typescriptreact"], })), createLanguage(require("linguist-languages/data/JSON"), () => ({ name: "JSON.stringify", @@ -42,37 +42,37 @@ const languages = [ parsers: ["json-stringify"], vscodeLanguageIds: ["json"], extensions: [], // .json file defaults to json instead of json-stringify - filenames: ["package.json", "package-lock.json", "composer.json"] + filenames: ["package.json", "package-lock.json", "composer.json"], })), - createLanguage(require("linguist-languages/data/JSON"), data => ({ + createLanguage(require("linguist-languages/data/JSON"), (data) => ({ since: "1.5.0", parsers: ["json"], vscodeLanguageIds: ["json"], - filenames: data.filenames.concat([".prettierrc"]) + filenames: data.filenames.concat([".prettierrc"]), })), createLanguage( require("linguist-languages/data/JSON with Comments"), - data => ({ + (data) => ({ since: "1.5.0", parsers: ["json"], vscodeLanguageIds: ["jsonc"], - filenames: data.filenames.concat([".eslintrc"]) + filenames: data.filenames.concat([".eslintrc"]), }) ), createLanguage(require("linguist-languages/data/JSON5"), () => ({ since: "1.13.0", parsers: ["json5"], - vscodeLanguageIds: ["json5"] - })) + vscodeLanguageIds: ["json5"], + })), ]; const printers = { estree: estreePrinter, - "estree-json": estreeJsonPrinter + "estree-json": estreeJsonPrinter, }; module.exports = { languages, options, - printers + printers, }; diff --git a/src/language-js/loc.js b/src/language-js/loc.js index 98df29f90..ca81bc23e 100644 --- a/src/language-js/loc.js +++ b/src/language-js/loc.js @@ -73,13 +73,13 @@ function composeLoc(startNode, endNodeOrLength = startNode) { end: length !== -1 ? { line: startLoc.line, column: startLoc.column + length } - : endNodeOrLength.loc.end - } + : endNodeOrLength.loc.end, + }, }; } module.exports = { locStart, locEnd, - composeLoc + composeLoc, }; diff --git a/src/language-js/needs-parens.js b/src/language-js/needs-parens.js index c0d4edfd8..dfaa165c4 100644 --- a/src/language-js/needs-parens.js +++ b/src/language-js/needs-parens.js @@ -7,7 +7,7 @@ const { getLeftSidePathName, hasFlowShorthandAnnotationComment, hasNakedLeftSide, - hasNode + hasNode, } = require("./utils"); function needsParens(path, options) { @@ -208,7 +208,7 @@ function needsParens(path, options) { return true; } - const isLeftOfAForStatement = node => { + const isLeftOfAForStatement = (node) => { let i = 0; while (node) { const parent = path.getParentNode(i++); @@ -759,9 +759,12 @@ function isStatement(node) { function includesFunctionTypeInObjectType(node) { return hasNode( node, - n1 => + (n1) => (n1.type === "ObjectTypeAnnotation" && - hasNode(n1, n2 => n2.type === "FunctionTypeAnnotation" || undefined)) || + hasNode( + n1, + (n2) => n2.type === "FunctionTypeAnnotation" || undefined + )) || undefined ); } @@ -839,7 +842,7 @@ function shouldWrapFunctionForExportDefault(path, options) { } return path.call( - childPath => shouldWrapFunctionForExportDefault(childPath, options), + (childPath) => shouldWrapFunctionForExportDefault(childPath, options), ...getLeftSidePathName(path, node) ); } diff --git a/src/language-js/options.js b/src/language-js/options.js index 568cd648b..7dea5b00d 100644 --- a/src/language-js/options.js +++ b/src/language-js/options.js @@ -12,19 +12,19 @@ module.exports = { type: "choice", default: [ { since: "1.9.0", value: "avoid" }, - { since: "2.0.0", value: "always" } + { since: "2.0.0", value: "always" }, ], description: "Include parentheses around a sole arrow function parameter.", choices: [ { value: "always", - description: "Always include parens. Example: `(x) => x`" + description: "Always include parens. Example: `(x) => x`", }, { value: "avoid", - description: "Omit parens when possible. Example: `x => x`" - } - ] + description: "Omit parens when possible. Example: `x => x`", + }, + ], }, bracketSpacing: commonOptions.bracketSpacing, jsxBracketSameLine: { @@ -32,7 +32,7 @@ module.exports = { category: CATEGORY_JAVASCRIPT, type: "boolean", default: false, - description: "Put > on the last line instead of at a new line." + description: "Put > on the last line instead of at a new line.", }, semi: { since: "1.0.0", @@ -41,7 +41,7 @@ module.exports = { default: true, description: "Print semicolons.", oppositeDescription: - "Do not print semicolons, except at the beginning of lines which may need them." + "Do not print semicolons, except at the beginning of lines which may need them.", }, singleQuote: commonOptions.singleQuote, jsxSingleQuote: { @@ -49,7 +49,7 @@ module.exports = { category: CATEGORY_JAVASCRIPT, type: "boolean", default: false, - description: "Use single quotes in JSX." + description: "Use single quotes in JSX.", }, quoteProps: { since: "1.17.0", @@ -60,18 +60,18 @@ module.exports = { choices: [ { value: "as-needed", - description: "Only add quotes around object properties where required." + description: "Only add quotes around object properties where required.", }, { value: "consistent", description: - "If at least one property in an object requires quotes, quote all properties." + "If at least one property in an object requires quotes, quote all properties.", }, { value: "preserve", - description: "Respect the input use of quotes in object properties." - } - ] + description: "Respect the input use of quotes in object properties.", + }, + ], }, trailingComma: { since: "0.0.0", @@ -80,21 +80,21 @@ module.exports = { default: [ { since: "0.0.0", value: false }, { since: "0.19.0", value: "none" }, - { since: "2.0.0", value: "es5" } + { since: "2.0.0", value: "es5" }, ], description: "Print trailing commas wherever possible when multi-line.", choices: [ { value: "es5", description: - "Trailing commas where valid in ES5 (objects, arrays, etc.)" + "Trailing commas where valid in ES5 (objects, arrays, etc.)", }, { value: "none", description: "No trailing commas." }, { value: "all", description: - "Trailing commas wherever possible (including function arguments)." - } - ] - } + "Trailing commas wherever possible (including function arguments).", + }, + ], + }, }; diff --git a/src/language-js/parser-angular.js b/src/language-js/parser-angular.js index 0201a2f11..3df11f3f3 100644 --- a/src/language-js/parser-angular.js +++ b/src/language-js/parser-angular.js @@ -11,7 +11,7 @@ function createParser(_parse) { node: options.parser === "__ng_action" && node.type !== "NGChainedExpression" ? { ...node, type: "NGChainedExpression", expressions: [node] } - : node + : node, }; }; return { astFormat: "estree", parse, ...locFns }; @@ -22,6 +22,6 @@ module.exports = { __ng_action: createParser((text, ng) => ng.parseAction(text)), __ng_binding: createParser((text, ng) => ng.parseBinding(text)), __ng_interpolation: createParser((text, ng) => ng.parseInterpolation(text)), - __ng_directive: createParser((text, ng) => ng.parseTemplateBindings(text)) - } + __ng_directive: createParser((text, ng) => ng.parseTemplateBindings(text)), + }, }; diff --git a/src/language-js/parser-babel.js b/src/language-js/parser-babel.js index ace510b79..0ef8ffb5b 100644 --- a/src/language-js/parser-babel.js +++ b/src/language-js/parser-babel.js @@ -39,8 +39,8 @@ function babelOptions(extraPlugins = []) { "v8intrinsic", "partialApplication", ["decorators", { decoratorsBeforeExport: false }], - ...extraPlugins - ] + ...extraPlugins, + ], }; } @@ -52,7 +52,7 @@ function createParse(parseMethod, ...pluginCombinations) { let ast; try { ast = tryCombinations( - options => babel[parseMethod](text, options), + (options) => babel[parseMethod](text, options), pluginCombinations.map(babelOptions) ); } catch (error) { @@ -63,8 +63,8 @@ function createParse(parseMethod, ...pluginCombinations) { { start: { line: error.loc.line, - column: error.loc.column + 1 - } + column: error.loc.column + 1, + }, } ); } @@ -76,7 +76,7 @@ function createParse(parseMethod, ...pluginCombinations) { const parse = createParse("parse", ["jsx", "flow"]); const parseFlow = createParse("parse", [ "jsx", - ["flow", { all: true, enums: true }] + ["flow", { all: true, enums: true }], ]); const parseTypeScript = createParse( "parse", @@ -160,8 +160,8 @@ function assertJsonNode(node, parent) { return createError(`${name} is not allowed in JSON.`, { start: { line: node.loc.start.line, - column: node.loc.start.column + 1 - } + column: node.loc.start.column + 1, + }, }); } } @@ -181,19 +181,19 @@ module.exports = { ...babelExpression, hasPragma() { return true; - } + }, }, json5: babelExpression, "json-stringify": { parse: parseJson, astFormat: "estree-json", - ...locFns + ...locFns, }, /** @internal */ __js_expression: babelExpression, /** for vue filter */ __vue_expression: babelExpression, /** for vue event binding to handle semicolon */ - __vue_event_binding: babel - } + __vue_event_binding: babel, + }, }; diff --git a/src/language-js/parser-flow.js b/src/language-js/parser-flow.js index 637029989..1cafd8c4d 100644 --- a/src/language-js/parser-flow.js +++ b/src/language-js/parser-flow.js @@ -17,14 +17,14 @@ function parse(text, parsers, opts) { esproposal_class_static_fields: true, esproposal_export_star_as: true, esproposal_optional_chaining: true, - esproposal_nullish_coalescing: true + esproposal_nullish_coalescing: true, }); if (ast.errors.length > 0) { const { loc } = ast.errors[0]; throw createError(ast.errors[0].message, { start: { line: loc.start.line, column: loc.start.column + 1 }, - end: { line: loc.end.line, column: loc.end.column + 1 } + end: { line: loc.end.line, column: loc.end.column + 1 }, }); } @@ -35,6 +35,6 @@ function parse(text, parsers, opts) { // Export as a plugin so we can reuse the same bundle for UMD loading module.exports = { parsers: { - flow: { parse, astFormat: "estree", hasPragma, ...locFns } - } + flow: { parse, astFormat: "estree", hasPragma, ...locFns }, + }, }; diff --git a/src/language-js/parser-typescript.js b/src/language-js/parser-typescript.js index fc3fa4f0b..300bffbc8 100644 --- a/src/language-js/parser-typescript.js +++ b/src/language-js/parser-typescript.js @@ -25,7 +25,7 @@ function parse(text, parsers, opts) { } throw createError(e.message, { - start: { line: e.lineNumber, column: e.column + 1 } + start: { line: e.lineNumber, column: e.column + 1 }, }); } } @@ -41,7 +41,7 @@ function tryParseTypeScript(text, jsx) { range: true, comment: true, useJSXTextNode: true, - jsx + jsx, }); } @@ -53,7 +53,7 @@ function isProbablyJsx(text) { [ "(^[^\"'`]*)" // Contains "/>" on line not starting with "//" + "(^[^/]{2}.*/>)", // Contains "/>" on line not starting with "//" ].join(""), "m" ).test(text); @@ -64,6 +64,6 @@ const parser = { parse, astFormat: "estree", hasPragma, ...locFns }; // Export as a plugin so we can reuse the same bundle for UMD loading module.exports = { parsers: { - typescript: parser - } + typescript: parser, + }, }; diff --git a/src/language-js/postprocess.js b/src/language-js/postprocess.js index e3dd46800..e35279825 100644 --- a/src/language-js/postprocess.js +++ b/src/language-js/postprocess.js @@ -2,7 +2,7 @@ const { getLast, - getNextNonSpaceNonCommentCharacter + getNextNonSpaceNonCommentCharacter, } = require("../common/util"); const { composeLoc, locEnd } = require("./loc"); const { isTypeCastComment } = require("./comments"); @@ -16,7 +16,7 @@ function postprocess(ast, options) { // E.g.: /** @type {Foo} */ (foo).bar(); // Let's use the fact that those ancestors and ParenthesizedExpression have the same start offset. - visitNode(ast, node => { + visitNode(ast, (node) => { if ( node.leadingComments && node.leadingComments.some(isTypeCastComment) @@ -25,7 +25,7 @@ function postprocess(ast, options) { } }); - visitNode(ast, node => { + visitNode(ast, (node) => { if ( node.type === "ParenthesizedExpression" && !startOffsetsOfTypeCastedNodes.has(node.start) @@ -41,7 +41,7 @@ function postprocess(ast, options) { }); } - visitNode(ast, node => { + visitNode(ast, (node) => { switch (node.type) { case "LogicalExpression": { // We remove unneeded parens around same-operator LogicalExpressions @@ -75,7 +75,7 @@ function postprocess(ast, options) { node.name = { type: "Identifier", name: node.name, - ...composeLoc(node, node.name.length) + ...composeLoc(node, node.name.length), }; } break; @@ -115,14 +115,14 @@ function postprocess(ast, options) { if (Array.isArray(toBeOverriddenNode.range)) { toBeOverriddenNode.range = [ toBeOverriddenNode.range[0], - toOverrideNode.range[1] + toOverrideNode.range[1], ]; } else { toBeOverriddenNode.end = toOverrideNode.end; } toBeOverriddenNode.loc = { ...toBeOverriddenNode.loc, - end: toBeOverriddenNode.loc.end + end: toBeOverriddenNode.loc.end, }; } } @@ -175,10 +175,10 @@ function rebalanceLogicalTree(node) { operator: node.operator, left: node.left, right: node.right.left, - ...composeLoc(node.left, node.right.left) + ...composeLoc(node.left, node.right.left), }), right: node.right.right, - ...composeLoc(node) + ...composeLoc(node), }); } diff --git a/src/language-js/pragma.js b/src/language-js/pragma.js index c2a2786a8..6f73a305d 100644 --- a/src/language-js/pragma.js +++ b/src/language-js/pragma.js @@ -13,7 +13,7 @@ function insertPragma(text) { const newDocblock = docblock .print({ pragmas, - comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines + comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, ""), // remove leading newlines }) .replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock) const strippedText = docblock.strip(text); @@ -23,5 +23,5 @@ function insertPragma(text) { module.exports = { hasPragma, - insertPragma + insertPragma, }; diff --git a/src/language-js/preprocess.js b/src/language-js/preprocess.js index 9a60f6e11..b776cab9b 100644 --- a/src/language-js/preprocess.js +++ b/src/language-js/preprocess.js @@ -12,7 +12,7 @@ function preprocess(ast, options) { type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot", node: ast, comments: [], - rootMarker: options.rootMarker + rootMarker: options.rootMarker, }; default: return ast; diff --git a/src/language-js/printer-estree-json.js b/src/language-js/printer-estree-json.js index 92e8b3bb0..e83025821 100644 --- a/src/language-js/printer-estree-json.js +++ b/src/language-js/printer-estree-json.js @@ -16,11 +16,11 @@ function genericPrint(path, options, print) { indent( concat([ hardline, - join(concat([",", hardline]), path.map(print, "elements")) + join(concat([",", hardline]), path.map(print, "elements")), ]) ), hardline, - "]" + "]", ]); case "ObjectExpression": return node.properties.length === 0 @@ -30,18 +30,18 @@ function genericPrint(path, options, print) { indent( concat([ hardline, - join(concat([",", hardline]), path.map(print, "properties")) + join(concat([",", hardline]), path.map(print, "properties")), ]) ), hardline, - "}" + "}", ]); case "ObjectProperty": return concat([path.call(print, "key"), ": ", path.call(print, "value")]); case "UnaryExpression": return concat([ node.operator === "+" ? "" : node.operator, - path.call(print, "argument") + path.call(print, "argument"), ]); case "NullLiteral": return "null"; @@ -77,5 +77,5 @@ function clean(node, newNode /*, parent*/) { module.exports = { preprocess, print: genericPrint, - massageAstNode: clean + massageAstNode: clean, }; diff --git a/src/language-js/printer-estree.js b/src/language-js/printer-estree.js index 1bf9ff156..2f7118520 100644 --- a/src/language-js/printer-estree.js +++ b/src/language-js/printer-estree.js @@ -18,12 +18,12 @@ const { getPenultimate, startsWithNoLookaheadToken, getIndentSize, - getPreferredQuote + getPreferredQuote, } = require("../common/util"); const { isNextLineEmpty, isNextLineEmptyAfterIndex, - getNextNonSpaceNonCommentCharacterIndex + getNextNonSpaceNonCommentCharacterIndex, } = require("../common/util-shared"); const embed = require("./embed"); const clean = require("./clean"); @@ -32,7 +32,7 @@ const handleComments = require("./comments"); const pathNeedsParens = require("./needs-parens"); const { printHtmlBinding, - isVueEventBindingExpression + isVueEventBindingExpression, } = require("./html-binding"); const preprocess = require("./preprocess"); const { @@ -89,7 +89,7 @@ const { matchJsxWhitespaceRegex, needsHardlineAfterDanglingComment, rawText, - returnArgumentHasLeadingComment + returnArgumentHasLeadingComment, } = require("./utils"); const needsQuoteProps = new WeakMap(); @@ -111,10 +111,10 @@ const { breakParent, lineSuffixBoundary, addAlignmentToDoc, - dedent + dedent, }, utils: { willBreak, isLineNext, isEmpty, removeLines }, - printer: { printDocToString } + printer: { printDocToString }, } = require("../document"); let uid = 0; @@ -180,7 +180,7 @@ function genericPrint(path, options, printPath, args) { const separator = shouldBreak ? hardline : line; - path.each(decoratorPath => { + path.each((decoratorPath) => { let decorator = decoratorPath.getValue(); if (decorator.expression) { decorator = decorator.expression; @@ -207,7 +207,7 @@ function genericPrint(path, options, printPath, args) { // Export declarations are responsible for printing any decorators // that logically apply to node.declaration. path.each( - decoratorPath => { + (decoratorPath) => { const decorator = decoratorPath.getValue(); const prefix = decorator.type === "Decorator" ? "" : "@"; decorators.push(prefix, printPath(decoratorPath), hardline); @@ -251,7 +251,7 @@ function printDecorators(path, options, print) { return group( concat([ join(line, path.map(print, "decorators")), - hasNewlineBetweenOrAfterDecorators(node, options) ? hardline : line + hasNewlineBetweenOrAfterDecorators(node, options) ? hardline : line, ]) ); } @@ -286,7 +286,7 @@ function printTernaryOperator(path, options, print, operatorOptions) { const parent = path.getParentNode(); const isParentTest = parent.type === operatorOptions.conditionalNodeType && - operatorOptions.testNodePropertyNames.some(prop => parent[prop] === node); + operatorOptions.testNodePropertyNames.some((prop) => parent[prop] === node); let forceNoIndent = parent.type === operatorOptions.conditionalNodeType && !isParentTest; @@ -304,7 +304,7 @@ function printTernaryOperator(path, options, print, operatorOptions) { currentParent && currentParent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.every( - prop => currentParent[prop] !== previousParent + (prop) => currentParent[prop] !== previousParent ) ); const firstNonConditionalParent = currentParent || parent; @@ -323,19 +323,19 @@ function printTernaryOperator(path, options, print, operatorOptions) { // Even though they don't need parens, we wrap (almost) everything in // parens when using ?: within JSX, because the parens are analogous to // curly braces in an if statement. - const wrap = doc => + const wrap = (doc) => concat([ ifBreak("(", ""), indent(concat([softline, doc])), softline, - ifBreak(")", "") + ifBreak(")", ""), ]); // The only things we don't wrap are: // * Nested conditional expressions in alternates // * null // * undefined - const isNil = node => + const isNil = (node) => node.type === "NullLiteral" || (node.type === "Literal" && node.value === null) || (node.type === "Identifier" && node.name === "undefined"); @@ -367,7 +367,7 @@ function printTernaryOperator(path, options, print, operatorOptions) { ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) - : align(2, path.call(print, operatorOptions.alternateNodePropertyName)) + : align(2, path.call(print, operatorOptions.alternateNodePropertyName)), ]); parts.push( parent.type !== operatorOptions.conditionalNodeType || @@ -383,7 +383,7 @@ function printTernaryOperator(path, options, print, operatorOptions) { // We want a whole chain of ConditionalExpressions to all // break if any of them break. That means we should only group around the // outer-most ConditionalExpression. - const maybeGroup = doc => + const maybeGroup = (doc) => parent === firstNonConditionalParent ? group(doc) : doc; // Break the closing paren to keep the chain right after it: @@ -401,7 +401,7 @@ function printTernaryOperator(path, options, print, operatorOptions) { const result = maybeGroup( concat( [].concat( - (testDoc => + ((testDoc) => /** * a * ? b @@ -456,7 +456,7 @@ function printPathNoParens(path, options, print, args) { if (n.program && n.program.interpreter) { parts.push( path.call( - programPath => programPath.call(print, "interpreter"), + (programPath) => programPath.call(print, "interpreter"), "program" ) ); @@ -469,7 +469,7 @@ function printPathNoParens(path, options, print, args) { case "Program": // Babel 6 if (n.directives) { - path.each(childPath => { + path.each((childPath) => { parts.push(print(childPath), semi, hardline); if ( isNextLineEmpty( @@ -484,7 +484,7 @@ function printPathNoParens(path, options, print, args) { } parts.push( - path.call(bodyPath => { + path.call((bodyPath) => { return printStatementSequence(bodyPath, options, print); }, "body") ); @@ -517,7 +517,7 @@ function printPathNoParens(path, options, print, args) { ) { return concat([ path.call(print, "expression"), - isVueEventBindingExpression(n.expression) ? ";" : "" + isVueEventBindingExpression(n.expression) ? ";" : "", ]); } } @@ -525,7 +525,7 @@ function printPathNoParens(path, options, print, args) { // Do not append semicolon after the only JSX element in a program return concat([ path.call(print, "expression"), - isTheOnlyJSXElementInMarkdown(options, path) ? "" : semi + isTheOnlyJSXElementInMarkdown(options, path) ? "" : semi, ]); // Babel non-standard node. Used for Closure-style type casts. See postprocess.js. case "ParenthesizedExpression": { @@ -538,7 +538,7 @@ function printPathNoParens(path, options, print, args) { "(", indent(concat([softline, path.call(print, "expression")])), softline, - ")" + ")", ]) ); } @@ -672,7 +672,7 @@ function printPathNoParens(path, options, print, args) { // level. The first item is guaranteed to be the first // left-most expression. parts.length > 0 ? parts[0] : "", - indent(rest) + indent(rest), ]), { id: groupId } ); @@ -690,7 +690,7 @@ function printPathNoParens(path, options, print, args) { return concat([ path.call(print, "left"), " = ", - path.call(print, "right") + path.call(print, "right"), ]); case "TSTypeAssertion": { const shouldBreakAfterCast = !( @@ -703,7 +703,7 @@ function printPathNoParens(path, options, print, args) { "<", indent(concat([softline, path.call(print, "typeAnnotation")])), softline, - ">" + ">", ]) ); @@ -711,14 +711,14 @@ function printPathNoParens(path, options, print, args) { ifBreak("("), indent(concat([softline, path.call(print, "expression")])), softline, - ifBreak(")") + ifBreak(")"), ]); if (shouldBreakAfterCast) { return conditionalGroup([ concat([castGroup, path.call(print, "expression")]), concat([castGroup, group(exprContents, { shouldBreak: true })]), - concat([castGroup, path.call(print, "expression")]) + concat([castGroup, path.call(print, "expression")]), ]); } return group(concat([castGroup, path.call(print, "expression")])); @@ -760,14 +760,14 @@ function printPathNoParens(path, options, print, args) { indent( concat([softline, printMemberLookup(path, options, print)]) ) - ) + ), ]); } case "MetaProperty": return concat([ path.call(print, "meta"), ".", - path.call(print, "property") + path.call(print, "property"), ]); case "BindExpression": if (n.object) { @@ -787,7 +787,7 @@ function printPathNoParens(path, options, print, args) { return concat([ n.name, printOptionalToken(path), - printTypeAnnotation(path, options, print) + printTypeAnnotation(path, options, print), ]); } case "V8IntrinsicIdentifier": @@ -802,7 +802,7 @@ function printPathNoParens(path, options, print, args) { return concat([ "...", path.call(print, "argument"), - printTypeAnnotation(path, options, print) + printTypeAnnotation(path, options, print), ]); case "FunctionDeclaration": case "FunctionExpression": @@ -830,7 +830,7 @@ function printPathNoParens(path, options, print, args) { (args.expandLastArg || args.expandFirstArg), /* printTypeParams */ true ), - printReturnType(path, print, options) + printReturnType(path, print, options), ]) ) ); @@ -840,7 +840,7 @@ function printPathNoParens(path, options, print, args) { path, options, /* sameIndent */ true, - comment => { + (comment) => { const nextCharacter = getNextNonSpaceNonCommentCharacterIndex( options.originalText, comment, @@ -858,7 +858,7 @@ function printPathNoParens(path, options, print, args) { parts.push(" =>"); - const body = path.call(bodyPath => print(bodyPath, args), "body"); + const body = path.call((bodyPath) => print(bodyPath, args), "body"); // We want to always keep these types of nodes on the same line // as the arrow. @@ -883,7 +883,7 @@ function printPathNoParens(path, options, print, args) { concat(parts), group( concat([" (", indent(concat([softline, body])), softline, ")"]) - ) + ), ]) ); } @@ -917,14 +917,14 @@ function printPathNoParens(path, options, print, args) { line, shouldAddParens ? ifBreak("", "(") : "", body, - shouldAddParens ? ifBreak("", ")") : "" + shouldAddParens ? ifBreak("", ")") : "", ]) ), shouldAddSoftLine ? concat([ifBreak(printTrailingComma ? "," : ""), softline]) - : "" + : "", ]) - ) + ), ]) ); } @@ -1017,7 +1017,7 @@ function printPathNoParens(path, options, print, args) { const standalones = []; const grouped = []; if (n.specifiers && n.specifiers.length > 0) { - path.each(specifierPath => { + path.each((specifierPath) => { const value = specifierPath.getValue(); if ( value.type === "ImportDefaultSpecifier" || @@ -1041,7 +1041,7 @@ function printPathNoParens(path, options, print, args) { grouped.length === 1 && standalones.length === 0 && n.specifiers && - !n.specifiers.some(node => node.comments) + !n.specifiers.some((node) => node.comments) ) { parts.push( concat([ @@ -1049,7 +1049,7 @@ function printPathNoParens(path, options, print, args) { options.bracketSpacing ? " " : "", concat(grouped), options.bracketSpacing ? " " : "", - "}" + "}", ]) ); } else if (grouped.length >= 1) { @@ -1060,12 +1060,12 @@ function printPathNoParens(path, options, print, args) { indent( concat([ options.bracketSpacing ? line : softline, - join(concat([",", line]), grouped) + join(concat([",", line]), grouped), ]) ), ifBreak(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line : softline, - "}" + "}", ]) ) ); @@ -1094,11 +1094,11 @@ function printPathNoParens(path, options, print, args) { return "import"; case "TSModuleBlock": case "BlockStatement": { - const naked = path.call(bodyPath => { + const naked = path.call((bodyPath) => { return printStatementSequence(bodyPath, options, print); }, "body"); - const hasContent = n.body.find(node => node.type !== "EmptyStatement"); + const hasContent = n.body.find((node) => node.type !== "EmptyStatement"); const hasDirectives = n.directives && n.directives.length > 0; const parent = path.getParentNode(); @@ -1127,7 +1127,7 @@ function printPathNoParens(path, options, print, args) { // Babel 6 if (hasDirectives) { - path.each(childPath => { + path.each((childPath) => { parts.push(indent(concat([hardline, print(childPath), semi]))); if ( isNextLineEmpty( @@ -1153,7 +1153,7 @@ function printPathNoParens(path, options, print, args) { case "ReturnStatement": return concat([ "return", - printReturnAndThrowArgument(path, options, print) + printReturnAndThrowArgument(path, options, print), ]); case "NewExpression": case "OptionalCallExpression": @@ -1184,7 +1184,7 @@ function printPathNoParens(path, options, print, args) { path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), - concat(["(", join(", ", path.map(print, "arguments")), ")"]) + concat(["(", join(", ", path.map(print, "arguments")), ")"]), ]); } @@ -1206,7 +1206,7 @@ function printPathNoParens(path, options, print, args) { if ( !isNew && isMemberish(n.callee) && - !path.call(path => pathNeedsParens(path, options), "callee") + !path.call((path) => pathNeedsParens(path, options), "callee") ) { return printMemberChain(path, options, print); } @@ -1219,7 +1219,7 @@ function printPathNoParens(path, options, print, args) { ? `/*:: ${n.callee.trailingComments[0].value.slice(2).trim()} */` : "", printFunctionTypeParameters(path, options, print), - printArgumentsList(path, options, print) + printArgumentsList(path, options, print), ]); // We group here when the callee is itself a call expression. @@ -1254,7 +1254,7 @@ function printPathNoParens(path, options, print, args) { (n.extends.length === 1 ? identity : indent)( join(concat([",", line]), path.map(print, "extends")) ), - " " + " ", ]) ) ) @@ -1273,7 +1273,7 @@ function printPathNoParens(path, options, print, args) { "]]", printOptionalToken(path), n.method ? "" : ": ", - path.call(print, "value") + path.call(print, "value"), ]); case "ObjectExpression": @@ -1299,7 +1299,7 @@ function printPathNoParens(path, options, print, args) { fields.push(propertiesField); const firstProperty = fields - .map(field => n[field][0]) + .map((field) => n[field][0]) .sort((a, b) => options.locStart(a) - options.locStart(b))[0]; const parent = path.getParentNode(0); @@ -1323,7 +1323,7 @@ function printPathNoParens(path, options, print, args) { parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && n.properties.some( - property => + (property) => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern") @@ -1348,13 +1348,13 @@ function printPathNoParens(path, options, print, args) { // interleaved in the source code. So we need to reorder them before // printing them. const propsAndLoc = []; - fields.forEach(field => { - path.each(childPath => { + fields.forEach((field) => { + path.each((childPath) => { const node = childPath.getValue(); propsAndLoc.push({ node, printed: print(childPath), - loc: options.locStart(node) + loc: options.locStart(node), }); }, field); }); @@ -1362,7 +1362,7 @@ function printPathNoParens(path, options, print, args) { let separatorParts = []; const props = propsAndLoc .sort((a, b) => a.loc - b.loc) - .map(prop => { + .map((prop) => { const result = concat(separatorParts.concat(group(prop.printed))); separatorParts = [separator, line]; if ( @@ -1401,7 +1401,7 @@ function printPathNoParens(path, options, print, args) { return concat([ leftBrace, rightBrace, - printTypeAnnotation(path, options, print) + printTypeAnnotation(path, options, print), ]); } @@ -1412,7 +1412,7 @@ function printPathNoParens(path, options, print, args) { softline, rightBrace, printOptionalToken(path), - printTypeAnnotation(path, options, print) + printTypeAnnotation(path, options, print), ]) ); } else { @@ -1429,7 +1429,7 @@ function printPathNoParens(path, options, print, args) { ), concat([options.bracketSpacing ? line : softline, rightBrace]), printOptionalToken(path), - printTypeAnnotation(path, options, print) + printTypeAnnotation(path, options, print), ]); } @@ -1438,7 +1438,7 @@ function printPathNoParens(path, options, print, args) { // type if ( path.match( - node => node.type === "ObjectPattern" && !node.decorators, + (node) => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && @@ -1509,7 +1509,7 @@ function printPathNoParens(path, options, print, args) { return concat([ "@", path.call(print, "expression"), - path.call(print, "callee") + path.call(print, "callee"), ]); case "ArrayExpression": case "ArrayPattern": @@ -1523,7 +1523,7 @@ function printPathNoParens(path, options, print, args) { "[", comments.printDanglingComments(path, options), softline, - "]" + "]", ]) ) ); @@ -1576,7 +1576,7 @@ function printPathNoParens(path, options, print, args) { indent( concat([ softline, - printArrayItems(path, options, "elements", print) + printArrayItems(path, options, "elements", print), ]) ), needsForcedTrailingComma ? "," : "", @@ -1593,7 +1593,7 @@ function printPathNoParens(path, options, print, args) { /* sameIndent */ true ), softline, - "]" + "]", ]), { shouldBreak } ) @@ -1616,7 +1616,7 @@ function printPathNoParens(path, options, print, args) { // the few places a SequenceExpression appears unparenthesized, we want // to indent expressions after the first. const parts = []; - path.each(p => { + path.each((p) => { if (p.getName() === 0) { parts.push(print(p)); } else { @@ -1684,7 +1684,7 @@ function printPathNoParens(path, options, print, args) { "(", indent(concat([softline, path.call(print, "argument")])), softline, - ")" + ")", ]) ) ); @@ -1704,15 +1704,15 @@ function printPathNoParens(path, options, print, args) { case "ConditionalExpression": return printTernaryOperator(path, options, print, { beforeParts: () => [path.call(print, "test")], - afterParts: breakClosingParen => [breakClosingParen ? softline : ""], + afterParts: (breakClosingParen) => [breakClosingParen ? softline : ""], shouldCheckJsx: true, conditionalNodeType: "ConditionalExpression", consequentNodePropertyName: "consequent", alternateNodePropertyName: "alternate", - testNodePropertyNames: ["test"] + testNodePropertyNames: ["test"], }); case "VariableDeclaration": { - const printed = path.map(childPath => { + const printed = path.map((childPath) => { return print(childPath); }, "declarations"); @@ -1726,7 +1726,7 @@ function printPathNoParens(path, options, print, args) { parentNode.type === "ForOfStatement" || parentNode.type === "ForAwaitStatement"; - const hasValue = n.declarations.some(decl => decl.init); + const hasValue = n.declarations.some((decl) => decl.init); let firstVariable; if (printed.length === 1 && !n.declarations[0].comments) { @@ -1744,11 +1744,11 @@ function printPathNoParens(path, options, print, args) { concat( printed .slice(1) - .map(p => + .map((p) => concat([",", hasValue && !isParentForLoop ? hardline : line, p]) ) ) - ) + ), ]; if (!(isParentForLoop && parentNode.body !== n)) { @@ -1795,7 +1795,7 @@ function printPathNoParens(path, options, print, args) { "with (", path.call(print, "object"), ")", - adjustClause(n.body, path.call(print, "body")) + adjustClause(n.body, path.call(print, "body")), ]) ); case "IfStatement": { @@ -1806,11 +1806,11 @@ function printPathNoParens(path, options, print, args) { group( concat([ indent(concat([softline, path.call(print, "test")])), - softline + softline, ]) ), ")", - con + con, ]) ); @@ -1820,7 +1820,7 @@ function printPathNoParens(path, options, print, args) { const commentOnOwnLine = (hasTrailingComment(n.consequent) && n.consequent.comments.some( - comment => + (comment) => comment.trailing && !handleComments.isBlockComment(comment) )) || needsHardlineAfterDanglingComment(n); @@ -1882,16 +1882,16 @@ function printPathNoParens(path, options, print, args) { path.call(print, "test"), ";", line, - path.call(print, "update") + path.call(print, "update"), ]) ), - softline + softline, ]) ), ")", - body + body, ]) - ) + ), ]); } case "WhileStatement": @@ -1901,11 +1901,11 @@ function printPathNoParens(path, options, print, args) { group( concat([ indent(concat([softline, path.call(print, "test")])), - softline + softline, ]) ), ")", - adjustClause(n.body, path.call(print, "body")) + adjustClause(n.body, path.call(print, "body")), ]) ); case "ForInStatement": @@ -1917,7 +1917,7 @@ function printPathNoParens(path, options, print, args) { " in ", path.call(print, "right"), ")", - adjustClause(n.body, path.call(print, "body")) + adjustClause(n.body, path.call(print, "body")), ]) ); @@ -1937,7 +1937,7 @@ function printPathNoParens(path, options, print, args) { " of ", path.call(print, "right"), ")", - adjustClause(n.body, path.call(print, "body")) + adjustClause(n.body, path.call(print, "body")), ]) ); } @@ -1958,7 +1958,7 @@ function printPathNoParens(path, options, print, args) { group( concat([ indent(concat([softline, path.call(print, "test")])), - softline + softline, ]) ), ")", @@ -1997,27 +1997,27 @@ function printPathNoParens(path, options, print, args) { return concat([ path.call(print, "label"), ": ", - path.call(print, "body") + path.call(print, "body"), ]); case "TryStatement": return concat([ "try ", path.call(print, "block"), n.handler ? concat([" ", path.call(print, "handler")]) : "", - n.finalizer ? concat([" finally ", path.call(print, "finalizer")]) : "" + n.finalizer ? concat([" finally ", path.call(print, "finalizer")]) : "", ]); case "CatchClause": if (n.param) { const hasComments = n.param.comments && n.param.comments.some( - comment => + (comment) => !handleComments.isBlockComment(comment) || (comment.leading && hasNewline(options.originalText, options.locEnd(comment))) || (comment.trailing && hasNewline(options.originalText, options.locStart(comment), { - backwards: true + backwards: true, })) ); const param = path.call(print, "param"); @@ -2027,7 +2027,7 @@ function printPathNoParens(path, options, print, args) { hasComments ? concat(["(", indent(concat([softline, param])), softline, ") "]) : concat(["(", param, ") "]), - path.call(print, "body") + path.call(print, "body"), ]); } @@ -2035,7 +2035,7 @@ function printPathNoParens(path, options, print, args) { case "ThrowStatement": return concat([ "throw", - printReturnAndThrowArgument(path, options, print) + printReturnAndThrowArgument(path, options, print), ]); // Note: ignoring n.lexical because it has no printing consequences. case "SwitchStatement": @@ -2045,7 +2045,7 @@ function printPathNoParens(path, options, print, args) { "switch (", indent(concat([softline, path.call(print, "discriminant")])), softline, - ")" + ")", ]) ), " {", @@ -2055,7 +2055,7 @@ function printPathNoParens(path, options, print, args) { hardline, join( hardline, - path.map(casePath => { + path.map((casePath) => { const caseNode = casePath.getValue(); return concat([ casePath.call(print), @@ -2066,15 +2066,15 @@ function printPathNoParens(path, options, print, args) { options.locEnd ) ? hardline - : "" + : "", ]); }, "cases") - ) + ), ]) ) : "", hardline, - "}" + "}", ]); case "SwitchCase": { if (n.test) { @@ -2084,11 +2084,11 @@ function printPathNoParens(path, options, print, args) { } const consequent = n.consequent.filter( - node => node.type !== "EmptyStatement" + (node) => node.type !== "EmptyStatement" ); if (consequent.length > 0) { - const cons = path.call(consequentPath => { + const cons = path.call((consequentPath) => { return printStatementSequence(consequentPath, options, print); }, "consequent"); @@ -2132,12 +2132,12 @@ function printPathNoParens(path, options, print, args) { case "JSXNamespacedName": return join(":", [ path.call(print, "namespace"), - path.call(print, "name") + path.call(print, "name"), ]); case "JSXMemberExpression": return join(".", [ path.call(print, "object"), - path.call(print, "property") + path.call(print, "property"), ]); case "TSQualifiedName": return join(".", [path.call(print, "left"), path.call(print, "right")]); @@ -2146,7 +2146,7 @@ function printPathNoParens(path, options, print, args) { return concat([ "{", path.call( - p => { + (p) => { const printed = concat(["...", print(p)]); const n = p.getValue(); if (!n.comments || !n.comments.length) { @@ -2156,15 +2156,15 @@ function printPathNoParens(path, options, print, args) { indent( concat([ softline, - comments.printComments(p, () => printed, options) + comments.printComments(p, () => printed, options), ]) ), - softline + softline, ]); }, n.type === "JSXSpreadAttribute" ? "argument" : "expression" ), - "}" + "}", ]); } case "JSXExpressionContainer": { @@ -2203,7 +2203,7 @@ function printPathNoParens(path, options, print, args) { indent(concat([softline, path.call(print, "expression")])), softline, lineSuffixBoundary, - "}" + "}", ]) ); } @@ -2231,7 +2231,7 @@ function printPathNoParens(path, options, print, args) { "<", path.call(print, "name"), path.call(print, "typeParameters"), - " />" + " />", ]); } @@ -2261,7 +2261,7 @@ function printPathNoParens(path, options, print, args) { path.call(print, "typeParameters"), " ", concat(path.map(print, "attributes")), - n.selfClosing ? " />" : ">" + n.selfClosing ? " />" : ">", ]) ); } @@ -2289,7 +2289,7 @@ function printPathNoParens(path, options, print, args) { const shouldBreak = n.attributes && n.attributes.some( - attr => + (attr) => attr.value && isStringLiteral(attr.value) && attr.value.value.includes("\n") @@ -2303,12 +2303,12 @@ function printPathNoParens(path, options, print, args) { concat([ indent( concat( - path.map(attr => concat([line, print(attr)]), "attributes") + path.map((attr) => concat([line, print(attr)]), "attributes") ) ), - n.selfClosing ? line : bracketSameLine ? ">" : softline + n.selfClosing ? line : bracketSameLine ? ">" : softline, ]), - n.selfClosing ? "/>" : bracketSameLine ? "" : ">" + n.selfClosing ? "/>" : bracketSameLine ? "" : ">", ]), { shouldBreak } ); @@ -2330,11 +2330,11 @@ function printPathNoParens(path, options, print, args) { : hasComment && !isOpeningFragment ? " " : "", - comments.printDanglingComments(path, options, true) + comments.printDanglingComments(path, options, true), ]) ), hasOwnLineComment ? hardline : "", - ">" + ">", ]); } case "JSXText": @@ -2350,7 +2350,7 @@ function printPathNoParens(path, options, print, args) { options, /* sameIndent */ !requiresHardline ), - requiresHardline ? hardline : "" + requiresHardline ? hardline : "", ]); } case "ClassBody": @@ -2364,14 +2364,14 @@ function printPathNoParens(path, options, print, args) { ? indent( concat([ hardline, - path.call(bodyPath => { + path.call((bodyPath) => { return printStatementSequence(bodyPath, options, print); - }, "body") + }, "body"), ]) ) : comments.printDanglingComments(path, options), hardline, - "}" + "}", ]); case "ClassProperty": case "TSAbstractClassProperty": @@ -2451,7 +2451,7 @@ function printPathNoParens(path, options, print, args) { const isSimple = isSimpleTemplateLiteral(n); if (isSimple) { expressions = expressions.map( - doc => + (doc) => printDocToString(doc, { ...options, printWidth: Infinity }) .formatted ); @@ -2459,7 +2459,7 @@ function printPathNoParens(path, options, print, args) { parts.push(lineSuffixBoundary, "`"); - path.each(childPath => { + path.each((childPath) => { const i = childPath.getName(); parts.push(print(childPath)); @@ -2518,7 +2518,7 @@ function printPathNoParens(path, options, print, args) { return concat([ path.call(print, "tag"), path.call(print, "typeParameters"), - path.call(print, "quasi") + path.call(print, "quasi"), ]); case "Node": case "Printable": @@ -2558,13 +2558,13 @@ function printPathNoParens(path, options, print, args) { indent( concat([ softline, - printArrayItems(path, options, typesField, print) + printArrayItems(path, options, typesField, print), ]) ), ifBreak(shouldPrintComma(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options, /* sameIndent */ true), softline, - "]" + "]", ]) ); } @@ -2591,7 +2591,7 @@ function printPathNoParens(path, options, print, args) { return concat([ n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), - semi + semi, ]); case "DeclareFunction": return printFlowDeclaration(path, [ @@ -2599,21 +2599,21 @@ function printPathNoParens(path, options, print, args) { path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), - semi + semi, ]); case "DeclareModule": return printFlowDeclaration(path, [ "module ", path.call(print, "id"), " ", - path.call(print, "body") + path.call(print, "body"), ]); case "DeclareModuleExports": return printFlowDeclaration(path, [ "module.exports", ": ", path.call(print, "typeAnnotation"), - semi + semi, ]); case "DeclareVariable": return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]); @@ -2651,7 +2651,7 @@ function printPathNoParens(path, options, print, args) { "enum ", path.call(print, "id"), " ", - path.call(print, "body") + path.call(print, "body"), ]); case "EnumBooleanBody": case "EnumNumberBody": @@ -2682,7 +2682,7 @@ function printPathNoParens(path, options, print, args) { "{", comments.printDanglingComments(path, options), softline, - "}" + "}", ]) ) ); @@ -2695,7 +2695,7 @@ function printPathNoParens(path, options, print, args) { concat([ hardline, printArrayItems(path, options, "members", print), - shouldPrintComma(options) ? "," : "" + shouldPrintComma(options) ? "," : "", ]) ), comments.printDanglingComments( @@ -2704,7 +2704,7 @@ function printPathNoParens(path, options, print, args) { /* sameIndent */ true ), hardline, - "}" + "}", ]) ) ); @@ -2717,7 +2717,7 @@ function printPathNoParens(path, options, print, args) { return concat([ path.call(print, "id"), " = ", - typeof n.init === "object" ? path.call(print, "init") : String(n.init) + typeof n.init === "object" ? path.call(print, "init") : String(n.init), ]); case "EnumDefaultedMember": return path.call(print, "id"); @@ -2801,12 +2801,12 @@ function printPathNoParens(path, options, print, args) { path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", - path.call(print, "typeAnnotation") + path.call(print, "typeAnnotation"), ]); case "GenericTypeAnnotation": return concat([ path.call(print, "id"), - path.call(print, "typeParameters") + path.call(print, "typeParameters"), ]); case "DeclareInterface": @@ -2835,7 +2835,7 @@ function printPathNoParens(path, options, print, args) { "extends ", (n.extends.length === 1 ? identity : indent)( join(concat([",", line]), path.map(print, "extends")) - ) + ), ]) ) ) @@ -2850,12 +2850,12 @@ function printPathNoParens(path, options, print, args) { case "InterfaceExtends": return concat([ path.call(print, "id"), - path.call(print, "typeParameters") + path.call(print, "typeParameters"), ]); case "TSClassImplements": return concat([ path.call(print, "expression"), - path.call(print, "typeParameters") + path.call(print, "typeParameters"), ]); case "TSIntersectionType": case "IntersectionTypeAnnotation": { @@ -2922,7 +2922,7 @@ function printPathNoParens(path, options, print, args) { // | child1 // // comment // | child2 - const printed = path.map(typePath => { + const printed = path.map((typePath) => { let printedType = typePath.call(print); if (!shouldHug) { printedType = align(2, printedType); @@ -2940,7 +2940,7 @@ function printPathNoParens(path, options, print, args) { const code = concat([ ifBreak(concat([shouldAddStartLine ? line : "", "| "])), - join(concat([line, "| "]), printed) + join(concat([line, "| "]), printed), ]); if (pathNeedsParens(path, options)) { @@ -2955,7 +2955,7 @@ function printPathNoParens(path, options, print, args) { concat([ indent(concat([ifBreak(concat(["(", softline])), code])), softline, - ifBreak(")") + ifBreak(")"), ]) ); } @@ -2990,7 +2990,7 @@ function printPathNoParens(path, options, print, args) { n.id ? ": " : "", path.call(print, "key"), "]: ", - path.call(print, "value") + path.call(print, "value"), ]); } case "ObjectTypeProperty": { @@ -3011,14 +3011,14 @@ function printPathNoParens(path, options, print, args) { printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation(n, options) ? "" : ": ", - path.call(print, "value") + path.call(print, "value"), ]); } case "QualifiedTypeIdentifier": return concat([ path.call(print, "qualification"), ".", - path.call(print, "id") + path.call(print, "id"), ]); case "StringLiteralTypeAnnotation": return nodeStr(n, options); @@ -3061,7 +3061,7 @@ function printPathNoParens(path, options, print, args) { "(", path.call(print, "expression"), printTypeAnnotation(path, options, print), - ")" + ")", ]); } @@ -3080,7 +3080,7 @@ function printPathNoParens(path, options, print, args) { return concat([ "/*:: ", printTypeParameters(path, options, print, "params"), - " */" + " */", ]); } @@ -3197,7 +3197,7 @@ function printPathNoParens(path, options, print, args) { return concat([ path.call(print, "expression"), " as ", - path.call(print, "typeAnnotation") + path.call(print, "typeAnnotation"), ]); case "TSArrayType": return concat([path.call(print, "elementType"), "[]"]); @@ -3252,7 +3252,7 @@ function printPathNoParens(path, options, print, args) { case "TSTypeReference": return concat([ path.call(print, "typeName"), - printTypeParameters(path, options, print, "typeParameters") + printTypeParameters(path, options, print, "typeParameters"), ]); case "TSTypeQuery": return concat(["typeof ", path.call(print, "exprName")]); @@ -3264,11 +3264,11 @@ function printPathNoParens(path, options, print, args) { indent( concat([ softline, - join(concat([", ", softline]), path.map(print, "parameters")) + join(concat([", ", softline]), path.map(print, "parameters")), ]) ), ifBreak(shouldPrintComma(options) ? "," : ""), - softline + softline, ]) ); @@ -3281,7 +3281,7 @@ function printPathNoParens(path, options, print, args) { n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", - parent.type === "ClassBody" ? semi : "" + parent.type === "ClassBody" ? semi : "", ]); } case "TSTypePredicate": @@ -3290,7 +3290,7 @@ function printPathNoParens(path, options, print, args) { path.call(print, "parameterName"), n.typeAnnotation ? concat([" is ", path.call(print, "typeAnnotation")]) - : "" + : "", ]); case "TSNonNullExpression": return concat([path.call(print, "expression"), "!"]); @@ -3303,7 +3303,7 @@ function printPathNoParens(path, options, print, args) { path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat([".", path.call(print, "qualifier")]), - printTypeParameters(path, options, print, "typeParameters") + printTypeParameters(path, options, print, "typeParameters"), ]); case "TSLiteralType": return path.call(print, "literal"); @@ -3312,7 +3312,7 @@ function printPathNoParens(path, options, print, args) { path.call(print, "objectType"), "[", path.call(print, "indexType"), - "]" + "]", ]); case "TSConstructSignatureDeclaration": case "TSCallSignatureDeclaration": @@ -3360,7 +3360,7 @@ function printPathNoParens(path, options, print, args) { n.readonly ? concat([ getTypeScriptMappedTypeModifier(n.readonly, "readonly"), - " " + " ", ]) : "", printTypeScriptModifiers(path, options, print), @@ -3370,12 +3370,12 @@ function printPathNoParens(path, options, print, args) { : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), - ifBreak(semi, "") + ifBreak(semi, ""), ]) ), comments.printDanglingComments(path, options, /* sameIndent */ true), options.bracketSpacing ? line : softline, - "}" + "}", ]), { shouldBreak } ); @@ -3436,7 +3436,7 @@ function printPathNoParens(path, options, print, args) { "{", comments.printDanglingComments(path, options), softline, - "}" + "}", ]) ) ); @@ -3449,7 +3449,7 @@ function printPathNoParens(path, options, print, args) { concat([ hardline, printArrayItems(path, options, "members", print), - shouldPrintComma(options, "es5") ? "," : "" + shouldPrintComma(options, "es5") ? "," : "", ]) ), comments.printDanglingComments( @@ -3458,7 +3458,7 @@ function printPathNoParens(path, options, print, args) { /* sameIndent */ true ), hardline, - "}" + "}", ]) ) ); @@ -3552,14 +3552,14 @@ function printPathNoParens(path, options, print, args) { " ", "extends", " ", - path.call(print, "extendsType") + path.call(print, "extendsType"), ], afterParts: () => [], shouldCheckJsx: false, conditionalNodeType: "TSConditionalType", consequentNodePropertyName: "trueType", alternateNodePropertyName: "falseType", - testNodePropertyNames: ["checkType", "extendsType"] + testNodePropertyNames: ["checkType", "extendsType"], }); case "TSInferType": @@ -3588,7 +3588,7 @@ function printPathNoParens(path, options, print, args) { join( concat([";", line]), path.map( - childPath => + (childPath) => hasNgSideEffect(childPath) ? print(childPath) : concat(["(", print(childPath), ")"]), @@ -3610,7 +3610,7 @@ function printPathNoParens(path, options, print, args) { : isNgForOf(childPath.getValue(), index, n) ? " " : concat([";", line]), - print(childPath) + print(childPath), ]), "body" ) @@ -3622,7 +3622,7 @@ function printPathNoParens(path, options, print, args) { case "NGMicrosyntaxExpression": return concat([ path.call(print, "expression"), - n.alias === null ? "" : concat([" as ", path.call(print, "alias")]) + n.alias === null ? "" : concat([" as ", path.call(print, "alias")]), ]); case "NGMicrosyntaxKeyedExpression": { const index = path.getName(); @@ -3639,20 +3639,20 @@ function printPathNoParens(path, options, print, args) { return concat([ path.call(print, "key"), shouldNotPrintColon ? " " : ": ", - path.call(print, "expression") + path.call(print, "expression"), ]); } case "NGMicrosyntaxLet": return concat([ "let ", path.call(print, "key"), - n.value === null ? "" : concat([" = ", path.call(print, "value")]) + n.value === null ? "" : concat([" = ", path.call(print, "value")]), ]); case "NGMicrosyntaxAs": return concat([ path.call(print, "key"), " as ", - path.call(print, "alias") + path.call(print, "alias"), ]); case "ArgumentPlaceholder": @@ -3672,7 +3672,7 @@ function printPathNoParens(path, options, print, args) { "function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error). "): ", - path.call(print, "typeAnnotation") + path.call(print, "typeAnnotation"), ]); default: @@ -3715,7 +3715,7 @@ function printStatementSequence(path, options, print) { !isTheOnlyJSXElementInMarkdown(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options) ) { - if (stmt.comments && stmt.comments.some(comment => comment.leading)) { + if (stmt.comments && stmt.comments.some((comment) => comment.leading)) { parts.push(print(stmtPath, { needsSemi: true })); } else { parts.push(";", stmtPrinted); @@ -3772,7 +3772,7 @@ function printPropertyKey(path, options, print) { parent.body || parent.members ).some( - prop => + (prop) => !prop.computed && prop.key && isStringLiteral(prop.key) && @@ -3789,7 +3789,7 @@ function printPropertyKey(path, options, print) { // a -> "a" const prop = printString(JSON.stringify(key.name), options); return path.call( - keyPath => comments.printComments(keyPath, () => prop, options), + (keyPath) => comments.printComments(keyPath, () => prop, options), "key" ); } @@ -3801,7 +3801,7 @@ function printPropertyKey(path, options, print) { ) { // 'a' -> a return path.call( - keyPath => comments.printComments(keyPath, () => key.value, options), + (keyPath) => comments.printComments(keyPath, () => key.value, options), "key" ); } @@ -3833,7 +3833,7 @@ function printMethod(path, options, print) { node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) - : path.call(path => printMethodInternal(path, options, print), "value") + : path.call((path) => printMethodInternal(path, options, print), "value") ); return concat(parts); @@ -3845,9 +3845,9 @@ function printMethodInternal(path, options, print) { group( concat([ printFunctionParams(path, print, options), - printReturnType(path, print, options) + printReturnType(path, print, options), ]) - ) + ), ]; if (path.getNode().body) { @@ -3935,16 +3935,16 @@ function printJestEachTemplateLiteral(node, expressions, options) { const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/); if ( headerNames.length > 1 || - headerNames.some(headerName => headerName.length !== 0) + headerNames.some((headerName) => headerName.length !== 0) ) { const parts = []; const stringifiedExpressions = expressions.map( - doc => + (doc) => "${" + printDocToString(doc, { ...options, printWidth: Infinity, - endOfLine: "lf" + endOfLine: "lf", }).formatted + "}" ); @@ -3966,15 +3966,15 @@ function printJestEachTemplateLiteral(node, expressions, options) { const maxColumnCount = Math.max( headerNames.length, - ...tableBody.map(row => row.cells.length) + ...tableBody.map((row) => row.cells.length) ); const maxColumnWidths = Array.from({ length: maxColumnCount }).fill(0); const table = [ { cells: headerNames }, - ...tableBody.filter(row => row.cells.length !== 0) + ...tableBody.filter((row) => row.cells.length !== 0), ]; - for (const { cells } of table.filter(row => !row.hasLineBreak)) { + for (const { cells } of table.filter((row) => !row.hasLineBreak)) { cells.forEach((cell, index) => { maxColumnWidths[index] = Math.max( maxColumnWidths[index], @@ -3991,7 +3991,7 @@ function printJestEachTemplateLiteral(node, expressions, options) { hardline, join( hardline, - table.map(row => + table.map((row) => join( " | ", row.cells.map((cell, index) => @@ -4002,7 +4002,7 @@ function printJestEachTemplateLiteral(node, expressions, options) { ) ) ) - ) + ), ]) ), hardline, @@ -4020,7 +4020,7 @@ function printArgumentsList(path, options, print) { return concat([ "(", comments.printDanglingComments(path, options, /* sameIndent */ true), - ")" + ")", ]); } @@ -4031,14 +4031,14 @@ function printArgumentsList(path, options, print) { args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && - !args.find(arg => arg.comments) + !args.find((arg) => arg.comments) ) { return concat([ "(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), - ")" + ")", ]); } @@ -4062,7 +4062,7 @@ function printArgumentsList(path, options, print) { } let shouldBreak = false; - argPath.each(paramPath => { + argPath.each((paramPath) => { const printed = concat([print(paramPath)]); shouldBreak = shouldBreak || willBreak(printed); }, "params"); @@ -4113,7 +4113,7 @@ function printArgumentsList(path, options, print) { indent(concat([line, concat(printedArguments)])), maybeTrailingComma, line, - ")" + ")", ]), { shouldBreak: true } ); @@ -4139,21 +4139,21 @@ function printArgumentsList(path, options, print) { // We want to print the last argument with a special flag let printedExpanded; let i = 0; - path.each(argPath => { + path.each((argPath) => { if (shouldGroupFirst && i === 0) { printedExpanded = [ concat([ - argPath.call(p => print(p, { expandFirstArg: true })), + argPath.call((p) => print(p, { expandFirstArg: true })), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline : line, - hasEmptyLineFollowingFirstArg ? hardline : "" - ]) + hasEmptyLineFollowingFirstArg ? hardline : "", + ]), ].concat(printedArguments.slice(1)); } if (shouldGroupLast && i === args.length - 1) { printedExpanded = printedArguments .slice(0, -1) - .concat(argPath.call(p => print(p, { expandLastArg: true }))); + .concat(argPath.call((p) => print(p, { expandLastArg: true }))); } i++; }, "arguments"); @@ -4176,20 +4176,20 @@ function printArgumentsList(path, options, print) { "(", group(printedExpanded[0], { shouldBreak: true }), concat(printedExpanded.slice(1)), - ")" + ")", ]) : concat([ "(", concat(printedArguments.slice(0, -1)), group(getLast(printedExpanded), { - shouldBreak: true + shouldBreak: true, }), - ")" + ")", ]), - allArgsBrokenOut() + allArgsBrokenOut(), ], { shouldBreak } - ) + ), ]); } @@ -4198,7 +4198,7 @@ function printArgumentsList(path, options, print) { indent(concat([softline, concat(printedArguments)])), ifBreak(maybeTrailingComma), softline, - ")" + ")", ]); if (isLongCurriedCallExpression(path)) { // By not wrapping the arguments in a group, the printer prioritizes @@ -4207,7 +4207,7 @@ function printArgumentsList(path, options, print) { } return group(contents, { - shouldBreak: printedArguments.some(willBreak) || anyArgEmptyLine + shouldBreak: printedArguments.some(willBreak) || anyArgEmptyLine, }); } @@ -4235,7 +4235,7 @@ function printTypeAnnotation(path, options, print) { return concat([ isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", - path.call(print, "typeAnnotation") + path.call(print, "typeAnnotation"), ]); } @@ -4257,7 +4257,8 @@ function printFunctionParams(path, print, options, expandArg, printTypeParams) { const isParametersInTestCall = isTestCall(parent); const shouldHugParameters = shouldHugArguments(fun); const shouldExpandParameters = - expandArg && !(fun[paramsField] && fun[paramsField].some(n => n.comments)); + expandArg && + !(fun[paramsField] && fun[paramsField].some((n) => n.comments)); const typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) @@ -4305,14 +4306,14 @@ function printFunctionParams(path, print, options, expandArg, printTypeParams) { path, options, /* sameIndent */ true, - comment => + (comment) => getNextNonSpaceNonCommentCharacter( options.originalText, comment, options.locEnd ) === ")" ), - ")" + ")", ]); } @@ -4334,7 +4335,7 @@ function printFunctionParams(path, print, options, expandArg, printTypeParams) { removeLines(typeParams), "(", concat(printed.map(removeLines)), - ")" + ")", ]) ); } @@ -4347,7 +4348,7 @@ function printFunctionParams(path, print, options, expandArg, printTypeParams) { // c // }) {} const hasNotParameterDecorator = fun[paramsField].every( - param => !param.decorators + (param) => !param.decorators ); if (shouldHugParameters && hasNotParameterDecorator) { return concat([typeParams, "(", concat(printed), ")"]); @@ -4392,7 +4393,7 @@ function printFunctionParams(path, print, options, expandArg, printTypeParams) { canHaveTrailingComma && shouldPrintComma(options, "all") ? "," : "" ), softline, - ")" + ")", ]); } @@ -4448,7 +4449,7 @@ function printFunctionDeclaration(path, print, options) { group( concat([ printFunctionParams(path, print, options), - printReturnType(path, print, options) + printReturnType(path, print, options), ]) ), n.body ? " " : "", @@ -4523,7 +4524,7 @@ function printExportDeclaration(path, options, print) { const specifiers = []; const defaultSpecifiers = []; const namespaceSpecifiers = []; - path.each(specifierPath => { + path.each((specifierPath) => { const specifierType = path.getValue().type; if (specifierType === "ExportSpecifier") { specifiers.push(print(specifierPath)); @@ -4544,7 +4545,7 @@ function printExportDeclaration(path, options, print) { const canBreak = specifiers.length > 1 || defaultSpecifiers.length > 0 || - (decl.specifiers && decl.specifiers.some(node => node.comments)); + (decl.specifiers && decl.specifiers.some((node) => node.comments)); let printed = ""; if (specifiers.length !== 0) { @@ -4555,12 +4556,12 @@ function printExportDeclaration(path, options, print) { indent( concat([ options.bracketSpacing ? line : softline, - join(concat([",", line]), specifiers) + join(concat([",", line]), specifiers), ]) ), ifBreak(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line : softline, - "}" + "}", ]) ); } else { @@ -4569,7 +4570,7 @@ function printExportDeclaration(path, options, print) { options.bracketSpacing ? " " : "", concat(specifiers), options.bracketSpacing ? " " : "", - "}" + "}", ]); } } @@ -4685,7 +4686,7 @@ function printTypeParameters(path, options, print, paramsKey) { "<", join(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(n), - ">" + ">", ]); } @@ -4695,7 +4696,7 @@ function printTypeParameters(path, options, print, paramsKey) { indent( concat([ softline, - join(concat([",", line]), path.map(print, paramsKey)) + join(concat([",", line]), path.map(print, paramsKey)), ]) ), ifBreak( @@ -4706,7 +4707,7 @@ function printTypeParameters(path, options, print, paramsKey) { : "" ), softline, - ">" + ">", ]) ); } @@ -4732,7 +4733,7 @@ function printClass(path, options, print) { const printed = concat([ "extends ", path.call(print, "superClass"), - path.call(print, "superTypeParameters") + path.call(print, "superTypeParameters"), ]); // Keep old behaviour of extends in same line // If there is only on extends and there are not comments @@ -4744,10 +4745,10 @@ function printClass(path, options, print) { concat([ " ", path.call( - superClass => + (superClass) => comments.printComments(superClass, () => printed, options), "superClass" - ) + ), ]) ); } else { @@ -4756,10 +4757,10 @@ function printClass(path, options, print) { concat([ line, path.call( - superClass => + (superClass) => comments.printComments(superClass, () => printed, options), "superClass" - ) + ), ]) ) ); @@ -4784,7 +4785,7 @@ function printClass(path, options, print) { indent( concat([ line, - join(concat([",", line]), path.map(print, "implements")) + join(concat([",", line]), path.map(print, "implements")), ]) ) ) @@ -4913,14 +4914,14 @@ function printMemberChain(path, options, print) { concat([ printOptionalToken(path), printFunctionTypeParameters(path, options, print), - printArgumentsList(path, options, print) + printArgumentsList(path, options, print), ]), options ), - shouldInsertEmptyLineAfter(node) ? hardline : "" - ]) + shouldInsertEmptyLineAfter(node) ? hardline : "", + ]), }); - path.call(callee => rec(callee), "callee"); + path.call((callee) => rec(callee), "callee"); } else if (isMemberish(node)) { printedNodes.unshift({ node, @@ -4933,19 +4934,19 @@ function printMemberChain(path, options, print) { ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print), options - ) + ), }); - path.call(object => rec(object), "object"); + path.call((object) => rec(object), "object"); } else if (node.type === "TSNonNullExpression") { printedNodes.unshift({ node, - printed: comments.printComments(path, () => "!", options) + printed: comments.printComments(path, () => "!", options), }); - path.call(expression => rec(expression), "expression"); + path.call((expression) => rec(expression), "expression"); } else { printedNodes.unshift({ node, - printed: path.call(print) + printed: path.call(print), }); } } @@ -4958,10 +4959,10 @@ function printMemberChain(path, options, print) { printed: concat([ printOptionalToken(path), printFunctionTypeParameters(path, options, print), - printArgumentsList(path, options, print) - ]) + printArgumentsList(path, options, print), + ]), }); - path.call(callee => rec(callee), "callee"); + path.call((callee) => rec(callee), "callee"); // Once we have a linear list of printed nodes, we want to create groups out // of it. @@ -5055,7 +5056,7 @@ function printMemberChain(path, options, print) { if ( printedNodes[i].node.comments && - printedNodes[i].node.comments.some(comment => comment.trailing) + printedNodes[i].node.comments.some((comment) => comment.trailing) ) { groups.push(currentGroup); currentGroup = []; @@ -5122,7 +5123,7 @@ function printMemberChain(path, options, print) { groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups); function printGroup(printedGroup) { - const printed = printedGroup.map(tuple => tuple.printed); + const printed = printedGroup.map((tuple) => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print // accordingly if ( @@ -5150,8 +5151,8 @@ function printMemberChain(path, options, print) { const flatGroups = groups.reduce((res, group) => res.concat(group), []); const hasComment = - flatGroups.slice(1, -1).some(node => hasLeadingComment(node.node)) || - flatGroups.slice(0, -1).some(node => hasTrailingComment(node.node)) || + flatGroups.slice(1, -1).some((node) => hasLeadingComment(node.node)) || + flatGroups.slice(0, -1).some((node) => hasTrailingComment(node.node)) || (groups[cutoff] && hasLeadingComment(groups[cutoff][0].node)); // If we only have a single `.`, we shouldn't do anything fancy and just @@ -5177,7 +5178,7 @@ function printMemberChain(path, options, print) { printGroup(groups[0]), shouldMerge ? concat(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline : "", - printIndentedGroup(groups.slice(shouldMerge ? 2 : 1)) + printIndentedGroup(groups.slice(shouldMerge ? 2 : 1)), ]); const callExpressions = printedNodes @@ -5193,7 +5194,7 @@ function printMemberChain(path, options, print) { hasComment || (callExpressions.length > 2 && callExpressions.some( - expr => !expr.arguments.every(arg => isSimpleCallArgument(arg, 0)) + (expr) => !expr.arguments.every((arg) => isSimpleCallArgument(arg, 0)) )) || printedGroups.slice(0, -1).some(willBreak) || /** @@ -5208,7 +5209,7 @@ function printMemberChain(path, options, print) { ) && callExpressions .slice(0, -1) - .some(n => n.arguments.some(isFunctionOrArrowExpression))) + .some((n) => n.arguments.some(isFunctionOrArrowExpression))) ) { return group(expanded); } @@ -5218,7 +5219,7 @@ function printMemberChain(path, options, print) { // that means that the parent group has already been broken // naturally willBreak(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent : "", - conditionalGroup([oneLine, expanded]) + conditionalGroup([oneLine, expanded]), ]); } @@ -5419,7 +5420,7 @@ function printJSXElement(path, options, print) { if (n.type === "JSXElement" && isEmptyJSXElement(n)) { return concat([ path.call(print, "openingElement"), - path.call(print, "closingElement") + path.call(print, "closingElement"), ]); } @@ -5441,19 +5442,19 @@ function printJSXElement(path, options, print) { return concat([ openingLines, concat(path.map(print, "children")), - closingLines + closingLines, ]); } // Convert `{" "}` to text nodes containing a space. // This makes it easy to turn them into `jsxWhitespace` which // can then print as either a space or `{" "}` when breaking. - n.children = n.children.map(child => { + n.children = n.children.map((child) => { if (isJSXWhitespaceExpression(child)) { return { type: "JSXText", value: " ", - raw: " " + raw: " ", }; } return child; @@ -5461,8 +5462,8 @@ function printJSXElement(path, options, print) { const containsTag = n.children.filter(isJSXNode).length > 0; const containsMultipleExpressions = - n.children.filter(child => child.type === "JSXExpressionContainer").length > - 1; + n.children.filter((child) => child.type === "JSXExpressionContainer") + .length > 1; const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; @@ -5493,7 +5494,7 @@ function printJSXElement(path, options, print) { isFacebookTranslationTag ); - const containsText = n.children.some(child => isMeaningfulJSXText(child)); + const containsText = n.children.some((child) => isMeaningfulJSXText(child)); // We can end up we multiple whitespace elements with empty string // content between them. @@ -5606,7 +5607,7 @@ function printJSXElement(path, options, print) { openingLines, indent(concat([hardline, content])), hardline, - closingLines + closingLines, ]) ); @@ -5616,7 +5617,7 @@ function printJSXElement(path, options, print) { return conditionalGroup([ group(concat([openingLines, concat(children), closingLines])), - multiLineElem + multiLineElem, ]); } @@ -5636,7 +5637,7 @@ function maybeWrapJSXElementInParens(path, elem, options) { CallExpression: true, OptionalCallExpression: true, ConditionalExpression: true, - JsExpressionRoot: true + JsExpressionRoot: true, }; if (NO_WRAP_PARENTS[parent.type]) { return elem; @@ -5644,9 +5645,9 @@ function maybeWrapJSXElementInParens(path, elem, options) { const shouldBreak = path.match( undefined, - node => node.type === "ArrowFunctionExpression", + (node) => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression, - node => node.type === "JSXExpressionContainer" + (node) => node.type === "JSXExpressionContainer" ); const needsParens = pathNeedsParens(path, options); @@ -5656,7 +5657,7 @@ function maybeWrapJSXElementInParens(path, elem, options) { needsParens ? "" : ifBreak("("), indent(concat([softline, elem])), softline, - needsParens ? "" : ifBreak(")") + needsParens ? "" : ifBreak(")"), ]), { shouldBreak } ); @@ -5721,7 +5722,7 @@ function printBinaryishExpressions( // Flatten them out by recursively calling this function. parts = parts.concat( path.call( - left => + (left) => printBinaryishExpressions( left, print, @@ -5753,8 +5754,10 @@ function printBinaryishExpressions( ": ", join( concat([softline, ":", ifBreak(" ")]), - path.map(print, "arguments").map(arg => align(2, group(arg))) - ) + path + .map(print, "arguments") + .map((arg) => align(2, group(arg))) + ), ]) ) ) @@ -5767,7 +5770,7 @@ function printBinaryishExpressions( operator, lineBeforeOperator ? " " : line, path.call(print, "right"), - rightSuffix + rightSuffix, ]); // If there's only a single binary expression, we want to create a group @@ -5867,10 +5870,7 @@ function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) { } function printRegex(node) { - const flags = node.flags - .split("") - .sort() - .join(""); + const flags = node.flags.split("").sort().join(""); return `/${node.pattern}/${flags}`; } @@ -5905,7 +5905,7 @@ function exprNeedsASIProtection(path, options) { } return path.call( - childPath => exprNeedsASIProtection(childPath, options), + (childPath) => exprNeedsASIProtection(childPath, options), ...getLeftSidePathName(path, node) ); } @@ -5918,7 +5918,7 @@ function stmtNeedsASIProtection(path, options) { } return path.call( - childPath => exprNeedsASIProtection(childPath, options), + (childPath) => exprNeedsASIProtection(childPath, options), "expression" ); } @@ -5930,7 +5930,7 @@ function shouldHugType(node) { if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") { const voidCount = node.types.filter( - n => + (n) => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || @@ -5938,7 +5938,7 @@ function shouldHugType(node) { ).length; const hasObject = node.types.some( - n => + (n) => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}> @@ -5989,7 +5989,7 @@ function printArrayItems(path, options, printPath, print) { const printedElements = []; let separatorParts = []; - path.each(childPath => { + path.each((childPath) => { printedElements.push(concat(separatorParts)); printedElements.push(group(print(childPath))); @@ -6021,7 +6021,7 @@ function printReturnAndThrowArgument(path, options, print) { " (", indent(concat([hardline, path.call(print, "argument")])), hardline, - ")" + ")", ]) ); } else if ( @@ -6035,7 +6035,7 @@ function printReturnAndThrowArgument(path, options, print) { ifBreak(" (", " "), indent(concat([softline, path.call(print, "argument")])), softline, - ifBreak(")") + ifBreak(")"), ]) ) ); @@ -6120,7 +6120,7 @@ function printComment(commentPath, options) { if ( comment.trailing && !hasNewline(options.originalText, options.locStart(comment), { - backwards: true + backwards: true, }) ) { return concat([hardline, printed]); @@ -6154,7 +6154,7 @@ function isIndentableBlockComment(comment) { // `*/` delimiters are not included in the comment value, so add them // back first. const lines = `*${comment.value}*`.split("\n"); - return lines.length > 1 && lines.every(line => line.trim()[0] === "*"); + return lines.length > 1 && lines.every((line) => line.trim()[0] === "*"); } function printIndentableBlockComment(comment) { @@ -6170,7 +6170,7 @@ function printIndentableBlockComment(comment) { : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()) ) ), - "*/" + "*/", ]); } @@ -6188,8 +6188,8 @@ module.exports = { handleComments: { ownLine: handleComments.handleOwnLineComment, endOfLine: handleComments.handleEndOfLineComment, - remaining: handleComments.handleRemainingComment + remaining: handleComments.handleRemainingComment, }, getGapRegex: handleComments.getGapRegex, - getCommentChildNodes: handleComments.getCommentChildNodes + getCommentChildNodes: handleComments.getCommentChildNodes, }; diff --git a/src/language-js/utils.js b/src/language-js/utils.js index 6ded49ca5..34d3a6f04 100644 --- a/src/language-js/utils.js +++ b/src/language-js/utils.js @@ -6,7 +6,7 @@ const { hasNewlineInRange, hasIgnoreComment, hasNodeIgnoreComment, - skipWhitespace + skipWhitespace, } = require("../common/util"); const isIdentifierName = require("esutils").keyword.isIdentifierNameES5; const handleComments = require("./comments"); @@ -47,12 +47,12 @@ function hasNode(node, fn) { return false; } if (Array.isArray(node)) { - return node.some(value => hasNode(value, fn)); + return node.some((value) => hasNode(value, fn)); } const result = fn(node); return typeof result === "boolean" ? result - : Object.keys(node).some(key => hasNode(node[key], fn)); + : Object.keys(node).some((key) => hasNode(node[key], fn)); } function hasNakedLeftSide(node) { @@ -123,7 +123,7 @@ const exportDeclarationTypes = new Set([ "ExportDefaultSpecifier", "DeclareExportDeclaration", "ExportNamedDeclaration", - "ExportAllDeclaration" + "ExportAllDeclaration", ]); function isExportDeclaration(node) { return node && exportDeclarationTypes.has(node.type); @@ -313,7 +313,7 @@ function isSimpleFlowType(node) { "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", - "StringTypeAnnotation" + "StringTypeAnnotation", ]; return ( @@ -382,11 +382,11 @@ function isTestCall(n, parent) { } function hasLeadingComment(node) { - return node.comments && node.comments.some(comment => comment.leading); + return node.comments && node.comments.some((comment) => comment.leading); } function hasTrailingComment(node) { - return node.comments && node.comments.some(comment => comment.trailing); + return node.comments && node.comments.some((comment) => comment.trailing); } function isCallOrOptionalCallExpression(node) { @@ -398,13 +398,13 @@ function isCallOrOptionalCallExpression(node) { function hasDanglingComments(node) { return ( node.comments && - node.comments.some(comment => !comment.leading && !comment.trailing) + node.comments.some((comment) => !comment.leading && !comment.trailing) ); } /** identify if an angular expression seems to have side effects */ function hasNgSideEffect(path) { - return hasNode(path.getValue(), node => { + return hasNode(path.getValue(), (node) => { switch (node.type) { case undefined: return false; @@ -432,7 +432,7 @@ function isSimpleTemplateLiteral(node) { return false; } - return node.expressions.every(expr => { + return node.expressions.every((expr) => { // Disallow comments since printDocToString can't print them here if (expr.comments) { return false; @@ -627,7 +627,7 @@ function hasJsxIgnoreComment(path) { prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find( - comment => comment.value.trim() === "prettier-ignore" + (comment) => comment.value.trim() === "prettier-ignore" ) ); } @@ -657,7 +657,7 @@ function isLastStatement(path) { } const node = path.getValue(); const body = (parent.body || parent.consequent).filter( - stmt => stmt.type !== "EmptyStatement" + (stmt) => stmt.type !== "EmptyStatement" ); return body && body[body.length - 1] === node; } @@ -678,7 +678,7 @@ function hasLeadingOwnLineComment(text, node, options) { const res = node.comments && node.comments.some( - comment => comment.leading && hasNewline(text, options.locEnd(comment)) + (comment) => comment.leading && hasNewline(text, options.locEnd(comment)) ); return res; } @@ -750,7 +750,7 @@ function isJestEachTemplateLiteral(node, parentNode) { } function templateLiteralHasNewLines(template) { - return template.quasis.some(quasi => quasi.value.raw.includes("\n")); + return template.quasis.some((quasi) => quasi.value.raw.includes("\n")); } function isTemplateOnItsOwnLine(n, text, options) { @@ -767,7 +767,7 @@ function needsHardlineAfterDanglingComment(node) { return false; } const lastDanglingComment = getLast( - node.comments.filter(comment => !comment.leading && !comment.trailing) + node.comments.filter((comment) => !comment.leading && !comment.trailing) ); return ( lastDanglingComment && !handleComments.isBlockComment(lastDanglingComment) @@ -921,7 +921,7 @@ function isSimpleCallArgument(node, depth) { if (depth >= 2) { return false; } - const isChildSimple = child => isSimpleCallArgument(child, depth + 1); + const isChildSimple = (child) => isSimpleCallArgument(child, depth + 1); const regexpPattern = (node.type === "Literal" && node.regex && node.regex.pattern) || @@ -953,7 +953,7 @@ function isSimpleCallArgument(node, depth) { } if (node.type === "ObjectExpression") { return node.properties.every( - p => !p.computed && (p.shorthand || (p.value && isChildSimple(p.value))) + (p) => !p.computed && (p.shorthand || (p.value && isChildSimple(p.value))) ); } if (node.type === "ArrayExpression") { @@ -1057,5 +1057,5 @@ module.exports = { matchJsxWhitespaceRegex, needsHardlineAfterDanglingComment, rawText, - returnArgumentHasLeadingComment + returnArgumentHasLeadingComment, }; diff --git a/src/language-markdown/constants.evaluate.js b/src/language-markdown/constants.evaluate.js index 8956cab6b..71ae1dd03 100644 --- a/src/language-markdown/constants.evaluate.js +++ b/src/language-markdown/constants.evaluate.js @@ -14,8 +14,8 @@ const cjkPattern = cjkRegex() "Other_Symbol", "Modifier_Letter", "Modifier_Symbol", - "Nonspacing_Mark" - ] + "Nonspacing_Mark", + ], }) ) .toString(); @@ -42,8 +42,8 @@ const punctuationCharset = unicodeRegex({ /* Pf */ "Final_Punctuation", /* Pi */ "Initial_Punctuation", /* Po */ "Other_Punctuation", - /* Ps */ "Open_Punctuation" - ] + /* Ps */ "Open_Punctuation", + ], }).union(asciiPunctuationCharset); const punctuationPattern = punctuationCharset.toString(); @@ -51,5 +51,5 @@ const punctuationPattern = punctuationCharset.toString(); module.exports = { cjkPattern, kPattern, - punctuationPattern + punctuationPattern, }; diff --git a/src/language-markdown/embed.js b/src/language-markdown/embed.js index 2731c9e3d..2919ffce4 100644 --- a/src/language-markdown/embed.js +++ b/src/language-markdown/embed.js @@ -4,7 +4,7 @@ const util = require("../common/util"); const support = require("../main/support"); const { builders: { hardline, literalline, concat, markAsRoot }, - utils: { mapDoc } + utils: { mapDoc }, } = require("../document"); const { getFencedCodeBlockValue } = require("./utils"); @@ -31,7 +31,7 @@ function embed(path, print, textToDoc, options) { node.lang, hardline, replaceNewlinesWithLiterallines(doc), - style + style, ]) ); } @@ -47,7 +47,7 @@ function embed(path, print, textToDoc, options) { textToDoc(node.value, { parser: "yaml" }) ) : "", - "---" + "---", ]) ); } @@ -59,7 +59,7 @@ function embed(path, print, textToDoc, options) { case "jsx": return textToDoc(`<$>${node.value}`, { parser: "__js_expression", - rootMarker: "mdx" + rootMarker: "mdx", }); } @@ -68,11 +68,11 @@ function embed(path, print, textToDoc, options) { function getParserName(lang) { const supportInfo = support.getSupportInfo({ plugins: options.plugins }); const language = supportInfo.languages.find( - language => + (language) => language.name.toLowerCase() === lang || (language.aliases && language.aliases.includes(lang)) || (language.extensions && - language.extensions.find(ext => ext === `.${lang}`)) + language.extensions.find((ext) => ext === `.${lang}`)) ); if (language) { return language.parsers[0]; @@ -82,7 +82,7 @@ function embed(path, print, textToDoc, options) { } function replaceNewlinesWithLiterallines(doc) { - return mapDoc(doc, currentDoc => + return mapDoc(doc, (currentDoc) => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat( currentDoc diff --git a/src/language-markdown/index.js b/src/language-markdown/index.js index 2db0583fa..359654551 100644 --- a/src/language-markdown/index.js +++ b/src/language-markdown/index.js @@ -5,12 +5,12 @@ const options = require("./options"); const createLanguage = require("../utils/create-language"); const languages = [ - createLanguage(require("linguist-languages/data/Markdown"), data => ({ + createLanguage(require("linguist-languages/data/Markdown"), (data) => ({ since: "1.8.0", parsers: ["markdown"], vscodeLanguageIds: ["markdown"], filenames: data.filenames.concat(["README"]), - extensions: data.extensions.filter(extension => extension !== ".mdx") + extensions: data.extensions.filter((extension) => extension !== ".mdx"), })), createLanguage(require("linguist-languages/data/Markdown"), () => ({ name: "MDX", @@ -18,16 +18,16 @@ const languages = [ parsers: ["mdx"], vscodeLanguageIds: ["mdx"], filenames: [], - extensions: [".mdx"] - })) + extensions: [".mdx"], + })), ]; const printers = { - mdast: printer + mdast: printer, }; module.exports = { languages, options, - printers + printers, }; diff --git a/src/language-markdown/mdx.js b/src/language-markdown/mdx.js index bec22f48c..d73610de9 100644 --- a/src/language-markdown/mdx.js +++ b/src/language-markdown/mdx.js @@ -30,8 +30,8 @@ const BLOCKS_REGEX = "[a-z][a-z0-9]*(\\.[a-z][a-z0-9]*)*|"; const COMMENT_REGEX = "|"; const EMPTY_NEWLINE = "\n\n"; -const isImport = text => IMPORT_REGEX.test(text); -const isExport = text => EXPORT_REGEX.test(text); +const isImport = (text) => IMPORT_REGEX.test(text); +const isExport = (text) => EXPORT_REGEX.test(text); const tokenizeEsSyntax = (eat, value) => { const index = value.indexOf(EMPTY_NEWLINE); @@ -40,7 +40,7 @@ const tokenizeEsSyntax = (eat, value) => { if (isExport(subvalue) || isImport(subvalue)) { return eat(subvalue)({ type: isExport(subvalue) ? "export" : "import", - value: subvalue + value: subvalue, }); } }; @@ -62,5 +62,5 @@ function esSyntax() { module.exports = { esSyntax, BLOCKS_REGEX, - COMMENT_REGEX + COMMENT_REGEX, }; diff --git a/src/language-markdown/options.js b/src/language-markdown/options.js index 68e4dbf40..11d40f10d 100644 --- a/src/language-markdown/options.js +++ b/src/language-markdown/options.js @@ -5,5 +5,5 @@ const commonOptions = require("../common/common-options"); // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js module.exports = { proseWrap: commonOptions.proseWrap, - singleQuote: commonOptions.singleQuote + singleQuote: commonOptions.singleQuote, }; diff --git a/src/language-markdown/parser-markdown.js b/src/language-markdown/parser-markdown.js index 65d4fce99..a9e4f6183 100644 --- a/src/language-markdown/parser-markdown.js +++ b/src/language-markdown/parser-markdown.js @@ -23,12 +23,12 @@ const remarkMath = require("remark-math"); * interface InlineCode { children: Array } */ function createParse({ isMDX }) { - return text => { + return (text) => { const processor = unified() .use(remarkParse, { footnotes: true, commonmark: true, - ...(isMDX && { blocks: [mdx.BLOCKS_REGEX] }) + ...(isMDX && { blocks: [mdx.BLOCKS_REGEX] }), }) .use(frontMatter) .use(remarkMath) @@ -44,7 +44,7 @@ function identity(x) { } function htmlToJsx() { - return ast => + return (ast) => mapAst(ast, (node, _index, [parent]) => { if ( node.type !== "html" || @@ -85,11 +85,11 @@ function liquid() { if (match) { return eat(match[0])({ type: "liquidNode", - value: match[0] + value: match[0], }); } } - tokenizer.locator = function(value, fromIndex) { + tokenizer.locator = function (value, fromIndex) { return value.indexOf("{", fromIndex); }; } @@ -97,9 +97,9 @@ function liquid() { const baseParser = { astFormat: "mdast", hasPragma: pragma.hasPragma, - locStart: node => node.position.start.offset, - locEnd: node => node.position.end.offset, - preprocess: text => text.replace(/\n\s+$/, "\n") // workaround for https://github.com/remarkjs/remark/issues/350 + locStart: (node) => node.position.start.offset, + locEnd: (node) => node.position.end.offset, + preprocess: (text) => text.replace(/\n\s+$/, "\n"), // workaround for https://github.com/remarkjs/remark/issues/350 }; const markdownParser = { ...baseParser, parse: createParse({ isMDX: false }) }; @@ -110,6 +110,6 @@ module.exports = { parsers: { remark: markdownParser, markdown: markdownParser, - mdx: mdxParser - } + mdx: mdxParser, + }, }; diff --git a/src/language-markdown/pragma.js b/src/language-markdown/pragma.js index 4ca546c0f..998d5e4b7 100644 --- a/src/language-markdown/pragma.js +++ b/src/language-markdown/pragma.js @@ -9,7 +9,7 @@ function startWithPragma(text) { const regex = new RegExp( [ ``, - `` + ``, ].join("|"), "m" ); @@ -19,13 +19,13 @@ function startWithPragma(text) { module.exports = { startWithPragma, - hasPragma: text => + hasPragma: (text) => startWithPragma(parseFrontMatter(text).content.trimStart()), - insertPragma: text => { + insertPragma: (text) => { const extracted = parseFrontMatter(text); const pragma = ``; return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`; - } + }, }; diff --git a/src/language-markdown/preprocess.js b/src/language-markdown/preprocess.js index 072f89a48..5b97c7e42 100644 --- a/src/language-markdown/preprocess.js +++ b/src/language-markdown/preprocess.js @@ -19,7 +19,7 @@ function preprocess(ast, options) { } function transformImportExport(ast) { - return mapAst(ast, node => { + return mapAst(ast, (node) => { if (node.type !== "import" && node.type !== "export") { return node; } @@ -29,7 +29,7 @@ function transformImportExport(ast) { } function transformInlineCode(ast) { - return mapAst(ast, node => { + return mapAst(ast, (node) => { if (node.type !== "inlineCode") { return node; } @@ -39,7 +39,7 @@ function transformInlineCode(ast) { } function restoreUnescapedCharacter(ast, options) { - return mapAst(ast, node => { + return mapAst(ast, (node) => { return node.type !== "text" ? node : { @@ -55,7 +55,7 @@ function restoreUnescapedCharacter(ast, options) { node.position.start.offset, node.position.end.offset ) - : node.value + : node.value, }; }); } @@ -70,14 +70,14 @@ function mergeContinuousImportExport(ast) { value: prevNode.value + "\n\n" + node.value, position: { start: prevNode.position.start, - end: node.position.end - } + end: node.position.end, + }, }) ); } function mergeChildren(ast, shouldMerge, mergeNode) { - return mapAst(ast, node => { + return mapAst(ast, (node) => { if (!node.children) { return node; } @@ -103,8 +103,8 @@ function mergeContinuousTexts(ast) { value: prevNode.value + node.value, position: { start: prevNode.position.start, - end: node.position.end - } + end: node.position.end, + }, }) ); } @@ -129,7 +129,7 @@ function splitTextIntoSentences(ast, options) { return { type: "sentence", position: node.position, - children: splitText(value, options) + children: splitText(value, options), }; }); } diff --git a/src/language-markdown/printer-markdown.js b/src/language-markdown/printer-markdown.js index 12aee5830..ef61e8e1e 100644 --- a/src/language-markdown/printer-markdown.js +++ b/src/language-markdown/printer-markdown.js @@ -18,10 +18,10 @@ const { fill, align, indent, - group + group, }, utils: { mapDoc }, - printer: { printDocToString } + printer: { printDocToString }, } = require("../document"); const { getFencedCodeBlockValue, @@ -29,7 +29,7 @@ const { splitText, punctuationPattern, INLINE_NODE_TYPES, - INLINE_NODE_WRAPPER_TYPES + INLINE_NODE_WRAPPER_TYPES, } = require("./utils"); const { replaceEndOfLineWith } = require("../common/util"); @@ -48,7 +48,7 @@ function genericPrint(path, options, print) { node.position.end.offset ), options - ).map(node => + ).map((node) => node.type === "word" ? node.value : node.value === "" @@ -67,11 +67,11 @@ function genericPrint(path, options, print) { normalizeDoc(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.includes(getLastDescendantNode(node).type) ? hardline - : "" + : "", ]); case "paragraph": return printChildren(path, options, print, { - postprocessor: fill + postprocessor: fill, }); case "sentence": return printChildren(path, options, print); @@ -82,7 +82,7 @@ function genericPrint(path, options, print) { new RegExp( [ `(^|${punctuationPattern})(_+)`, - `(_+)(${punctuationPattern}|$)` + `(_+)(${punctuationPattern}|$)`, ].join("|"), "g" ), @@ -160,7 +160,7 @@ function genericPrint(path, options, print) { "](", printUrl(node.url, ")"), printTitle(node.title, options), - ")" + ")", ]); default: return options.originalText.slice( @@ -175,14 +175,14 @@ function genericPrint(path, options, print) { "](", printUrl(node.url, ")"), printTitle(node.title, options), - ")" + ")", ]); case "blockquote": return concat(["> ", align("> ", printChildren(path, options, print))]); case "heading": return concat([ "#".repeat(node.depth) + " ", - printChildren(path, options, print) + printChildren(path, options, print), ]); case "code": { if (node.isIndented) { @@ -192,7 +192,7 @@ function genericPrint(path, options, print) { alignment, concat([ alignment, - concat(replaceEndOfLineWith(node.value, hardline)) + concat(replaceEndOfLineWith(node.value, hardline)), ]) ); } @@ -216,7 +216,7 @@ function genericPrint(path, options, print) { ) ), hardline, - style + style, ]); } case "yaml": @@ -264,7 +264,7 @@ function genericPrint(path, options, print) { ) { return concat([ prefix, - printListItem(childPath, options, print, prefix) + printListItem(childPath, options, print, prefix), ]); } @@ -273,7 +273,7 @@ function genericPrint(path, options, print) { align( " ".repeat(prefix.length), printListItem(childPath, options, print, prefix) - ) + ), ]); function getPrefix() { @@ -293,7 +293,7 @@ function genericPrint(path, options, print) { ? alignListPrefix(rawPrefix, options) : rawPrefix; } - } + }, }); } case "thematicBreak": { @@ -316,7 +316,7 @@ function genericPrint(path, options, print) { ? concat(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" - : "" + : "", ]); case "imageReference": switch (node.referenceType) { @@ -327,7 +327,7 @@ function genericPrint(path, options, print) { "![", node.alt, "]", - node.referenceType === "collapsed" ? "[]" : "" + node.referenceType === "collapsed" ? "[]" : "", ]); } case "definition": { @@ -341,9 +341,9 @@ function genericPrint(path, options, print) { printUrl(node.url), node.title === null ? "" - : concat([lineOrSpace, printTitle(node.title, options, false)]) + : concat([lineOrSpace, printTitle(node.title, options, false)]), ]) - ) + ), ]) ); } @@ -375,14 +375,14 @@ function genericPrint(path, options, print) { return index === 0 ? group(concat([softline, childPath.call(print)])) : childPath.call(print); - } + }, }) ), nextNode && nextNode.type === "footnoteDefinition" ? softline - : "" + : "", ]) - ) + ), ]); } case "table": @@ -406,10 +406,10 @@ function genericPrint(path, options, print) { node.value ? concat([ concat(replaceEndOfLineWith(node.value, hardline)), - hardline + hardline, ]) : "", - "$$" + "$$", ]); case "inlineMath": { // remark-math trims content but we don't want to remove whitespaces @@ -442,8 +442,8 @@ function printListItem(path, options, print, listPrefix) { clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block ); return concat([alignment, align(alignment, childPath.call(print))]); - } - }) + }, + }), ]); } @@ -466,7 +466,7 @@ function getNthListSiblingIndex(node, parentNode) { return getNthSiblingIndex( node, parentNode, - siblingNode => siblingNode.ordered === node.ordered + (siblingNode) => siblingNode.ordered === node.ordered ); } @@ -541,10 +541,10 @@ function printTable(path, options, print) { const node = path.getValue(); const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } } - path.map(rowPath => { + path.map((rowPath) => { const rowContents = []; - rowPath.map(cellPath => { + rowPath.map((cellPath) => { rowContents.push( printDocToString(cellPath.call(print), options).formatted ); @@ -566,8 +566,8 @@ function printTable(path, options, print) { printSeparator(), join( hardlineWithoutBreakParent, - contents.slice(1).map(rowContents => printRow(rowContents)) - ) + contents.slice(1).map((rowContents) => printRow(rowContents)) + ), ]); if (options.proseWrap !== "never") { @@ -582,8 +582,8 @@ function printTable(path, options, print) { hardlineWithoutBreakParent, contents .slice(1) - .map(rowContents => printRow(rowContents, /* isCompact */ true)) - ) + .map((rowContents) => printRow(rowContents, /* isCompact */ true)) + ), ]); return concat([breakParent, group(ifBreak(compactTable, alignedTable))]); @@ -607,7 +607,7 @@ function printTable(path, options, print) { } }) ), - " |" + " |", ]); } @@ -629,7 +629,7 @@ function printTable(path, options, print) { } }) ), - " |" + " |", ]); } @@ -671,7 +671,7 @@ function printRoot(path, options, print) { if (ignoreStart !== null) { ignoreRanges.push({ start: ignoreStart, - end: { index, offset: childNode.position.start.offset } + end: { index, offset: childNode.position.start.offset }, }); ignoreStart = null; } @@ -694,7 +694,7 @@ function printRoot(path, options, print) { ignoreRange.start.offset, ignoreRange.end.offset ), - children[ignoreRange.end.index].value + children[ignoreRange.end.index].value, ]); } @@ -709,7 +709,7 @@ function printRoot(path, options, print) { } return childPath.call(print); - } + }, }); } @@ -717,7 +717,7 @@ function printChildren(path, options, print, events) { events = events || {}; const postprocessor = events.postprocessor || concat; - const processor = events.processor || (childPath => childPath.call(print)); + const processor = events.processor || ((childPath) => childPath.call(print)); const node = path.getValue(); const parts = []; @@ -733,7 +733,7 @@ function printChildren(path, options, print, events) { parts, prevNode: lastChildNode, parentNode: node, - options + options, }; if (!shouldNotPrePrintHardline(childNode, data)) { @@ -846,7 +846,7 @@ function shouldPrePrintTripleHardline(node, data) { function shouldRemainTheSameContent(path) { const ancestorNode = getAncestorNode(path, [ "linkReference", - "imageReference" + "imageReference", ]); return ( @@ -857,7 +857,7 @@ function shouldRemainTheSameContent(path) { } function normalizeDoc(doc) { - return mapDoc(doc, currentDoc => { + return mapDoc(doc, (currentDoc) => { if (!currentDoc.parts) { return currentDoc; } @@ -877,14 +877,14 @@ function normalizeDoc(doc) { return { ...currentDoc, - parts: normalizeParts(parts) + parts: normalizeParts(parts), }; }); } function printUrl(url, dangerousCharOrChars) { const dangerousChars = [" "].concat(dangerousCharOrChars || []); - return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) + return new RegExp(dangerousChars.map((x) => `\\${x}`).join("|")).test(url) ? `<${url}>` : url; } @@ -997,5 +997,5 @@ module.exports = { embed, massageAstNode: clean, hasPrettierIgnore, - insertPragma: pragma.insertPragma + insertPragma: pragma.insertPragma, }; diff --git a/src/language-markdown/utils.js b/src/language-markdown/utils.js index f2e52c88f..05abf00fc 100644 --- a/src/language-markdown/utils.js +++ b/src/language-markdown/utils.js @@ -3,7 +3,7 @@ const { cjkPattern, kPattern, - punctuationPattern + punctuationPattern, } = require("./constants.evaluate"); const { getLast } = require("../common/util"); @@ -23,13 +23,13 @@ const INLINE_NODE_TYPES = [ "whitespace", "word", "break", - "inlineMath" + "inlineMath", ]; const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat([ "tableCell", "paragraph", - "heading" + "heading", ]); const kRegex = new RegExp(kPattern); @@ -58,7 +58,7 @@ function splitText(text, options) { if (index % 2 === 1) { nodes.push({ type: "whitespace", - value: /\n/.test(token) ? "\n" : " " + value: /\n/.test(token) ? "\n" : " ", }); return; } @@ -89,7 +89,7 @@ function splitText(text, options) { hasLeadingPunctuation: punctuationRegex.test(innerToken[0]), hasTrailingPunctuation: punctuationRegex.test( getLast(innerToken) - ) + ), }); } return; @@ -103,7 +103,7 @@ function splitText(text, options) { value: innerToken, kind: KIND_CJK_PUNCTUATION, hasLeadingPunctuation: true, - hasTrailingPunctuation: true + hasTrailingPunctuation: true, } : { type: "word", @@ -112,7 +112,7 @@ function splitText(text, options) { ? KIND_K_LETTER : KIND_CJ_LETTER, hasLeadingPunctuation: false, - hasTrailingPunctuation: false + hasTrailingPunctuation: false, } ); }); @@ -135,7 +135,7 @@ function splitText(text, options) { } else if ( !isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace - ![lastNode.value, node.value].some(value => /\u3000/.test(value)) + ![lastNode.value, node.value].some((value) => /\u3000/.test(value)) ) { nodes.push({ type: "whitespace", value: "" }); } @@ -249,5 +249,5 @@ module.exports = { getOrderedListItemInfo, hasGitDiffFriendlyOrderedList, INLINE_NODE_TYPES, - INLINE_NODE_WRAPPER_TYPES + INLINE_NODE_WRAPPER_TYPES, }; diff --git a/src/language-yaml/index.js b/src/language-yaml/index.js index f4544855e..79ee040c9 100644 --- a/src/language-yaml/index.js +++ b/src/language-yaml/index.js @@ -8,12 +8,12 @@ const languages = [ createLanguage(require("linguist-languages/data/YAML"), () => ({ since: "1.14.0", parsers: ["yaml"], - vscodeLanguageIds: ["yaml"] - })) + vscodeLanguageIds: ["yaml"], + })), ]; module.exports = { languages, printers: { yaml: printer }, - options + options, }; diff --git a/src/language-yaml/options.js b/src/language-yaml/options.js index 62215b77e..7f5ad6652 100644 --- a/src/language-yaml/options.js +++ b/src/language-yaml/options.js @@ -6,5 +6,5 @@ const commonOptions = require("../common/common-options"); module.exports = { bracketSpacing: commonOptions.bracketSpacing, singleQuote: commonOptions.singleQuote, - proseWrap: commonOptions.proseWrap + proseWrap: commonOptions.proseWrap, }; diff --git a/src/language-yaml/parser-yaml.js b/src/language-yaml/parser-yaml.js index 3d7c9bf83..e7d8c3530 100644 --- a/src/language-yaml/parser-yaml.js +++ b/src/language-yaml/parser-yaml.js @@ -28,12 +28,12 @@ const parser = { astFormat: "yaml", parse, hasPragma, - locStart: node => node.position.start.offset, - locEnd: node => node.position.end.offset + locStart: (node) => node.position.start.offset, + locEnd: (node) => node.position.end.offset, }; module.exports = { parsers: { - yaml: parser - } + yaml: parser, + }, }; diff --git a/src/language-yaml/pragma.js b/src/language-yaml/pragma.js index c2853c4ad..56225a0d3 100644 --- a/src/language-yaml/pragma.js +++ b/src/language-yaml/pragma.js @@ -15,5 +15,5 @@ function insertPragma(text) { module.exports = { isPragma, hasPragma, - insertPragma + insertPragma, }; diff --git a/src/language-yaml/printer-yaml.js b/src/language-yaml/printer-yaml.js index d0a47e418..52f711a91 100644 --- a/src/language-yaml/printer-yaml.js +++ b/src/language-yaml/printer-yaml.js @@ -18,7 +18,7 @@ const { isNode, isEmptyNode, defineShortcut, - mapNode + mapNode, } = require("./utils"); const docBuilders = require("../document").builders; const { @@ -36,7 +36,7 @@ const { lineSuffix, literalline, markAsRoot, - softline + softline, } = docBuilders; const { replaceEndOfLineWith } = require("../common/util"); @@ -80,7 +80,7 @@ function genericPrint(path, options, print) { "comment", "directive", "mappingItem", - "sequenceItem" + "sequenceItem", ]) && !isLastDescendantNode(path) ? printNextEmptyLine(path, options.originalText) : ""; @@ -101,7 +101,7 @@ function genericPrint(path, options, print) { ? concat([ node.middleComments.length === 1 ? "" : hardline, join(hardline, path.map(print, "middleComments")), - hardline + hardline, ]) : "", hasPrettierIgnore(path) @@ -124,7 +124,7 @@ function genericPrint(path, options, print) { isInlineNode(node) ? "" : breakParent, - path.call(print, "trailingComment") + path.call(print, "trailingComment"), ]) ) : "", @@ -134,7 +134,7 @@ function genericPrint(path, options, print) { node.type === "sequenceItem" ? 2 : 0, concat([hardline, join(hardline, path.map(print, "endComments"))]) ) - : "" + : "", ]); } @@ -155,20 +155,20 @@ function _print(node, parentNode, path, options, print) { "...", hasTrailingComment(document) ? concat([" ", path.call(print, "trailingComment")]) - : "" + : "", ]) : !nextDocument || hasTrailingComment(nextDocument.head) ? "" - : concat([hardline, "---"]) + : concat([hardline, "---"]), ]); }, "children") ), node.children.length === 0 || - (lastDescendantNode => + ((lastDescendantNode) => isNode(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep")(getLastDescendantNode(node)) ? "" - : hardline + : hardline, ]); case "document": { const nextDocument = parentNode.children[path.getName() + 1]; @@ -193,14 +193,14 @@ function _print(node, parentNode, path, options, print) { hasTrailingComment(node.head) ? concat([ " ", - path.call(print, "head", "trailingComment") + path.call(print, "head", "trailingComment"), ]) - : "" - ]) + : "", + ]), ].filter(Boolean) ) : "", - shouldPrintDocumentBody(node) ? path.call(print, "body") : "" + shouldPrintDocumentBody(node) ? path.call(print, "body") : "", ].filter(Boolean) ); } @@ -215,7 +215,7 @@ function _print(node, parentNode, path, options, print) { const separator = children.length === 0 || endComments.length === 0 ? "" - : (lastDescendantNode => + : ((lastDescendantNode) => isNode(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true) @@ -268,7 +268,7 @@ function _print(node, parentNode, path, options, print) { return concat([ originalQuote, printFlowScalarContent(node.type, raw, options), - originalQuote + originalQuote, ]); } else if (raw.includes(doubleQuote)) { return concat([ @@ -283,7 +283,7 @@ function _print(node, parentNode, path, options, print) { : raw, options ), - singleQuote + singleQuote, ]); } @@ -298,7 +298,7 @@ function _print(node, parentNode, path, options, print) { : raw, options ), - doubleQuote + doubleQuote, ]); } @@ -306,12 +306,12 @@ function _print(node, parentNode, path, options, print) { return concat([ quote, printFlowScalarContent(node.type, raw, options), - quote + quote, ]); } case "blockFolded": case "blockLiteral": { - const parentIndent = getAncestorCount(path, ancestorNode => + const parentIndent = getAncestorCount(path, (ancestorNode) => isNode(ancestorNode, ["sequence", "mapping"]) ); const isLastDescendant = isLastDescendantNode(path); @@ -331,7 +331,7 @@ function _print(node, parentNode, path, options, print) { getBlockValueLineContents(node, { parentIndent, isLastDescendant, - options + options, }).reduce( (reduced, lineWords, index, lineContents) => reduced.concat( @@ -351,7 +351,7 @@ function _print(node, parentNode, path, options, print) { ) ) ) - ) + ), ]); } case "sequence": @@ -359,7 +359,7 @@ function _print(node, parentNode, path, options, print) { case "sequenceItem": return concat([ "- ", - align(2, !node.content ? "" : path.call(print, "content")) + align(2, !node.content ? "" : path.call(print, "content")), ]); case "mappingKey": return !node.content ? "" : path.call(print, "content"); @@ -410,10 +410,10 @@ function _print(node, parentNode, path, options, print) { "", path .map(print, "value", "leadingComments") - .map(comment => concat([comment, hardline])) + .map((comment) => concat([comment, hardline])) ), ": ", - align(2, value) + align(2, value), ]) : // force singleline isSingleLineNode(node.key.content) && @@ -429,7 +429,7 @@ function _print(node, parentNode, path, options, print) { key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", - value + value, ]) : conditionalGroup([ concat([ @@ -456,12 +456,12 @@ function _print(node, parentNode, path, options, print) { : !node.value.content ? "" : line, - value + value, ]) ), { groupId } - ) - ]) + ), + ]), ]); } case "flowMapping": @@ -476,7 +476,7 @@ function _print(node, parentNode, path, options, print) { : softline; const isLastItemEmptyMappingItem = node.children.length !== 0 && - (lastItem => + ((lastItem) => lastItem.type === "flowMappingItem" && isEmptyNode(lastItem.key) && isEmptyNode(lastItem.value))(getLast(node.children)); @@ -501,17 +501,17 @@ function _print(node, parentNode, path, options, print) { childPath, options.originalText ) - : "" - ]) + : "", + ]), ]), "children" ) ), - ifBreak(",", "") + ifBreak(",", ""), ]) ), isLastItemEmptyMappingItem ? "" : bracketSpacing, - closeMarker + closeMarker, ]); } case "flowSequenceItem": @@ -704,7 +704,7 @@ function printFlowScalarContent(nodeType, content, options) { const lineContents = getFlowScalarLineContents(nodeType, content, options); return join( hardline, - lineContents.map(lineContentWords => + lineContents.map((lineContentWords) => fill(join(line, lineContentWords).parts) ) ); @@ -732,5 +732,5 @@ module.exports = { preprocess, print: genericPrint, massageAstNode: clean, - insertPragma + insertPragma, }; diff --git a/src/language-yaml/utils.js b/src/language-yaml/utils.js index 829349cdf..0ff8f6ed7 100644 --- a/src/language-yaml/utils.js +++ b/src/language-yaml/utils.js @@ -31,9 +31,9 @@ function mapNode(node, callback, parent) { "children" in node ? { ...node, - children: node.children.map(childNode => + children: node.children.map((childNode) => mapNode(childNode, callback, node) - ) + ), } : node, parent @@ -43,7 +43,7 @@ function mapNode(node, callback, parent) { function defineShortcut(x, key, getter) { Object.defineProperty(x, key, { get: getter, - enumerable: false + enumerable: false, }); } @@ -204,13 +204,13 @@ function getFlowScalarLineContents(nodeType, content, options) { ); if (options.proseWrap === "preserve") { - return rawLineContents.map(lineContent => + return rawLineContents.map((lineContent) => lineContent.length === 0 ? [] : [lineContent] ); } return rawLineContents - .map(lineContent => + .map((lineContent) => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent) ) .reduce( @@ -229,7 +229,7 @@ function getFlowScalarLineContents(nodeType, content, options) { : reduced.concat([lineContentWords]), [] ) - .map(lineContentWords => + .map((lineContentWords) => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords @@ -250,18 +250,18 @@ function getBlockValueLineContents( const leadingSpaceCount = node.indent === null - ? (match => (match ? match[1].length : Infinity))( + ? ((match) => (match ? match[1].length : Infinity))( content.match(/^( *)\S/m) ) : node.indent - 1 + parentIndent; const rawLineContents = content .split("\n") - .map(lineContent => lineContent.slice(leadingSpaceCount)); + .map((lineContent) => lineContent.slice(leadingSpaceCount)); if (options.proseWrap === "preserve" || node.type === "blockLiteral") { return removeUnnecessaryTrailingNewlines( - rawLineContents.map(lineContent => + rawLineContents.map((lineContent) => lineContent.length === 0 ? [] : [lineContent] ) ); @@ -269,7 +269,7 @@ function getBlockValueLineContents( return removeUnnecessaryTrailingNewlines( rawLineContents - .map(lineContent => + .map((lineContent) => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent) ) .reduce( @@ -283,7 +283,7 @@ function getBlockValueLineContents( : reduced.concat([lineContentWords]), [] ) - .map(lineContentWords => + .map((lineContentWords) => lineContentWords.reduce( (reduced, word) => // disallow trailing spaces @@ -293,7 +293,7 @@ function getBlockValueLineContents( [] ) ) - .map(lineContentWords => + .map((lineContentWords) => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords @@ -342,5 +342,5 @@ module.exports = { hasMiddleComments, hasIndicatorComment, hasTrailingComment, - hasEndComments + hasEndComments, }; diff --git a/src/main/ast-to-doc.js b/src/main/ast-to-doc.js index df5d0cfa4..8863f26b4 100644 --- a/src/main/ast-to-doc.js +++ b/src/main/ast-to-doc.js @@ -61,7 +61,7 @@ function printAstToDoc(ast, options, alignmentSize = 0) { // comments to print res = comments.printComments( path, - p => callPluginPrintFunction(p, options, printGenerically, args), + (p) => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi ); diff --git a/src/main/comments.js b/src/main/comments.js index 1c1758d93..385b0c3ca 100644 --- a/src/main/comments.js +++ b/src/main/comments.js @@ -9,17 +9,17 @@ const { indent, lineSuffix, join, - cursor + cursor, } = require("../document").builders; const { hasNewline, skipNewline, - isPreviousLineEmpty + isPreviousLineEmpty, } = require("../common/util"); const { addLeadingComment, addDanglingComment, - addTrailingComment + addTrailingComment, } = require("../common/util-shared"); const childNodesCacheKey = Symbol("child-nodes"); @@ -56,12 +56,12 @@ function getSortedChildNodes(node, options, resultArray) { (typeof node === "object" && Object.keys(node) .filter( - n => + (n) => n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode" ) - .map(n => node[n])); + .map((n) => node[n])); if (!childNodes) { return; @@ -70,11 +70,11 @@ function getSortedChildNodes(node, options, resultArray) { if (!resultArray) { Object.defineProperty(node, childNodesCacheKey, { value: (resultArray = []), - enumerable: false + enumerable: false, }); } - childNodes.forEach(childNode => { + childNodes.forEach((childNode) => { getSortedChildNodes(childNode, options, resultArray); }); @@ -285,7 +285,7 @@ function attach(comments, ast, text, options) { breakTies(tiesToBreak, text, options); - comments.forEach(comment => { + comments.forEach((comment) => { // These node references were useful for breaking ties, but we // don't need them anymore, and they create cycles in the AST that // may lead to infinite recursion if we don't delete them here. @@ -390,7 +390,7 @@ function printLeadingComment(commentPath, print, options) { if (isBlock) { const lineBreak = hasNewline(options.originalText, options.locEnd(comment)) ? hasNewline(options.originalText, options.locStart(comment), { - backwards: true + backwards: true, }) ? hardline : line @@ -424,7 +424,7 @@ function printTrailingComment(commentPath, print, options) { if ( hasNewline(options.originalText, options.locStart(comment), { - backwards: true + backwards: true, }) ) { // This allows comments at the end of nested structures: @@ -455,7 +455,7 @@ function printTrailingComment(commentPath, print, options) { return concat([ lineSuffix(concat([" ", contents])), - !isBlock ? breakParent : "" + !isBlock ? breakParent : "", ]); } @@ -467,7 +467,7 @@ function printDanglingComments(path, options, sameIndent, filter) { return ""; } - path.each(commentPath => { + path.each((commentPath) => { const comment = commentPath.getValue(); if ( comment && @@ -508,7 +508,7 @@ function printComments(path, print, options, needsSemi) { const leadingParts = []; const trailingParts = [needsSemi ? ";" : "", printed]; - path.each(commentPath => { + path.each((commentPath) => { const comment = commentPath.getValue(); const { leading, trailing } = comment; @@ -540,5 +540,5 @@ module.exports = { attach, printComments, printDanglingComments, - getSortedChildNodes + getSortedChildNodes, }; diff --git a/src/main/core-options.js b/src/main/core-options.js index bbb1712f8..1721817c8 100644 --- a/src/main/core-options.js +++ b/src/main/core-options.js @@ -59,7 +59,7 @@ const options = { Print (to stderr) where a cursor at the given position would move to after formatting. This option cannot be used with --range-start and --range-end. `, - cliCategory: CATEGORY_EDITOR + cliCategory: CATEGORY_EDITOR, }, endOfLine: { since: "1.15.0", @@ -67,32 +67,32 @@ const options = { type: "choice", default: [ { since: "1.15.0", value: "auto" }, - { since: "2.0.0", value: "lf" } + { since: "2.0.0", value: "lf" }, ], description: "Which end of line characters to apply.", choices: [ { value: "lf", description: - "Line Feed only (\\n), common on Linux and macOS as well as inside git repos" + "Line Feed only (\\n), common on Linux and macOS as well as inside git repos", }, { value: "crlf", description: - "Carriage Return + Line Feed characters (\\r\\n), common on Windows" + "Carriage Return + Line Feed characters (\\r\\n), common on Windows", }, { value: "cr", - description: "Carriage Return character only (\\r), used very rarely" + description: "Carriage Return character only (\\r), used very rarely", }, { value: "auto", description: dedent` Maintain existing (mixed values within one file are normalised by looking at what's used after the first line) - ` - } - ] + `, + }, + ], }, filepath: { since: "1.4.0", @@ -102,7 +102,7 @@ const options = { "Specify the input filepath. This will be used to do parser inference.", cliName: "stdin-filepath", cliCategory: CATEGORY_OTHER, - cliDescription: "Path to the file to pretend that stdin comes from." + cliDescription: "Path to the file to pretend that stdin comes from.", }, insertPragma: { since: "1.8.0", @@ -110,7 +110,7 @@ const options = { type: "boolean", default: false, description: "Insert @format pragma into file's first docblock comment.", - cliCategory: CATEGORY_OTHER + cliCategory: CATEGORY_OTHER, }, parser: { since: "0.0.10", @@ -118,10 +118,10 @@ const options = { type: "choice", default: [ { since: "0.0.10", value: "babylon" }, - { since: "1.13.0", value: undefined } + { since: "1.13.0", value: undefined }, ], description: "Which parser to use.", - exception: value => + exception: (value) => typeof value === "string" || typeof value === "function", choices: [ { value: "flow", description: "Flow" }, @@ -137,7 +137,7 @@ const options = { { value: "json-stringify", since: "1.13.0", - description: "JSON.stringify" + description: "JSON.stringify", }, { value: "graphql", since: "1.5.0", description: "GraphQL" }, { value: "markdown", since: "1.8.0", description: "Markdown" }, @@ -147,12 +147,16 @@ const options = { { value: "glimmer", since: null, - description: "Handlebars" + description: "Handlebars", }, { value: "html", since: "1.15.0", description: "HTML" }, { value: "angular", since: "1.15.0", description: "Angular" }, - { value: "lwc", since: "1.17.0", description: "Lightning Web Components" } - ] + { + value: "lwc", + since: "1.17.0", + description: "Lightning Web Components", + }, + ], }, plugins: { since: "1.10.0", @@ -162,9 +166,10 @@ const options = { category: CATEGORY_GLOBAL, description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.", - exception: value => typeof value === "string" || typeof value === "object", + exception: (value) => + typeof value === "string" || typeof value === "object", cliName: "plugin", - cliCategory: CATEGORY_CONFIG + cliCategory: CATEGORY_CONFIG, }, pluginSearchDirs: { since: "1.13.0", @@ -177,9 +182,10 @@ const options = { Overrides default behavior when plugins are searched relatively to the location of Prettier. Multiple values are accepted. `, - exception: value => typeof value === "string" || typeof value === "object", + exception: (value) => + typeof value === "string" || typeof value === "object", cliName: "plugin-search-dir", - cliCategory: CATEGORY_CONFIG + cliCategory: CATEGORY_CONFIG, }, printWidth: { since: "0.0.0", @@ -187,7 +193,7 @@ const options = { type: "int", default: 80, description: "The line length where Prettier will try wrap.", - range: { start: 0, end: Infinity, step: 1 } + range: { start: 0, end: Infinity, step: 1 }, }, rangeEnd: { since: "1.4.0", @@ -200,7 +206,7 @@ const options = { The range will extend forwards to the end of the selected statement. This option cannot be used with --cursor-offset. `, - cliCategory: CATEGORY_EDITOR + cliCategory: CATEGORY_EDITOR, }, rangeStart: { since: "1.4.0", @@ -213,7 +219,7 @@ const options = { The range will extend backwards to the start of the first line containing the selected statement. This option cannot be used with --cursor-offset. `, - cliCategory: CATEGORY_EDITOR + cliCategory: CATEGORY_EDITOR, }, requirePragma: { since: "1.7.0", @@ -224,22 +230,22 @@ const options = { Require either '@prettier' or '@format' to be present in the file's first docblock comment in order for it to be formatted. `, - cliCategory: CATEGORY_OTHER + cliCategory: CATEGORY_OTHER, }, tabWidth: { type: "int", category: CATEGORY_GLOBAL, default: 2, description: "Number of spaces per indentation level.", - range: { start: 0, end: Infinity, step: 1 } + range: { start: 0, end: Infinity, step: 1 }, }, useTabs: { since: "1.0.0", category: CATEGORY_GLOBAL, type: "boolean", default: false, - description: "Indent with tabs instead of spaces." - } + description: "Indent with tabs instead of spaces.", + }, }; module.exports = { @@ -250,5 +256,5 @@ module.exports = { CATEGORY_OUTPUT, CATEGORY_GLOBAL, CATEGORY_SPECIAL, - options + options, }; diff --git a/src/main/core.js b/src/main/core.js index 9205eb4d6..6e9dc42ec 100644 --- a/src/main/core.js +++ b/src/main/core.js @@ -9,14 +9,14 @@ const parser = require("./parser"); const printAstToDoc = require("./ast-to-doc"); const { guessEndOfLine, - convertEndOfLineToChars + convertEndOfLineToChars, } = require("../common/end-of-line"); const rangeUtil = require("./range-util"); const privateUtil = require("../common/util"); const { utils: { mapDoc }, printer: { printDocToString }, - debug: { printDocToDebug } + debug: { printDocToDebug }, } = require("../document"); const BOM = "\uFEFF"; @@ -25,7 +25,7 @@ const CURSOR = Symbol("cursor"); const PLACEHOLDERS = { cursorOffset: "<<>>", rangeStart: "<<>>", - rangeEnd: "<<>>" + rangeEnd: "<<>>", }; function ensureAllCommentsPrinted(astComments) { @@ -41,7 +41,7 @@ function ensureAllCommentsPrinted(astComments) { } } - astComments.forEach(comment => { + astComments.forEach((comment) => { if (!comment.printed) { throw new Error( 'Comment "' + @@ -89,7 +89,7 @@ function coreFormat(text, opts, addAlignmentSize) { const result = printDocToString( opts.endOfLine === "lf" ? doc - : mapDoc(doc, currentDoc => + : mapDoc(doc, (currentDoc) => typeof currentDoc === "string" && currentDoc.includes("\n") ? currentDoc.replace(/\n/g, eol) : currentDoc @@ -143,7 +143,7 @@ function coreFormat(text, opts, addAlignmentSize) { if (oldCursorNodeText === newCursorNodeText) { return { formatted: result.formatted, - cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode + cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode, }; } @@ -214,7 +214,7 @@ function formatRange(text, opts) { cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart - : -1 + : -1, }, alignmentSize ); @@ -297,7 +297,7 @@ function format(text, opts) { const offsetKeys = [ hasCursor && "cursorOffset", hasRangeStart && "rangeStart", - hasRangeEnd && "rangeEnd" + hasRangeEnd && "rangeEnd", ] .filter(Boolean) .sort((aKey, bKey) => opts[aKey] - opts[bKey]); @@ -406,5 +406,5 @@ module.exports = { printDocToString(doc, opts) { return printDocToString(doc, normalizeOptions(opts)); - } + }, }; diff --git a/src/main/massage-ast.js b/src/main/massage-ast.js index 3bfeb2828..c3f5383d2 100644 --- a/src/main/massage-ast.js +++ b/src/main/massage-ast.js @@ -2,7 +2,7 @@ function massageAST(ast, options, parent) { if (Array.isArray(ast)) { - return ast.map(e => massageAST(e, options, parent)).filter(Boolean); + return ast.map((e) => massageAST(e, options, parent)).filter(Boolean); } if (!ast || typeof ast !== "object") { diff --git a/src/main/multiparser.js b/src/main/multiparser.js index 8af07b172..aedf52b04 100644 --- a/src/main/multiparser.js +++ b/src/main/multiparser.js @@ -28,7 +28,7 @@ function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) { parentOptions.parser === "angular" || parentOptions.parser === "lwc" ), - originalText: text + originalText: text, }, { passThrough: true } ); @@ -44,5 +44,5 @@ function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) { } module.exports = { - printSubtree + printSubtree, }; diff --git a/src/main/options-normalizer.js b/src/main/options-normalizer.js index 9ca816ad0..fc5d86540 100644 --- a/src/main/options-normalizer.js +++ b/src/main/options-normalizer.js @@ -5,8 +5,8 @@ const leven = require("leven"); const chalk = require("chalk"); const cliDescriptor = { - key: key => (key.length === 1 ? `-${key}` : `--${key}`), - value: value => vnopts.apiDescriptor.value(value), + key: (key) => (key.length === 1 ? `-${key}` : `--${key}`), + value: (value) => vnopts.apiDescriptor.value(value), pair: ({ key, value }) => value === false ? `--no-${key}` @@ -14,7 +14,7 @@ const cliDescriptor = { ? cliDescriptor.key(key) : value === "" ? `${cliDescriptor.key(key)} without an argument` - : `${cliDescriptor.key(key)}=${value}` + : `${cliDescriptor.key(key)}=${value}`, }; class FlagSchema extends vnopts.ChoiceSchema { @@ -28,12 +28,12 @@ class FlagSchema extends vnopts.ChoiceSchema { value.length !== 0 && !this._flags.includes(value) ) { - const suggestion = this._flags.find(flag => leven(flag, value) < 3); + const suggestion = this._flags.find((flag) => leven(flag, value) < 3); if (suggestion) { utils.logger.warn( [ `Unknown flag ${chalk.yellow(utils.descriptor.value(value))},`, - `did you mean ${chalk.blue(utils.descriptor.value(suggestion))}?` + `did you mean ${chalk.blue(utils.descriptor.value(suggestion))}?`, ].join(" ") ); return suggestion; @@ -65,7 +65,7 @@ function normalizeOptions( const normalizer = new vnopts.Normalizer(schemas, { logger, unknown, - descriptor + descriptor, }); const shouldSuppressDuplicateDeprecationWarnings = logger !== false; @@ -97,7 +97,7 @@ function optionInfosToSchemas(optionInfos, { isCLI }) { schemas.push( vnopts.AliasSchema.create({ name: optionInfo.alias, - sourceName: optionInfo.name + sourceName: optionInfo.name, }) ); } @@ -115,7 +115,7 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos }) { case "int": SchemaConstructor = vnopts.IntegerSchema; if (isCLI) { - parameters.preprocess = value => Number(value); + parameters.preprocess = (value) => Number(value); } break; case "string": @@ -123,13 +123,13 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos }) { break; case "choice": SchemaConstructor = vnopts.ChoiceSchema; - parameters.choices = optionInfo.choices.map(choiceInfo => + parameters.choices = optionInfo.choices.map((choiceInfo) => typeof choiceInfo === "object" && choiceInfo.redirect ? { ...choiceInfo, redirect: { - to: { key: optionInfo.name, value: choiceInfo.redirect } - } + to: { key: optionInfo.name, value: choiceInfo.redirect }, + }, } : choiceInfo ); @@ -140,7 +140,7 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos }) { case "flag": SchemaConstructor = FlagSchema; parameters.flags = optionInfos - .map(optionInfo => + .map((optionInfo) => [].concat( optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], @@ -167,14 +167,14 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos }) { } if (optionInfo.redirect) { - handlers.redirect = value => + handlers.redirect = (value) => !value ? undefined : { to: { key: optionInfo.redirect.option, - value: optionInfo.redirect.value - } + value: optionInfo.redirect.value, + }, }; } @@ -184,7 +184,7 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos }) { // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2 if (isCLI && !optionInfo.array) { - const originalPreprocess = parameters.preprocess || (x => x); + const originalPreprocess = parameters.preprocess || ((x) => x); parameters.preprocess = (value, schema, utils) => schema.preprocess( originalPreprocess( @@ -196,9 +196,9 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos }) { return optionInfo.array ? vnopts.ArraySchema.create({ - ...(isCLI ? { preprocess: v => [].concat(v) } : {}), + ...(isCLI ? { preprocess: (v) => [].concat(v) } : {}), ...handlers, - valueSchema: SchemaConstructor.create(parameters) + valueSchema: SchemaConstructor.create(parameters), }) : SchemaConstructor.create({ ...parameters, ...handlers }); } @@ -213,5 +213,5 @@ function normalizeCliOptions(options, optionInfos, opts) { module.exports = { normalizeApiOptions, - normalizeCliOptions + normalizeCliOptions, }; diff --git a/src/main/options.js b/src/main/options.js index 37c3887b3..18e9e614d 100644 --- a/src/main/options.js +++ b/src/main/options.js @@ -14,7 +14,7 @@ const hiddenDefaults = { printer: {}, originalText: undefined, locStart: null, - locEnd: null + locEnd: null, }; // Copy options and fill in default values. @@ -26,16 +26,16 @@ function normalize(options, opts) { const supportOptions = getSupportInfo({ plugins: options.plugins, showUnreleased: true, - showDeprecated: true + showDeprecated: true, }).options; const defaults = { ...hiddenDefaults, ...fromPairs( supportOptions - .filter(optionInfo => optionInfo.default !== undefined) - .map(option => [option.name, option.default]) - ) + .filter((optionInfo) => optionInfo.default !== undefined) + .map((option) => [option.name, option.default]) + ), }; if (!rawOptions.parser) { if (!rawOptions.filepath) { @@ -59,7 +59,7 @@ function normalize(options, opts) { const parser = resolveParser( normalizer.normalizeApiOptions( rawOptions, - [supportOptions.find(x => x.name === "parser")], + [supportOptions.find((x) => x.name === "parser")], { passThrough: true, logger: false } ) ); @@ -72,21 +72,21 @@ function normalize(options, opts) { const pluginDefaults = supportOptions .filter( - optionInfo => + (optionInfo) => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined ) .reduce( (reduced, optionInfo) => Object.assign(reduced, { - [optionInfo.name]: optionInfo.pluginDefaults[plugin.name] + [optionInfo.name]: optionInfo.pluginDefaults[plugin.name], }), {} ); const mixedDefaults = { ...defaults, ...pluginDefaults }; - Object.keys(mixedDefaults).forEach(k => { + Object.keys(mixedDefaults).forEach((k) => { if (rawOptions[k] == null) { rawOptions[k] = mixedDefaults[k]; } @@ -98,7 +98,7 @@ function normalize(options, opts) { return normalizer.normalizeApiOptions(rawOptions, supportOptions, { passThrough: Object.keys(hiddenDefaults), - ...opts + ...opts, }); } @@ -109,7 +109,7 @@ function getPlugin(options) { throw new Error("getPlugin() requires astFormat to be set"); } const printerPlugin = options.plugins.find( - plugin => plugin.printers && plugin.printers[astFormat] + (plugin) => plugin.printers && plugin.printers[astFormat] ); if (!printerPlugin) { throw new Error(`Couldn't find plugin for AST format "${astFormat}"`); @@ -168,12 +168,14 @@ function inferParser(filepath, plugins) { // interpreter in the shebang line, if any; but since this requires FS access, // do it last. const language = getSupportInfo({ plugins }).languages.find( - language => + (language) => language.since !== null && ((language.extensions && - language.extensions.some(extension => filename.endsWith(extension))) || + language.extensions.some((extension) => + filename.endsWith(extension) + )) || (language.filenames && - language.filenames.find(name => name.toLowerCase() === filename)) || + language.filenames.find((name) => name.toLowerCase() === filename)) || (!filename.includes(".") && language.interpreters && language.interpreters.includes(getInterpreter(filepath)))) diff --git a/src/main/parser.js b/src/main/parser.js index 78dec0a4a..2347fc9c8 100644 --- a/src/main/parser.js +++ b/src/main/parser.js @@ -34,7 +34,7 @@ function resolveParser(opts, parsers) { parse: opts.parser, astFormat: "estree", locStart, - locEnd + locEnd, }; } @@ -54,7 +54,7 @@ function resolveParser(opts, parsers) { parse: eval("require")(path.resolve(process.cwd(), opts.parser)), astFormat: "estree", locStart, - locEnd + locEnd, }; } catch (err) { /* istanbul ignore next */ @@ -75,7 +75,7 @@ function parse(text, opts) { enumerable: true, get() { return parsers[parserName].parse; - } + }, }), {} ); @@ -89,7 +89,7 @@ function parse(text, opts) { return { text, - ast: parser.parse(text, parsersForCustomParserApi, opts) + ast: parser.parse(text, parsersForCustomParserApi, opts), }; } catch (error) { const { loc } = error; @@ -97,7 +97,7 @@ function parse(text, opts) { if (loc) { const codeFrame = require("@babel/code-frame"); error.codeFrame = codeFrame.codeFrameColumns(text, loc, { - highlightCode: true + highlightCode: true, }); error.message += "\n" + error.codeFrame; throw error; diff --git a/src/main/range-util.js b/src/main/range-util.js index 5fccdf18c..b66b82957 100644 --- a/src/main/range-util.js +++ b/src/main/range-util.js @@ -9,7 +9,7 @@ function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { if (resultStartNode === resultEndNode) { return { startNode: resultStartNode, - endNode: resultEndNode + endNode: resultEndNode, }; } @@ -39,7 +39,7 @@ function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { return { startNode: resultStartNode, - endNode: resultEndNode + endNode: resultEndNode, }; } @@ -65,7 +65,7 @@ function findNodeAtOffset(node, offset, options, predicate, parentNodes) { if (predicate(node)) { return { node, - parentNodes + parentNodes, }; } } @@ -106,7 +106,7 @@ function isSourceElement(opts, node) { "InterfaceDeclaration", // Flow, TypeScript "TypeAliasDeclaration", // TypeScript "ExportAssignment", // TypeScript - "ExportDeclaration" // TypeScript + "ExportDeclaration", // TypeScript ]; const jsonSourceElements = [ "ObjectExpression", @@ -114,7 +114,7 @@ function isSourceElement(opts, node) { "StringLiteral", "NumericLiteral", "BooleanLiteral", - "NullLiteral" + "NullLiteral", ]; const graphqlSourceElements = [ "OperationDefinition", @@ -132,7 +132,7 @@ function isSourceElement(opts, node) { "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", - "ScalarTypeDefinition" + "ScalarTypeDefinition", ]; switch (opts.parser) { case "flow": @@ -174,19 +174,19 @@ function calculateRange(text, opts, ast) { ast, startNonWhitespace, opts, - node => isSourceElement(opts, node) + (node) => isSourceElement(opts, node) ); const endNodeAndParents = findNodeAtOffset( ast, endNonWhitespace, opts, - node => isSourceElement(opts, node) + (node) => isSourceElement(opts, node) ); if (!startNodeAndParents || !endNodeAndParents) { return { rangeStart: 0, - rangeEnd: 0 + rangeEnd: 0, }; } @@ -207,11 +207,11 @@ function calculateRange(text, opts, ast) { return { rangeStart, - rangeEnd + rangeEnd, }; } module.exports = { calculateRange, - findNodeAtOffset + findNodeAtOffset, }; diff --git a/src/main/support.js b/src/main/support.js index d67dd8b02..f1d0e54d2 100644 --- a/src/main/support.js +++ b/src/main/support.js @@ -3,7 +3,7 @@ const semver = { compare: require("semver/functions/compare"), lt: require("semver/functions/lt"), - gte: require("semver/functions/gte") + gte: require("semver/functions/gte"), }; const arrayify = require("../utils/arrayify"); const currentVersion = require("../../package.json").version; @@ -23,7 +23,7 @@ function getSupportInfo({ plugins = [], showUnreleased = false, showDeprecated = false, - showInternal = false + showInternal = false, } = {}) { // pre-release version is smaller than the normal version in semver, // we need to treat it as the normal one so as to test new features. @@ -33,10 +33,10 @@ function getSupportInfo({ Object.assign({}, ...plugins.map(({ options }) => options), coreOptions), "name" ) - .filter(option => filterSince(option) && filterDeprecated(option)) + .filter((option) => filterSince(option) && filterDeprecated(option)) .sort((a, b) => (a.name === b.name ? 0 : a.name < b.name ? -1 : 1)) .map(mapInternal) - .map(option => { + .map((option) => { option = { ...option }; if (Array.isArray(option.default)) { @@ -52,12 +52,12 @@ function getSupportInfo({ if (Array.isArray(option.choices)) { option.choices = option.choices.filter( - option => filterSince(option) && filterDeprecated(option) + (option) => filterSince(option) && filterDeprecated(option) ); } const filteredPlugins = plugins.filter( - plugin => + (plugin) => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined ); @@ -102,5 +102,5 @@ function getSupportInfo({ } module.exports = { - getSupportInfo + getSupportInfo, }; diff --git a/src/standalone.js b/src/standalone.js index bb33c9ef0..42062f428 100644 --- a/src/standalone.js +++ b/src/standalone.js @@ -15,7 +15,7 @@ const internalPlugins = [ require("./language-html"), require("./language-js"), require("./language-markdown"), - require("./language-yaml") + require("./language-yaml"), ]; function withPlugins( @@ -30,8 +30,8 @@ function withPlugins( ...opts, plugins: [ ...internalPlugins, - ...(Array.isArray(plugins) ? plugins : Object.values(plugins)) - ] + ...(Array.isArray(plugins) ? plugins : Object.values(plugins)), + ], }; return fn(...args); @@ -65,6 +65,6 @@ module.exports = { formatAST: withPlugins(core.formatAST), formatDoc: withPlugins(core.formatDoc), printToDoc: withPlugins(core.printToDoc), - printDocToString: withPlugins(core.printDocToString) - } + printDocToString: withPlugins(core.printDocToString), + }, }; diff --git a/src/utils/arrayify.js b/src/utils/arrayify.js index 7f3b40931..6cd24da84 100644 --- a/src/utils/arrayify.js +++ b/src/utils/arrayify.js @@ -3,5 +3,5 @@ module.exports = (object, keyName) => Object.entries(object).map(([key, value]) => ({ [keyName]: key, - ...value + ...value, })); diff --git a/src/utils/create-language.js b/src/utils/create-language.js index b059ecbd7..37ed075aa 100644 --- a/src/utils/create-language.js +++ b/src/utils/create-language.js @@ -1,10 +1,10 @@ "use strict"; -module.exports = function(linguistData, override) { +module.exports = function (linguistData, override) { const { languageId, ...rest } = linguistData; return { linguistLanguageId: languageId, ...rest, - ...override(linguistData) + ...override(linguistData), }; }; diff --git a/src/utils/front-matter.js b/src/utils/front-matter.js index 1d525d209..1fd8446c4 100644 --- a/src/utils/front-matter.js +++ b/src/utils/front-matter.js @@ -4,13 +4,11 @@ const escape = require("escape-string-regexp"); const DELIMITER_MAP = { "---": "yaml", - "+++": "toml" + "+++": "toml", }; function parse(text) { - const delimiterRegex = Object.keys(DELIMITER_MAP) - .map(escape) - .join("|"); + const delimiterRegex = Object.keys(DELIMITER_MAP).map(escape).join("|"); const match = text.match( // trailing spaces after delimiters are allowed @@ -29,9 +27,9 @@ function parse(text) { frontMatter: { type: DELIMITER_MAP[delimiter], value, - raw: raw.replace(/\n$/, "") + raw: raw.replace(/\n$/, ""), }, - content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length) + content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length), }; } diff --git a/src/utils/get-file-content-or-null.js b/src/utils/get-file-content-or-null.js index 2dabcd1cf..cdf93dcdb 100644 --- a/src/utils/get-file-content-or-null.js +++ b/src/utils/get-file-content-or-null.js @@ -22,7 +22,7 @@ function getFileContentOrNull(filename) { * @param {string} filename * @returns {null | string} */ -getFileContentOrNull.sync = function(filename) { +getFileContentOrNull.sync = function (filename) { try { return fs.readFileSync(filename, "utf8"); } catch (error) { diff --git a/src/utils/get-last.js b/src/utils/get-last.js index e36d00010..f7d19fafe 100644 --- a/src/utils/get-last.js +++ b/src/utils/get-last.js @@ -1,3 +1,3 @@ "use strict"; -module.exports = arr => arr[arr.length - 1]; +module.exports = (arr) => arr[arr.length - 1]; diff --git a/src/utils/line-column-to-index.js b/src/utils/line-column-to-index.js index 78f07e752..1cb72bbad 100644 --- a/src/utils/line-column-to-index.js +++ b/src/utils/line-column-to-index.js @@ -1,7 +1,7 @@ "use strict"; // Super inefficient, needs to be cached. -module.exports = function(lineColumn, text) { +module.exports = function (lineColumn, text) { let index = 0; for (let i = 0; i < lineColumn.line - 1; ++i) { index = text.indexOf("\n", index) + 1; diff --git a/src/utils/load-toml.js b/src/utils/load-toml.js index f8b5c7c79..59c475456 100644 --- a/src/utils/load-toml.js +++ b/src/utils/load-toml.js @@ -2,7 +2,7 @@ const parse = require("@iarna/toml/parse-string"); -module.exports = function(filePath, content) { +module.exports = function (filePath, content) { try { return parse(content); } catch (error) { diff --git a/tests_config/require_standalone.js b/tests_config/require_standalone.js index 03bc07024..6f06f1a03 100644 --- a/tests_config/require_standalone.js +++ b/tests_config/require_standalone.js @@ -15,8 +15,8 @@ const sources = [ "parser-markdown.js", "parser-postcss.js", "parser-typescript.js", - "parser-yaml.js" -].map(filename => + "parser-yaml.js", +].map((filename) => fs.readFileSync(path.join(process.env.PRETTIER_DIR, filename), "utf-8") ); @@ -46,6 +46,6 @@ module.exports = { );`, { $$$input: input, $$$options: options, ...sandbox } ); - } - } + }, + }, }; diff --git a/tests_config/run_spec.js b/tests_config/run_spec.js index bde58f06c..91ebfa432 100644 --- a/tests_config/run_spec.js +++ b/tests_config/run_spec.js @@ -21,8 +21,8 @@ const prettier = !TEST_STANDALONE const unstableTests = new Map( [ "class_comment/comments.js", - ["comments/dangling_array.js", options => options.semi === false], - ["comments/jsx.js", options => options.semi === false], + ["comments/dangling_array.js", (options) => options.semi === false], + ["comments/jsx.js", (options) => options.semi === false], "comments/return-statement.js", "comments/tagged-template-literal.js", "comments_closure_typecast/iife.js", @@ -30,7 +30,7 @@ const unstableTests = new Map( "graphql_interface/separator-detection.graphql", [ "html_angular/attributes.component.html", - options => options.printWidth === 1 + (options) => options.printWidth === 1, ], "html_prettier_ignore/cases.html", "js_empty/semicolon.js", @@ -41,11 +41,11 @@ const unstableTests = new Map( "multiparser_html_js/script-tag-escaping.html", [ "multiparser_js_markdown/codeblock.js", - options => options.proseWrap === "always" + (options) => options.proseWrap === "always", ], - ["no-semi/comments.js", options => options.semi === false], - "yaml_prettier_ignore/document.yml" - ].map(fixture => { + ["no-semi/comments.js", (options) => options.semi === false], + "yaml_prettier_ignore/document.yml", + ].map((fixture) => { const [file, isUnstable = () => true] = Array.isArray(fixture) ? fixture : [fixture]; @@ -102,13 +102,13 @@ global.run_spec = (dirname, parsers, options) => { ...options, rangeStart, rangeEnd, - cursorOffset + cursorOffset, }; const mainOptions = { ...baseOptions, ...(IS_PARSER_INFERENCE_TESTS ? { filepath: filename } - : { parser: parsers[0] }) + : { parser: parsers[0] }), }; const hasEndOfLine = "endOfLine" in mainOptions; @@ -210,7 +210,7 @@ function parse(source, options) { function format(source, filename, options) { const result = prettier.formatWithCursor(source, { filepath: filename, - ...options + ...options, }); return options.cursorOffset >= 0 @@ -222,7 +222,7 @@ function format(source, filename, options) { function consistentEndOfLine(text) { let firstEndOfLine; - return text.replace(/\r\n?|\n/g, endOfLine => { + return text.replace(/\r\n?|\n/g, (endOfLine) => { if (!firstEndOfLine) { firstEndOfLine = endOfLine; } @@ -231,7 +231,7 @@ function consistentEndOfLine(text) { } function visualizeEndOfLine(text) { - return text.replace(/\r\n?|\n/g, endOfLine => { + return text.replace(/\r\n?|\n/g, (endOfLine) => { switch (endOfLine) { case "\n": return "\n"; @@ -257,7 +257,7 @@ function createSnapshot(input, output, options) { printOptions( omit( options, - k => + (k) => k === "rangeStart" || k === "rangeEnd" || k === "cursorOffset" || @@ -283,12 +283,12 @@ function printSeparator(width, description) { function printOptions(options) { const keys = Object.keys(options).sort(); - return keys.map(key => `${key}: ${stringify(options[key])}`).join("\n"); + return keys.map((key) => `${key}: ${stringify(options[key])}`).join("\n"); function stringify(value) { return value === Infinity ? "Infinity" : Array.isArray(value) - ? `[${value.map(v => JSON.stringify(v)).join(", ")}]` + ? `[${value.map((v) => JSON.stringify(v)).join(", ")}]` : JSON.stringify(value); } } diff --git a/tests_integration/__tests__/arg-parsing.js b/tests_integration/__tests__/arg-parsing.js index bd0f31022..08002abb2 100644 --- a/tests_integration/__tests__/arg-parsing.js +++ b/tests_integration/__tests__/arg-parsing.js @@ -7,9 +7,9 @@ describe("boolean flags do not swallow the next argument", () => { "--end-of-line", "lf", "--single-quote", - "file.js" + "file.js", ]).test({ - status: 0 + status: 0, }); }); @@ -18,9 +18,9 @@ describe("negated options work", () => { "--end-of-line", "lf", "--no-semi", - "file.js" + "file.js", ]).test({ - status: 0 + status: 0, }); }); @@ -29,9 +29,9 @@ describe("unknown options are warned", () => { "--end-of-line", "lf", "file.js", - "--unknown" + "--unknown", ]).test({ - status: 0 + status: 0, }); }); @@ -40,9 +40,9 @@ describe("unknown negated options are warned", () => { "--end-of-line", "lf", "file.js", - "--no-unknown" + "--no-unknown", ]).test({ - status: 0 + status: 0, }); }); @@ -53,6 +53,6 @@ describe("allow overriding flags", () => { { input: "function a() { b }" } ).test({ stdout: "function a() {\n b;\n}\n", - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/check.js b/tests_integration/__tests__/check.js index aff86e6ec..4868980ef 100644 --- a/tests_integration/__tests__/check.js +++ b/tests_integration/__tests__/check.js @@ -4,21 +4,21 @@ const runPrettier = require("../runPrettier"); describe("checks stdin with --check", () => { runPrettier("cli/with-shebang", ["--check", "--parser", "babel"], { - input: "0" + input: "0", }).test({ stdout: "(stdin)\n", stderr: "", - status: "non-zero" + status: "non-zero", }); }); describe("checks stdin with -c (alias for --check)", () => { runPrettier("cli/with-shebang", ["-c", "--parser", "babel"], { - input: "0" + input: "0", }).test({ stdout: "(stdin)\n", stderr: "", - status: "non-zero" + status: "non-zero", }); }); @@ -28,22 +28,22 @@ describe("--checks works in CI just as in a non-TTY mode", () => { ["--check", "formatted.js", "unformatted.js"], { env: { - CI: "true" + CI: "true", }, - stdoutIsTTY: true + stdoutIsTTY: true, } ).test({ - status: 1 + status: 1, }); const result1 = runPrettier( "cli/write", ["--check", "formatted.js", "unformatted.js"], { - stdoutIsTTY: false + stdoutIsTTY: false, } ).test({ - status: 1 + status: 1, }); expect(result0.stdout).toEqual(result1.stdout); diff --git a/tests_integration/__tests__/config-invalid.js b/tests_integration/__tests__/config-invalid.js index 3049e50e2..a7a264615 100644 --- a/tests_integration/__tests__/config-invalid.js +++ b/tests_integration/__tests__/config-invalid.js @@ -7,45 +7,45 @@ expect.addSnapshotSerializer(require("../path-serializer")); describe("throw error for unsupported extension", () => { runPrettier("cli/config/invalid", [ "--config", - "file/.prettierrc.unsupported" + "file/.prettierrc.unsupported", ]).test({ - status: "non-zero" + status: "non-zero", }); }); describe("throw error with invalid config format", () => { runPrettier("cli/config/invalid", ["--config", "file/.prettierrc"]).test({ - status: "non-zero" + status: "non-zero", }); }); describe("throw error with invalid config target (directory)", () => { runPrettier("cli/config/invalid", [ "--config", - "folder/.prettierrc" // this is a directory + "folder/.prettierrc", // this is a directory ]).test({ - status: "non-zero" + status: "non-zero", }); }); describe("throw error with invalid config option (int)", () => { runPrettier("cli/config/invalid", ["--config", "option/int"]).test({ - status: "non-zero" + status: "non-zero", }); }); describe("throw error with invalid config option (trailingComma)", () => { runPrettier("cli/config/invalid", ["--config", "option/trailingComma"]).test({ - status: "non-zero" + status: "non-zero", }); }); describe("throw error with invalid config precedence option (configPrecedence)", () => { runPrettier("cli/config/invalid", [ "--config-precedence", - "option/configPrecedence" + "option/configPrecedence", ]).test({ - status: "non-zero" + status: "non-zero", }); }); @@ -56,9 +56,9 @@ describe("show warning with unknown option", () => { "--config", "option/unknown", "--parser", - "babel" + "babel", ]).test({ - status: 0 + status: 0, }); }); @@ -67,8 +67,8 @@ describe("show warning with kebab-case option key", () => { "--config", "option/kebab-case", "--parser", - "babel" + "babel", ]).test({ - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/config-resolution.js b/tests_integration/__tests__/config-resolution.js index 841c9f3ce..f54875426 100644 --- a/tests_integration/__tests__/config-resolution.js +++ b/tests_integration/__tests__/config-resolution.js @@ -9,49 +9,49 @@ expect.addSnapshotSerializer(require("../path-serializer")); describe("resolves configuration from external files", () => { runPrettier("cli/config/", ["--end-of-line", "lf", "**/*.js"]).test({ - status: 0 + status: 0, }); }); describe("resolves configuration from external files and overrides by extname", () => { runPrettier("cli/config/", ["--end-of-line", "lf", "**/*.ts"]).test({ - status: 0 + status: 0, }); }); describe("accepts configuration from --config", () => { runPrettier("cli/config/", ["--config", ".prettierrc", "./js/file.js"]).test({ - status: 0 + status: 0, }); }); describe("resolves external configuration from package.json", () => { runPrettier("cli/config/", ["external-config/index.js"]).test({ - status: 0 + status: 0, }); }); describe("resolves configuration file with --find-config-path file", () => { runPrettier("cli/config/", ["--find-config-path", "no-config/file.js"]).test({ - status: 0 + status: 0, }); }); describe("resolves json configuration file with --find-config-path file", () => { runPrettier("cli/config/", ["--find-config-path", "rc-json/file.js"]).test({ - status: 0 + status: 0, }); }); describe("resolves yaml configuration file with --find-config-path file", () => { runPrettier("cli/config/", ["--find-config-path", "rc-yaml/file.js"]).test({ - status: 0 + status: 0, }); }); describe("resolves toml configuration file with --find-config-path file", () => { runPrettier("cli/config/", ["--find-config-path", "rc-toml/file.js"]).test({ - status: 0 + status: 0, }); }); @@ -60,10 +60,10 @@ describe("prints nothing when no file found with --find-config-path", () => { "--end-of-line", "lf", "--find-config-path", - ".." + "..", ]).test({ stdout: "", - status: 1 + status: 1, }); }); @@ -73,14 +73,14 @@ describe("CLI overrides take precedence", () => { "lf", "--print-width", "1", - "**/*.js" + "**/*.js", ]).test({ - status: 0 + status: 0, }); }); test("API resolveConfig with no args", () => { - return prettier.resolveConfig().then(result => { + return prettier.resolveConfig().then((result) => { expect(result).toEqual({}); }); }); @@ -91,9 +91,9 @@ test("API resolveConfig.sync with no args", () => { test("API resolveConfig with file arg", () => { const file = path.resolve(path.join(__dirname, "../cli/config/js/file.js")); - return prettier.resolveConfig(file).then(result => { + return prettier.resolveConfig(file).then((result) => { expect(result).toMatchObject({ - tabWidth: 8 + tabWidth: 8, }); }); }); @@ -101,7 +101,7 @@ test("API resolveConfig with file arg", () => { test("API resolveConfig.sync with file arg", () => { const file = path.resolve(path.join(__dirname, "../cli/config/js/file.js")); expect(prettier.resolveConfig.sync(file)).toMatchObject({ - tabWidth: 8 + tabWidth: 8, }); }); @@ -109,9 +109,9 @@ test("API resolveConfig with file arg and extension override", () => { const file = path.resolve( path.join(__dirname, "../cli/config/no-config/file.ts") ); - return prettier.resolveConfig(file).then(result => { + return prettier.resolveConfig(file).then((result) => { expect(result).toMatchObject({ - semi: true + semi: true, }); }); }); @@ -121,7 +121,7 @@ test("API resolveConfig.sync with file arg and extension override", () => { path.join(__dirname, "../cli/config/no-config/file.ts") ); expect(prettier.resolveConfig.sync(file)).toMatchObject({ - semi: true + semi: true, }); }); @@ -129,11 +129,11 @@ test("API resolveConfig with file arg and .editorconfig", () => { const file = path.resolve( path.join(__dirname, "../cli/config/editorconfig/file.js") ); - return prettier.resolveConfig(file, { editorconfig: true }).then(result => { + return prettier.resolveConfig(file, { editorconfig: true }).then((result) => { expect(result).toMatchObject({ useTabs: true, tabWidth: 8, - printWidth: 100 + printWidth: 100, }); }); }); @@ -144,7 +144,7 @@ test("API resolveConfig.sync with file arg and .editorconfig", () => { ); expect(prettier.resolveConfig.sync(file)).toMatchObject({ - semi: false + semi: false, }); expect( @@ -152,7 +152,7 @@ test("API resolveConfig.sync with file arg and .editorconfig", () => { ).toMatchObject({ useTabs: true, tabWidth: 8, - printWidth: 100 + printWidth: 100, }); }); @@ -170,11 +170,11 @@ test("API resolveConfig with nested file arg and .editorconfig", () => { const file = path.resolve( path.join(__dirname, "../cli/config/editorconfig/lib/file.js") ); - return prettier.resolveConfig(file, { editorconfig: true }).then(result => { + return prettier.resolveConfig(file, { editorconfig: true }).then((result) => { expect(result).toMatchObject({ useTabs: false, tabWidth: 2, - printWidth: 100 + printWidth: 100, }); }); }); @@ -185,7 +185,7 @@ test("API resolveConfig.sync with nested file arg and .editorconfig", () => { ); expect(prettier.resolveConfig.sync(file)).toMatchObject({ - semi: false + semi: false, }); expect( @@ -193,7 +193,7 @@ test("API resolveConfig.sync with nested file arg and .editorconfig", () => { ).toMatchObject({ useTabs: false, tabWidth: 2, - printWidth: 100 + printWidth: 100, }); }); @@ -201,11 +201,11 @@ test("API resolveConfig with nested file arg and .editorconfig and indent_size = const file = path.resolve( path.join(__dirname, "../cli/config/editorconfig/lib/indent_size=tab.js") ); - return prettier.resolveConfig(file, { editorconfig: true }).then(result => { + return prettier.resolveConfig(file, { editorconfig: true }).then((result) => { expect(result).toMatchObject({ useTabs: false, tabWidth: 8, - printWidth: 100 + printWidth: 100, }); }); }); @@ -216,7 +216,7 @@ test("API resolveConfig.sync with nested file arg and .editorconfig and indent_s ); expect(prettier.resolveConfig.sync(file)).toMatchObject({ - semi: false + semi: false, }); expect( @@ -224,7 +224,7 @@ test("API resolveConfig.sync with nested file arg and .editorconfig and indent_s ).toMatchObject({ useTabs: false, tabWidth: 8, - printWidth: 100 + printWidth: 100, }); }); @@ -237,7 +237,7 @@ test("API resolveConfig overrides work with dotfiles", () => { return expect( prettier.resolveConfig(path.join(folder, ".foo.json")) ).resolves.toMatchObject({ - tabWidth: 4 + tabWidth: 4, }); }); @@ -245,7 +245,7 @@ test("API resolveConfig.sync overrides work with absolute paths", () => { // Absolute path const file = path.join(__dirname, "../cli/config/filepath/subfolder/file.js"); expect(prettier.resolveConfig.sync(file)).toMatchObject({ - tabWidth: 6 + tabWidth: 6, }); }); @@ -253,9 +253,9 @@ test("API resolveConfig removes $schema option", () => { const file = path.resolve( path.join(__dirname, "../cli/config/$schema/index.js") ); - return prettier.resolveConfig(file).then(result => { + return prettier.resolveConfig(file).then((result) => { expect(result).toEqual({ - tabWidth: 42 + tabWidth: 42, }); }); }); @@ -265,7 +265,7 @@ test("API resolveConfig.sync removes $schema option", () => { path.join(__dirname, "../cli/config/$schema/index.js") ); expect(prettier.resolveConfig.sync(file)).toEqual({ - tabWidth: 42 + tabWidth: 42, }); }); @@ -274,7 +274,7 @@ test("API resolveConfig resolves relative path values based on config filepath", const parentDir = path.resolve(currentDir, ".."); expect(prettier.resolveConfig.sync(`${currentDir}/index.js`)).toMatchObject({ plugins: [path.join(parentDir, "path-to-plugin")], - pluginSearchDirs: [path.join(parentDir, "path-to-plugin-search-dir")] + pluginSearchDirs: [path.join(parentDir, "path-to-plugin-search-dir")], }); }); @@ -282,6 +282,6 @@ test("API resolveConfig de-references to an external module", () => { const currentDir = path.join(__dirname, "../cli/config/external-config"); expect(prettier.resolveConfig.sync(`${currentDir}/index.js`)).toEqual({ printWidth: 77, - semi: false + semi: false, }); }); diff --git a/tests_integration/__tests__/cursor-offset.js b/tests_integration/__tests__/cursor-offset.js index f5faeed82..172febb45 100644 --- a/tests_integration/__tests__/cursor-offset.js +++ b/tests_integration/__tests__/cursor-offset.js @@ -4,16 +4,16 @@ const runPrettier = require("../runPrettier"); describe("write cursorOffset to stderr with --cursor-offset ", () => { runPrettier("cli", ["--cursor-offset", "2", "--parser", "babel"], { - input: " 1" + input: " 1", }).test({ - status: 0 + status: 0, }); }); describe("cursorOffset should not be affected by full-width character", () => { runPrettier("cli", ["--cursor-offset", "21", "--parser", "babel"], { input: - 'const x = ["中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文"];' + 'const x = ["中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文"];', // ^ offset = 21 ^ width = 80 }).test({ /** @@ -33,6 +33,6 @@ describe("cursorOffset should not be affected by full-width character", () => { * ]; */ stderr: "26\n", - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/debug-check.js b/tests_integration/__tests__/debug-check.js index f6336f97e..0e2a63c77 100644 --- a/tests_integration/__tests__/debug-check.js +++ b/tests_integration/__tests__/debug-check.js @@ -6,17 +6,17 @@ describe("doesn't crash when --debug-check is passed", () => { runPrettier("cli/with-shebang", ["issue1890.js", "--debug-check"]).test({ stdout: "issue1890.js\n", stderr: "", - status: 0 + status: 0, }); }); describe("checks stdin with --debug-check", () => { runPrettier("cli/with-shebang", ["--debug-check", "--parser", "babel"], { - input: "0" + input: "0", }).test({ stdout: "(stdin)\n", stderr: "", - status: 0 + status: 0, }); }); @@ -27,9 +27,9 @@ describe("show diff for 2+ error files with --debug-check", () => { "*.debug-check", "--debug-check", "--plugin", - "./plugin-for-testing-debug-check" + "./plugin-for-testing-debug-check", ]).test({ - status: "non-zero" + status: "non-zero", }); }); @@ -37,9 +37,9 @@ describe("should not exit non-zero for already prettified code with --debug-chec runPrettier("cli/debug-check", [ "issue-4599.js", "--debug-check", - "--check" + "--check", ]).test({ - status: 0 + status: 0, }); }); @@ -47,8 +47,8 @@ describe("should not exit non-zero for already prettified code with --debug-chec runPrettier("cli/debug-check", [ "issue-4599.js", "--debug-check", - "--list-different" + "--list-different", ]).test({ - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/debug-print-doc.js b/tests_integration/__tests__/debug-print-doc.js index b994c079b..074cbca57 100644 --- a/tests_integration/__tests__/debug-print-doc.js +++ b/tests_integration/__tests__/debug-print-doc.js @@ -4,10 +4,10 @@ const runPrettier = require("../runPrettier"); describe("prints doc with --debug-print-doc", () => { runPrettier("cli/with-shebang", ["--debug-print-doc", "--parser", "babel"], { - input: "0" + input: "0", }).test({ stdout: '["0", ";", hardline, breakParent];\n', stderr: "", - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/doc-mark-as-root.js b/tests_integration/__tests__/doc-mark-as-root.js index 15a3ea382..9c444f76c 100644 --- a/tests_integration/__tests__/doc-mark-as-root.js +++ b/tests_integration/__tests__/doc-mark-as-root.js @@ -12,18 +12,18 @@ describe("markAsRoot", () => { [ "with hardline will insert a newline with current indentation", concat([indent(markAsRoot(indent(hardline))), "123"]), - "\n 123" + "\n 123", ], [ "with literalline will insert a newline with root indentation", concat([indent(markAsRoot(indent(literalline))), "123"]), - "\n 123" + "\n 123", ], [ "followed by trim will trims up to the the first column, ignoring indented root", concat([indent(markAsRoot(indent(literalline))), trim, "123"]), - "\n123" - ] + "\n123", + ], ])("%s", (_, doc, expected) => { const result = printDocToString(doc, { printWidth: 80, tabWidth: 2 }); diff --git a/tests_integration/__tests__/doc-trim.js b/tests_integration/__tests__/doc-trim.js index ba4eb185e..ac4590ce2 100644 --- a/tests_integration/__tests__/doc-trim.js +++ b/tests_integration/__tests__/doc-trim.js @@ -27,11 +27,11 @@ describe("trim", () => { line, "alert(42);", line, - group(concat([trim, "#endif"])) + group(concat([trim, "#endif"])), ]) ), line, - "}" + "}", ]) ), `function() @@ -39,13 +39,13 @@ describe("trim", () => { #if DEBUG alert(42); #endif -}` +}`, ], [ "ignores trimmed characters when fitting the line", group(concat(["hello ", " ", trim, line, "world!"])), - "hello world!" - ] + "hello world!", + ], ])("%s", (_, doc, expected) => { const result = printDocToString(doc, { printWidth: 12, tabWidth: 2 }); diff --git a/tests_integration/__tests__/early-exit.js b/tests_integration/__tests__/early-exit.js index 9111cfafa..fa8ea94b2 100644 --- a/tests_integration/__tests__/early-exit.js +++ b/tests_integration/__tests__/early-exit.js @@ -6,19 +6,19 @@ const runPrettier = require("../runPrettier"); describe("show version with --version", () => { runPrettier("cli/with-shebang", ["--version"]).test({ stdout: prettier.version + "\n", - status: 0 + status: 0, }); }); describe("show usage with --help", () => { runPrettier("cli", ["--help"]).test({ - status: 0 + status: 0, }); }); describe("show detailed usage with --help l (alias)", () => { runPrettier("cli", ["--help", "l"]).test({ - status: 0 + status: 0, }); }); @@ -27,9 +27,9 @@ describe("show detailed usage with plugin options (automatic resolution)", () => "--help", "tab-width", "--parser=bar", - "--plugin-search-dir=." + "--plugin-search-dir=.", ]).test({ - status: 0 + status: 0, }); }); @@ -38,50 +38,50 @@ describe("show detailed usage with plugin options (manual resolution)", () => { "--help", "tab-width", "--plugin=../plugins/automatic/node_modules/prettier-plugin-bar", - "--parser=bar" + "--parser=bar", ]).test({ - status: 0 + status: 0, }); }); describe("throw error with --help not-found", () => { runPrettier("cli", ["--help", "not-found"]).test({ - status: 1 + status: 1, }); }); describe("show warning with --help not-found (typo)", () => { runPrettier("cli", ["--help", "parserr"]).test({ - status: 0 + status: 0, }); }); describe("throw error with --check + --list-different", () => { runPrettier("cli", ["--check", "--list-different"]).test({ - status: 1 + status: 1, }); }); describe("throw error with --write + --debug-check", () => { runPrettier("cli", ["--write", "--debug-check"]).test({ - status: 1 + status: 1, }); }); describe("throw error with --find-config-path + multiple files", () => { runPrettier("cli", ["--find-config-path", "abc.js", "def.js"]).test({ - status: 1 + status: 1, }); }); describe("throw error with --file-info + multiple files", () => { runPrettier("cli", ["--file-info", "abc.js", "def.js"]).test({ - status: 1 + status: 1, }); }); describe("throw error and show usage with something unexpected", () => { runPrettier("cli", [], { isTTY: true }).test({ - status: "non-zero" + status: "non-zero", }); }); diff --git a/tests_integration/__tests__/file-info.js b/tests_integration/__tests__/file-info.js index af327817c..77baea946 100644 --- a/tests_integration/__tests__/file-info.js +++ b/tests_integration/__tests__/file-info.js @@ -11,25 +11,25 @@ expect.addSnapshotSerializer(require("../path-serializer")); describe("extracts file-info for a js file", () => { runPrettier("cli/", ["--file-info", "something.js"]).test({ - status: 0 + status: 0, }); }); describe("extracts file-info for a markdown file", () => { runPrettier("cli/", ["--file-info", "README.md"]).test({ - status: 0 + status: 0, }); }); describe("extracts file-info for a known markdown file with no extension", () => { runPrettier("cli/", ["--file-info", "README"]).test({ - status: 0 + status: 0, }); }); describe("extracts file-info with ignored=true for a file in .prettierignore", () => { runPrettier("cli/ignore-path/", ["--file-info", "regular-module.js"]).test({ - status: 0 + status: 0, }); }); @@ -37,27 +37,27 @@ describe("extracts file-info with ignored=true for a file in a hand-picked .pret runPrettier("cli/", [ "--file-info", "regular-module.js", - "--ignore-path=ignore-path/.prettierignore" + "--ignore-path=ignore-path/.prettierignore", ]).test({ - status: 0 + status: 0, }); }); describe("extracts file-info for a file in not_node_modules", () => { runPrettier("cli/with-node-modules/", [ "--file-info", - "not_node_modules/file.js" + "not_node_modules/file.js", ]).test({ - status: 0 + status: 0, }); }); describe("extracts file-info with with ignored=true for a file in node_modules", () => { runPrettier("cli/with-node-modules/", [ "--file-info", - "node_modules/file.js" + "node_modules/file.js", ]).test({ - status: 0 + status: 0, }); }); @@ -65,21 +65,21 @@ describe("extracts file-info with ignored=false for a file in node_modules when runPrettier("cli/with-node-modules/", [ "--file-info", "node_modules/file.js", - "--with-node-modules" + "--with-node-modules", ]).test({ - status: 0 + status: 0, }); }); describe("extracts file-info with inferredParser=null for file.foo", () => { runPrettier("cli/", ["--file-info", "file.foo"]).test({ - status: 0 + status: 0, }); }); describe("extracts file-info with inferredParser=foo when plugins are autoloaded", () => { runPrettier("plugins/automatic/", ["--file-info", "file.foo"]).test({ - status: 0 + status: 0, }); }); @@ -88,9 +88,9 @@ describe("extracts file-info with inferredParser=foo when plugins are loaded wit "--file-info", "file.foo", "--plugin-search-dir", - "../plugins/automatic" + "../plugins/automatic", ]).test({ - status: 0 + status: 0, }); }); @@ -99,9 +99,9 @@ describe("extracts file-info with inferredParser=foo when a plugin is hand-picke "--file-info", "file.foo", "--plugin", - "../plugins/automatic/node_modules/@prettier/plugin-foo" + "../plugins/automatic/node_modules/@prettier/plugin-foo", ]).test({ - status: 0 + status: 0, }); }); @@ -120,14 +120,14 @@ test("API getFileInfo.sync with no args", () => { test("API getFileInfo with filepath only", () => { expect(prettier.getFileInfo("README")).resolves.toMatchObject({ ignored: false, - inferredParser: "markdown" + inferredParser: "markdown", }); }); test("API getFileInfo.sync with filepath only", () => { expect(prettier.getFileInfo.sync("README")).toMatchObject({ ignored: false, - inferredParser: "markdown" + inferredParser: "markdown", }); }); @@ -141,27 +141,27 @@ test("API getFileInfo with resolveConfig", () => { expect(prettier.getFileInfo(file1)).resolves.toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect(prettier.getFileInfo(file2)).resolves.toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect( prettier.getFileInfo(file1, { - resolveConfig: true + resolveConfig: true, }) ).resolves.toMatchObject({ ignored: false, - inferredParser: "json" + inferredParser: "json", }); expect( prettier.getFileInfo(file2, { - resolveConfig: true + resolveConfig: true, }) ).resolves.toMatchObject({ ignored: false, - inferredParser: "babel" + inferredParser: "babel", }); }); @@ -175,27 +175,27 @@ test("API getFileInfo with resolveConfig when no config is present", () => { expect(prettier.getFileInfo(file1)).resolves.toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect(prettier.getFileInfo(file2)).resolves.toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect( prettier.getFileInfo(file1, { - resolveConfig: true + resolveConfig: true, }) ).resolves.toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect( prettier.getFileInfo(file2, { - resolveConfig: true + resolveConfig: true, }) ).resolves.toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); }); @@ -209,27 +209,27 @@ test("API getFileInfo.sync with resolveConfig", () => { expect(prettier.getFileInfo.sync(file1)).toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect(prettier.getFileInfo.sync(file2)).toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect( prettier.getFileInfo.sync(file1, { - resolveConfig: true + resolveConfig: true, }) ).toMatchObject({ ignored: false, - inferredParser: "json" + inferredParser: "json", }); expect( prettier.getFileInfo.sync(file2, { - resolveConfig: true + resolveConfig: true, }) ).toMatchObject({ ignored: false, - inferredParser: "babel" + inferredParser: "babel", }); }); @@ -243,27 +243,27 @@ test("API getFileInfo.sync with resolveConfig when no config is present", () => expect(prettier.getFileInfo.sync(file1)).toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect(prettier.getFileInfo.sync(file2)).toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect( prettier.getFileInfo.sync(file1, { - resolveConfig: true + resolveConfig: true, }) ).toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect( prettier.getFileInfo.sync(file2, { - resolveConfig: true + resolveConfig: true, }) ).toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); }); @@ -277,16 +277,16 @@ test("API getFileInfo with ignorePath", () => { expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: false, - inferredParser: "babel" + inferredParser: "babel", }); expect( prettier.getFileInfo(file, { - ignorePath + ignorePath, }) ).resolves.toMatchObject({ ignored: true, - inferredParser: "babel" + inferredParser: "babel", }); }); @@ -300,16 +300,16 @@ test("API getFileInfo.sync with ignorePath", () => { expect(prettier.getFileInfo.sync(file)).toMatchObject({ ignored: false, - inferredParser: "babel" + inferredParser: "babel", }); expect( prettier.getFileInfo.sync(file, { - ignorePath + ignorePath, }) ).toMatchObject({ ignored: true, - inferredParser: "babel" + inferredParser: "babel", }); }); @@ -353,15 +353,15 @@ test("API getFileInfo with withNodeModules", () => { ); expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: true, - inferredParser: "babel" + inferredParser: "babel", }); expect( prettier.getFileInfo(file, { - withNodeModules: true + withNodeModules: true, }) ).resolves.toMatchObject({ ignored: false, - inferredParser: "babel" + inferredParser: "babel", }); }); @@ -370,7 +370,7 @@ describe("extracts file-info for a JS file with no extension but a standard sheb prettier.getFileInfo.sync("tests_integration/cli/shebang/node-shebang") ).toMatchObject({ ignored: false, - inferredParser: "babel" + inferredParser: "babel", }); }); @@ -379,7 +379,7 @@ describe("extracts file-info for a JS file with no extension but an env-based sh prettier.getFileInfo.sync("tests_integration/cli/shebang/env-node-shebang") ).toMatchObject({ ignored: false, - inferredParser: "babel" + inferredParser: "babel", }); }); @@ -388,7 +388,7 @@ describe("returns null parser for unknown shebang", () => { prettier.getFileInfo.sync("tests_integration/cli/shebang/nonsense-shebang") ).toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); }); @@ -399,15 +399,15 @@ test("API getFileInfo with plugins loaded using pluginSearchDir", () => { ); expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect( prettier.getFileInfo(file, { - pluginSearchDirs: [pluginsPath] + pluginSearchDirs: [pluginsPath], }) ).resolves.toMatchObject({ ignored: false, - inferredParser: "foo" + inferredParser: "foo", }); }); @@ -421,14 +421,14 @@ test("API getFileInfo with hand-picked plugins", () => { ); expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: false, - inferredParser: null + inferredParser: null, }); expect( prettier.getFileInfo(file, { - plugins: [pluginPath] + plugins: [pluginPath], }) ).resolves.toMatchObject({ ignored: false, - inferredParser: "foo" + inferredParser: "foo", }); }); diff --git a/tests_integration/__tests__/help-options.js b/tests_integration/__tests__/help-options.js index 3fdb031a1..2c83b734e 100644 --- a/tests_integration/__tests__/help-options.js +++ b/tests_integration/__tests__/help-options.js @@ -12,22 +12,22 @@ arrayify( prettier.getSupportInfo({ showDeprecated: true, showUnreleased: true, - showInternal: true + showInternal: true, }).options ), - ...util.normalizeDetailedOptionMap(constant.options) + ...util.normalizeDetailedOptionMap(constant.options), }, "name" -).forEach(option => { +).forEach((option) => { const optionNames = [ option.description ? option.name : null, - option.oppositeDescription ? `no-${option.name}` : null + option.oppositeDescription ? `no-${option.name}` : null, ].filter(Boolean); - optionNames.forEach(optionName => { + optionNames.forEach((optionName) => { describe(`show detailed usage with --help ${optionName}`, () => { runPrettier("cli", ["--help", optionName]).test({ - status: 0 + status: 0, }); }); }); diff --git a/tests_integration/__tests__/ignore-absolute-path.js b/tests_integration/__tests__/ignore-absolute-path.js index a69714a77..5a7bdd6a6 100644 --- a/tests_integration/__tests__/ignore-absolute-path.js +++ b/tests_integration/__tests__/ignore-absolute-path.js @@ -8,8 +8,8 @@ describe("support absolute filename", () => { path.resolve(__dirname, "../cli/ignore-absolute-path/ignored/module.js"), path.resolve(__dirname, "../cli/ignore-absolute-path/depth1/ignored/*.js"), path.resolve(__dirname, "../cli/ignore-absolute-path/regular-module.js"), - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); diff --git a/tests_integration/__tests__/ignore-in-subdirectories.js b/tests_integration/__tests__/ignore-in-subdirectories.js index 2b5a4937c..4b67ffb02 100644 --- a/tests_integration/__tests__/ignore-in-subdirectories.js +++ b/tests_integration/__tests__/ignore-in-subdirectories.js @@ -9,18 +9,18 @@ describe("ignores files when executing in a subdirectory", () => { "ignore-me/should-ignore.js", "--ignore-path", "../.prettierignore", - "-l" + "-l", ]).test({ - status: 0 + status: 0, }); runPrettier("cli/ignore-in-subdirectories/web1", [ "ignore-me/subdirectory/should-ignore.js", "--ignore-path", "../.prettierignore", - "-l" + "-l", ]).test({ - status: 0 + status: 0, }); }); @@ -29,18 +29,18 @@ describe("formats files when executing in a subdirectory", () => { "should-not-ignore.js", "--ignore-path", "../.prettierignore", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); runPrettier("cli/ignore-in-subdirectories/web2", [ "should-not-ignore.js", "--ignore-path", "../.prettierignore", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); @@ -51,14 +51,14 @@ describe("ignore files when executing in a subdirectory and using stdin", () => "--ignore-path", "../.prettierignore", "--stdin-filepath", - "ignore-me/example.js" + "ignore-me/example.js", ], { - input: "hello_world( );" + input: "hello_world( );", } ).test({ stdout: "hello_world( );", - status: 0 + status: 0, }); }); @@ -67,11 +67,11 @@ describe("formats files when executing in a subdirectory and using stdin", () => "cli/ignore-in-subdirectories/web1", ["--ignore-path", "../.prettierignore", "--stdin-filepath", "example.js"], { - input: "hello_world( );" + input: "hello_world( );", } ).test({ stdout: `hello_world(); `, - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/ignore-path.js b/tests_integration/__tests__/ignore-path.js index f5ef0bed3..0ff89da83 100644 --- a/tests_integration/__tests__/ignore-path.js +++ b/tests_integration/__tests__/ignore-path.js @@ -7,28 +7,28 @@ describe("ignore path", () => { "**/*.js", "--ignore-path", ".gitignore", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); describe("support .prettierignore", () => { runPrettier("cli/ignore-path", ["**/*.js", "-l"]).test({ - status: 1 + status: 1, }); }); describe("ignore file when using --debug-check", () => { runPrettier("cli/ignore-path", ["**/*.js", "--debug-check"]).test({ - status: 0 + status: 0, }); }); describe("outputs files as-is if no --write", () => { runPrettier("cli/ignore-path", ["regular-module.js"], { - ignoreLineEndings: true + ignoreLineEndings: true, }).test({ - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/ignore-relative-path.js b/tests_integration/__tests__/ignore-relative-path.js index e72ae74ab..d48bd0b5d 100644 --- a/tests_integration/__tests__/ignore-relative-path.js +++ b/tests_integration/__tests__/ignore-relative-path.js @@ -11,8 +11,8 @@ describe("support relative paths", () => { "level1-glob/level2-glob/level3-glob/shouldNotBeFormat.js", "./level1-glob/level2-glob/level3-glob/shouldNotBeIgnored.scss", "level1-glob/shouldNotBeIgnored.js", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); diff --git a/tests_integration/__tests__/ignore-vcs-files.js b/tests_integration/__tests__/ignore-vcs-files.js index 0bb13ce3f..064af6ec5 100644 --- a/tests_integration/__tests__/ignore-vcs-files.js +++ b/tests_integration/__tests__/ignore-vcs-files.js @@ -9,8 +9,8 @@ describe("ignores files in version control systems", () => { ".svn/file.js", ".hg/file.js", "file.js", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); diff --git a/tests_integration/__tests__/infer-parser.js b/tests_integration/__tests__/infer-parser.js index 6854515c9..0c5a22be5 100644 --- a/tests_integration/__tests__/infer-parser.js +++ b/tests_integration/__tests__/infer-parser.js @@ -8,27 +8,27 @@ describe("stdin no path and no parser", () => { runPrettier("cli/infer-parser/", [], { input: "foo" }).test({ status: 2, stdout: "", - write: [] + write: [], }); }); describe("--check logs error but exits with 0", () => { runPrettier("cli/infer-parser/", ["--check"], { - input: "foo" + input: "foo", }).test({ status: 0, stdout: "", - write: [] + write: [], }); }); describe("--list-different logs error but exits with 0", () => { runPrettier("cli/infer-parser/", ["--list-different"], { - input: "foo" + input: "foo", }).test({ status: 0, stdout: "", - write: [] + write: [], }); }); }); @@ -36,21 +36,21 @@ describe("stdin no path and no parser", () => { describe("stdin with unknown path and no parser", () => { describe("logs error and exits with 2", () => { runPrettier("cli/infer-parser/", ["--stdin-filepath", "foo"], { - input: "foo" + input: "foo", }).test({ status: 2, stdout: "", - write: [] + write: [], }); }); describe("--check logs error but exits with 0", () => { runPrettier("cli/infer-parser/", ["--check", "--stdin-filepath", "foo"], { - input: "foo" + input: "foo", }).test({ status: 0, stdout: "", - write: [] + write: [], }); }); @@ -62,7 +62,7 @@ describe("stdin with unknown path and no parser", () => { ).test({ status: 0, stdout: "", - write: [] + write: [], }); }); }); @@ -72,14 +72,14 @@ describe("unknown path and no parser", () => { runPrettier("cli/infer-parser/", ["--end-of-line", "lf", "FOO"]).test({ status: 2, stdout: "", - write: [] + write: [], }); }); describe("multiple files", () => { runPrettier("cli/infer-parser/", ["--end-of-line", "lf", "*"]).test({ status: 2, - write: [] + write: [], }); }); }); @@ -88,14 +88,14 @@ describe("--check with unknown path and no parser", () => { describe("specific file", () => { runPrettier("cli/infer-parser/", ["--check", "FOO"]).test({ status: 0, - write: [] + write: [], }); }); describe("multiple files", () => { runPrettier("cli/infer-parser/", ["--check", "*"]).test({ status: 1, - write: [] + write: [], }); }); }); @@ -105,7 +105,7 @@ describe("--list-different with unknown path and no parser", () => { runPrettier("cli/infer-parser/", ["--list-different", "FOO"]).test({ status: 0, stdout: "", - write: [] + write: [], }); }); @@ -113,7 +113,7 @@ describe("--list-different with unknown path and no parser", () => { runPrettier("cli/infer-parser/", ["--list-different", "*"]).test({ status: 1, stdout: "foo.js\n", - write: [] + write: [], }); }); }); @@ -123,13 +123,13 @@ describe("--write with unknown path and no parser", () => { runPrettier("cli/infer-parser/", ["--write", "FOO"]).test({ status: 2, stdout: "", - write: [] + write: [], }); }); describe("multiple files", () => { runPrettier("cli/infer-parser/", ["--write", "*"]).test({ - status: 2 + status: 2, }); }); }); @@ -138,13 +138,13 @@ describe("--write and --check with unknown path and no parser", () => { describe("specific file", () => { runPrettier("cli/infer-parser/", ["--check", "--write", "FOO"]).test({ status: 0, - write: [] + write: [], }); }); describe("multiple files", () => { runPrettier("cli/infer-parser/", ["--check", "--write", "*"]).test({ - status: 0 + status: 0, }); }); }); @@ -154,11 +154,11 @@ describe("--write and --list-different with unknown path and no parser", () => { runPrettier("cli/infer-parser/", [ "--list-different", "--write", - "FOO" + "FOO", ]).test({ status: 0, stdout: "", - write: [] + write: [], }); }); @@ -166,7 +166,7 @@ describe("--write and --list-different with unknown path and no parser", () => { runPrettier("cli/infer-parser/", [ "--list-different", "--write", - "*" + "*", ]).test({ status: 0 }); }); }); diff --git a/tests_integration/__tests__/invalid-ignore.js b/tests_integration/__tests__/invalid-ignore.js index 1d1fda684..3900dc62f 100644 --- a/tests_integration/__tests__/invalid-ignore.js +++ b/tests_integration/__tests__/invalid-ignore.js @@ -6,6 +6,6 @@ expect.addSnapshotSerializer(require("../path-serializer")); describe("throw error with invalid ignore", () => { runPrettier("cli/invalid-ignore", ["something.js"]).test({ - status: "non-zero" + status: "non-zero", }); }); diff --git a/tests_integration/__tests__/list-different.js b/tests_integration/__tests__/list-different.js index e28342e0a..38e9744e9 100644 --- a/tests_integration/__tests__/list-different.js +++ b/tests_integration/__tests__/list-different.js @@ -4,21 +4,21 @@ const runPrettier = require("../runPrettier"); describe("checks stdin with --list-different", () => { runPrettier("cli/with-shebang", ["--list-different", "--parser", "babel"], { - input: "0" + input: "0", }).test({ stdout: "(stdin)\n", stderr: "", - status: "non-zero" + status: "non-zero", }); }); describe("checks stdin with -l (alias for --list-different)", () => { runPrettier("cli/with-shebang", ["-l", "--parser", "babel"], { - input: "0" + input: "0", }).test({ stdout: "(stdin)\n", stderr: "", - status: "non-zero" + status: "non-zero", }); }); @@ -28,22 +28,22 @@ describe("--list-different works in CI just as in a non-TTY mode", () => { ["--list-different", "formatted.js", "unformatted.js"], { env: { - CI: "true" + CI: "true", }, - stdoutIsTTY: true + stdoutIsTTY: true, } ).test({ - status: 1 + status: 1, }); const result1 = runPrettier( "cli/write", ["--list-different", "formatted.js", "unformatted.js"], { - stdoutIsTTY: false + stdoutIsTTY: false, } ).test({ - status: 1 + status: 1, }); expect(result0.stdout).toEqual(result1.stdout); diff --git a/tests_integration/__tests__/loglevel.js b/tests_integration/__tests__/loglevel.js index 50e0e5850..24360e1ba 100644 --- a/tests_integration/__tests__/loglevel.js +++ b/tests_integration/__tests__/loglevel.js @@ -23,9 +23,9 @@ describe("--write with --loglevel=silent doesn't log filenames", () => { runPrettier("cli/write", [ "--write", "unformatted.js", - "--loglevel=silent" + "--loglevel=silent", ]).test({ - status: 0 + status: 0, }); }); @@ -36,7 +36,7 @@ function runPrettierWithLogLevel(logLevel, patterns) { "--unknown-option", "--parser", "unknown-parser", - "not-found.js" + "not-found.js", ]); expect(result.status).toEqual(2); @@ -44,7 +44,7 @@ function runPrettierWithLogLevel(logLevel, patterns) { const stderr = stripAnsi(result.stderr); if (patterns) { - patterns.forEach(pattern => { + patterns.forEach((pattern) => { expect(stderr).toMatch(pattern); }); } else { diff --git a/tests_integration/__tests__/parser-api.js b/tests_integration/__tests__/parser-api.js index f79e51601..9ef929381 100644 --- a/tests_integration/__tests__/parser-api.js +++ b/tests_integration/__tests__/parser-api.js @@ -10,9 +10,9 @@ test("allows custom parser provided as object", () => { return { type: "Literal", value: 2, - raw: "2" + raw: "2", }; - } + }, }); expect(output).toEqual("2"); }); @@ -24,7 +24,7 @@ test("allows usage of prettier's supported parsers", () => { const ast = parsers.babel(text); ast.program.body[0].expression.callee.name = "bar"; return ast; - } + }, }); expect(output).toEqual("bar();\n"); }); @@ -35,8 +35,8 @@ describe("allows passing a string to resolve a parser", () => { "lf", "./custom-rename-input.js", "--parser", - "./custom-rename-parser" + "./custom-rename-parser", ]).test({ - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/patterns-dirs.js b/tests_integration/__tests__/patterns-dirs.js index d4c969977..5939068ed 100644 --- a/tests_integration/__tests__/patterns-dirs.js +++ b/tests_integration/__tests__/patterns-dirs.js @@ -28,10 +28,10 @@ testPatterns("1", ["dir1", "dir2"]); testPatterns("1a - with *.foo plugin", [ "dir1", "dir2", - "--plugin=../../plugins/extensions/plugin" + "--plugin=../../plugins/extensions/plugin", ]); testPatterns("1b - special characters in dir name", ["dir1", "!dir"], { - stdout: expect.stringMatching(/!dir[/\\]a\.js/) + stdout: expect.stringMatching(/!dir[/\\]a\.js/), }); testPatterns("1c", ["dir1", "empty"], { status: 2 }); @@ -48,7 +48,7 @@ describe("Negative patterns", () => { testPatterns("3", [".", "!dir1/nested1/an1.js"]); testPatterns("4", ["!nonexistent-dir1 !nonexistent-dir2"], { status: 2 }); testPatterns("with explicit files", ["dir1/a1.js", "dir2/a2.js", "!dir1/*"], { - status: 2 + status: 2, }); }); @@ -90,13 +90,15 @@ function testPatterns(namePrefix, cliArgs, expected = {}) { const testName = (namePrefix ? namePrefix + ": " : "") + "prettier " + - cliArgs.map(arg => (/^[\w.=/-]+$/.test(arg) ? arg : `'${arg}'`)).join(" "); + cliArgs + .map((arg) => (/^[\w.=/-]+$/.test(arg) ? arg : `'${arg}'`)) + .join(" "); describe(testName, () => { runPrettier("cli/patterns-dirs", [...cliArgs, "-l"]).test({ write: [], ...(!("status" in expected) && { stderr: "", status: 1 }), - ...expected + ...expected, }); }); } diff --git a/tests_integration/__tests__/patterns-glob.js b/tests_integration/__tests__/patterns-glob.js index 476ddc9b9..34506c0b2 100644 --- a/tests_integration/__tests__/patterns-glob.js +++ b/tests_integration/__tests__/patterns-glob.js @@ -13,13 +13,13 @@ fixtures-1/ describe("fixtures-1: Should match all files", () => { runPrettier("cli/patterns-glob/fixtures-1", ["*.js", "!file.js", "-l"]).test({ - status: 1 + status: 1, }); }); describe("fixtures-1: Should match files except `a.js`", () => { runPrettier("cli/patterns-glob/fixtures-1", ["*.js", "!a.js", "-l"]).test({ - status: 1 + status: 1, }); }); @@ -34,19 +34,19 @@ fixtures-2/ describe("fixtures-2: Should match all js files and all supported files in the '!dir.js' directory", () => { runPrettier("cli/patterns-glob/fixtures-2", ["*.js", "!dir.js", "-l"]).test({ - status: 1 + status: 1, }); }); describe("fixtures-2: Should match `a.js` and `!b.js`", () => { runPrettier("cli/patterns-glob/fixtures-2", ["*.js", "!b.js", "-l"]).test({ - status: 1 + status: 1, }); }); describe("fixtures-2: Should only match `!b.js`", () => { runPrettier("cli/patterns-glob/fixtures-2", ["*.js", "!a.js", "-l"]).test({ - status: 1 + status: 1, }); }); @@ -65,15 +65,15 @@ describe("fixtures-3: Should match `outside.js`, `dir/inside.js` and `dir/node_m runPrettier("cli/patterns-glob/fixtures-3", [ "**/*.js", "-l", - "--with-node-modules" + "--with-node-modules", ]).test({ - status: 1 + status: 1, }); }); describe("fixtures-3: Should only match `outside.js` and `dir/inside.js`", () => { runPrettier("cli/patterns-glob/fixtures-3", ["**/*.js", "-l"]).test({ - status: 1 + status: 1, }); }); @@ -82,9 +82,9 @@ describe("fixtures-3: Should exclude `.svn`", () => { runPrettier("cli/patterns-glob/fixtures-3", [ "*.js", "dir/.svn/in-svn.js", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); @@ -92,9 +92,9 @@ describe("fixtures-3: Should exclude `.svn`", () => { runPrettier("cli/patterns-glob/fixtures-3", [ "*.js", ".svn/in-svn.js", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); }); @@ -112,24 +112,24 @@ fixtures-4/ describe("fixtures-4: Should match `level-1.js`", () => { runPrettier("cli/patterns-glob/fixtures-4", ["./0/./level-1.js", "-l"]).test({ - status: 1 + status: 1, }); }); describe("fixtures-4: Should match `level-1.js` #2", () => { runPrettier("cli/patterns-glob/fixtures-4", [ "./0/1/2/../../level-1.js", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); describe("fixtures-4: Should match `level-1.js` #3", () => { runPrettier("cli/patterns-glob/fixtures-4", [ "./0/non-exists-dir/2/../../level-1.js", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); diff --git a/tests_integration/__tests__/patterns.js b/tests_integration/__tests__/patterns.js index ab24079d2..807f190c8 100644 --- a/tests_integration/__tests__/patterns.js +++ b/tests_integration/__tests__/patterns.js @@ -8,9 +8,9 @@ describe("multiple patterns", () => { runPrettier("cli/patterns", [ "directory/**/*.js", "other-directory/**/*.js", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); @@ -18,9 +18,9 @@ describe("multiple patterns with non exists pattern", () => { runPrettier("cli/patterns", [ "directory/**/*.js", "non-existent.js", - "-l" + "-l", ]).test({ - status: 2 + status: 2, }); }); @@ -28,21 +28,21 @@ describe("multiple patterns with ignore nested directories pattern", () => { runPrettier("cli/patterns", [ "**/*.js", "!**/nested-directory/**", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); describe("multiple patterns by with ignore pattern, ignores node_modules by default", () => { runPrettier("cli/patterns", ["**/*.js", "!directory/**", "-l"]).test({ - status: 1 + status: 1, }); }); describe("multiple patterns by with ignore pattern, ignores node_modules by with ./**/*.js", () => { runPrettier("cli/patterns", ["./**/*.js", "!./directory/**", "-l"]).test({ - status: 1 + status: 1, }); }); @@ -51,16 +51,16 @@ describe("multiple patterns by with ignore pattern, doesn't ignore node_modules "**/*.js", "!directory/**", "-l", - "--with-node-modules" + "--with-node-modules", ]).test({ - status: 1 + status: 1, }); }); describe("no errors on empty patterns", () => { // --parser is mandatory if no filepath is passed runPrettier("cli/patterns", ["--parser", "babel"]).test({ - status: 0 + status: 0, }); }); @@ -68,8 +68,8 @@ describe("multiple patterns, throw error and exit with non zero code on non exis runPrettier("cli/patterns", [ "non-existent.js", "other-non-existent.js", - "-l" + "-l", ]).test({ - status: 2 + status: 2, }); }); diff --git a/tests_integration/__tests__/piped-output.js b/tests_integration/__tests__/piped-output.js index 22b18ef40..173cd72e1 100644 --- a/tests_integration/__tests__/piped-output.js +++ b/tests_integration/__tests__/piped-output.js @@ -8,7 +8,7 @@ describe("output with --check + unformatted differs when piped", () => { ["--write", "--check", "--no-color", "unformatted.js"], { stdoutIsTTY: true } ).test({ - status: 0 + status: 0, }); const result1 = runPrettier( @@ -16,7 +16,7 @@ describe("output with --check + unformatted differs when piped", () => { ["--write", "--check", "--no-color", "unformatted.js"], { stdoutIsTTY: false } ).test({ - status: 0 + status: 0, }); expect(result0.stdout.length).toBeGreaterThan(result1.stdout.length); @@ -29,7 +29,7 @@ describe("no file diffs with --check + formatted file", () => { ["--write", "--check", "--no-color", "formatted.js"], { stdoutIsTTY: true } ).test({ - status: 0 + status: 0, }); const result1 = runPrettier( @@ -37,7 +37,7 @@ describe("no file diffs with --check + formatted file", () => { ["--write", "--check", "--no-color", "formatted.js"], { stdoutIsTTY: false } ).test({ - status: 0 + status: 0, }); expect(result0.stdout).not.toEqual(result1.stdout); @@ -51,7 +51,7 @@ describe("output with --list-different + unformatted differs when piped", () => ["--write", "--list-different", "--no-color", "unformatted.js"], { stdoutIsTTY: true } ).test({ - status: 0 + status: 0, }); const result1 = runPrettier( @@ -59,7 +59,7 @@ describe("output with --list-different + unformatted differs when piped", () => ["--write", "--list-different", "--no-color", "unformatted.js"], { stdoutIsTTY: false } ).test({ - status: 0 + status: 0, }); expect(result0.stdout.length).toBeGreaterThan(result1.stdout.length); @@ -72,7 +72,7 @@ describe("no file diffs with --list-different + formatted file", () => { ["--write", "--list-different", "--no-color", "formatted.js"], { stdoutIsTTY: true } ).test({ - status: 0 + status: 0, }); const result1 = runPrettier( @@ -80,7 +80,7 @@ describe("no file diffs with --list-different + formatted file", () => { ["--write", "--list-different", "--no-color", "formatted.js"], { stdoutIsTTY: false } ).test({ - status: 0 + status: 0, }); expect(result0.stdout).not.toEqual(result1.stdout); diff --git a/tests_integration/__tests__/plugin-default-options.js b/tests_integration/__tests__/plugin-default-options.js index 2477762ef..b0a3f24b9 100644 --- a/tests_integration/__tests__/plugin-default-options.js +++ b/tests_integration/__tests__/plugin-default-options.js @@ -9,17 +9,17 @@ describe("plugin default options should work", () => { "--stdin-filepath", "example.foo", "--plugin=./plugin", - "--no-editorconfig" + "--no-editorconfig", ], { input: "hello-world" } ).test({ stdout: JSON.stringify({ tabWidth: 8, - bracketSpacing: false + bracketSpacing: false, }), stderr: "", status: 0, - write: [] + write: [], }); }); @@ -31,10 +31,10 @@ describe("overriding plugin default options should work", () => { ).test({ stdout: JSON.stringify({ tabWidth: 4, - bracketSpacing: false + bracketSpacing: false, }), stderr: "", status: 0, - write: [] + write: [], }); }); diff --git a/tests_integration/__tests__/plugin-extensions.js b/tests_integration/__tests__/plugin-extensions.js index 781690701..26843f1b3 100644 --- a/tests_integration/__tests__/plugin-extensions.js +++ b/tests_integration/__tests__/plugin-extensions.js @@ -5,11 +5,11 @@ const EOL = "\n"; describe("uses 'extensions' from languages to determine parser", () => { runPrettier("plugins/extensions", ["*.foo", "--plugin=./plugin"], { - ignoreLineEndings: true + ignoreLineEndings: true, }).test({ stdout: "!contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); diff --git a/tests_integration/__tests__/plugin-options-string.js b/tests_integration/__tests__/plugin-options-string.js index 3c12c1e81..aa2547738 100644 --- a/tests_integration/__tests__/plugin-options-string.js +++ b/tests_integration/__tests__/plugin-options-string.js @@ -8,7 +8,7 @@ describe("show external options with `--help`", () => { .stdout; const pluggedStdout = runPrettier("plugins/options-string", [ "--help", - "--plugin=./plugin" + "--plugin=./plugin", ]).stdout; expect(snapshotDiff(originalStdout, pluggedStdout)).toMatchSnapshot(); }); @@ -17,9 +17,9 @@ describe("show detailed external option with `--help foo-string`", () => { runPrettier("plugins/options-string", [ "--plugin=./plugin", "--help", - "foo-string" + "foo-string", ]).test({ - status: 0 + status: 0, }); }); @@ -31,14 +31,14 @@ describe("external options from CLI should work", () => { "--stdin-filepath", "example.foo", "--foo-string", - "baz" + "baz", ], { input: "hello-world" } ).test({ stdout: "foo:baz", stderr: "", status: 0, - write: [] + write: [], }); }); @@ -51,6 +51,6 @@ describe("external options from config file should work", () => { stdout: "foo:baz", stderr: "", status: 0, - write: [] + write: [], }); }); diff --git a/tests_integration/__tests__/plugin-options.js b/tests_integration/__tests__/plugin-options.js index 746384491..bb6ddfe9c 100644 --- a/tests_integration/__tests__/plugin-options.js +++ b/tests_integration/__tests__/plugin-options.js @@ -7,7 +7,7 @@ describe("show external options with `--help`", () => { const originalStdout = runPrettier("plugins/options", ["--help"]).stdout; const pluggedStdout = runPrettier("plugins/options", [ "--help", - "--plugin=./plugin" + "--plugin=./plugin", ]).stdout; expect(snapshotDiff(originalStdout, pluggedStdout)).toMatchSnapshot(); }); @@ -16,9 +16,9 @@ describe("show detailed external option with `--help foo-option`", () => { runPrettier("plugins/options", [ "--plugin=./plugin", "--help", - "foo-option" + "foo-option", ]).test({ - status: 0 + status: 0, }); }); @@ -30,14 +30,14 @@ describe("external options from CLI should work", () => { "--stdin-filepath", "example.foo", "--foo-option", - "baz" + "baz", ], { input: "hello-world" } ).test({ stdout: "foo:baz", stderr: "", status: 0, - write: [] + write: [], }); }); @@ -50,6 +50,6 @@ describe("external options from config file should work", () => { stdout: "foo:baz", stderr: "", status: 0, - write: [] + write: [], }); }); diff --git a/tests_integration/__tests__/plugin-precedence.js b/tests_integration/__tests__/plugin-precedence.js index 2a8935df2..355b24a48 100644 --- a/tests_integration/__tests__/plugin-precedence.js +++ b/tests_integration/__tests__/plugin-precedence.js @@ -5,12 +5,12 @@ const runPrettier = require("../runPrettier"); describe("json-stringify takes precedence over json for package.json", () => { runPrettier("plugins", ["--stdin-filepath=package.json"], { input: - '{ "a": "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong" }' + '{ "a": "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong" }', }).test({ stdout: '{\n "a": "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong"\n}\n', stderr: "", status: 0, - write: [] + write: [], }); }); diff --git a/tests_integration/__tests__/plugin-preprocess.js b/tests_integration/__tests__/plugin-preprocess.js index 9f6fba284..23819fe50 100644 --- a/tests_integration/__tests__/plugin-preprocess.js +++ b/tests_integration/__tests__/plugin-preprocess.js @@ -5,11 +5,11 @@ const EOL = "\n"; describe("parser preprocess function is used to reshape input text", () => { runPrettier("plugins/preprocess", ["*.foo", "--plugin=./plugin"], { - ignoreLineEndings: true + ignoreLineEndings: true, }).test({ stdout: "preprocessed:contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); diff --git a/tests_integration/__tests__/plugin-resolution.js b/tests_integration/__tests__/plugin-resolution.js index a7c4a2158..15a330f56 100644 --- a/tests_integration/__tests__/plugin-resolution.js +++ b/tests_integration/__tests__/plugin-resolution.js @@ -8,7 +8,7 @@ describe("automatically loads 'prettier-plugin-*'", () => { stdout: "content from `prettier-plugin-bar` package + contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -17,7 +17,7 @@ describe("automatically loads '@prettier/plugin-*'", () => { stdout: "foo+contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -26,7 +26,7 @@ describe("automatically loads '@/prettier-plugin-*'", () => { stdout: "foobar+contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -34,12 +34,12 @@ describe("automatically loads 'prettier-plugin-*' from --plugin-search-dir (same runPrettier("plugins/automatic", [ "file.txt", "--parser=foo", - "--plugin-search-dir=." + "--plugin-search-dir=.", ]).test({ stdout: "foo+contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -47,12 +47,12 @@ describe("automatically loads '@prettier/plugin-*' from --plugin-search-dir (sam runPrettier("plugins/automatic", [ "file.txt", "--parser=bar", - "--plugin-search-dir=." + "--plugin-search-dir=.", ]).test({ stdout: "content from `prettier-plugin-bar` package + contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -60,12 +60,12 @@ describe("automatically loads '@/prettier-plugin-*' from --plugin-search-d runPrettier("plugins/automatic", [ "file.txt", "--parser=foobar", - "--plugin-search-dir=." + "--plugin-search-dir=.", ]).test({ stdout: "foobar+contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -73,12 +73,12 @@ describe("automatically loads 'prettier-plugin-*' from --plugin-search-dir (diff runPrettier("plugins", [ "automatic/file.txt", "--parser=foo", - "--plugin-search-dir=automatic" + "--plugin-search-dir=automatic", ]).test({ stdout: "foo+contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -86,12 +86,12 @@ describe("automatically loads '@prettier/plugin-*' from --plugin-search-dir (dif runPrettier("plugins", [ "automatic/file.txt", "--parser=bar", - "--plugin-search-dir=automatic" + "--plugin-search-dir=automatic", ]).test({ stdout: "content from `prettier-plugin-bar` package + contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -103,14 +103,14 @@ describe("does not crash when --plugin-search-dir does not contain node_modules" "--end-of-line", "lf", "--plugin=./plugin", - "--plugin-search-dir=." + "--plugin-search-dir=.", ], { ignoreLineEndings: true } ).test({ stdout: "!contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -119,12 +119,12 @@ describe("crashes when one of --plugin-search-dir does not exist", () => { "file.txt", "--parser=foo", "--plugin-search-dir=non-existing-dir", - "--plugin-search-dir=." + "--plugin-search-dir=.", ]).test({ stdout: "", stderr: "non-existing-dir does not exist or is not a directory", status: 1, - write: [] + write: [], }); }); @@ -132,12 +132,12 @@ describe("loads --plugin by its relative path", () => { runPrettier("plugins", [ "automatic/file.txt", "--parser=bar", - "--plugin=./automatic/node_modules/prettier-plugin-bar/index.js" + "--plugin=./automatic/node_modules/prettier-plugin-bar/index.js", ]).test({ stdout: "content from `prettier-plugin-bar` package + contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -145,12 +145,12 @@ describe("loads --plugin by its relative path without leading ./", () => { runPrettier("plugins", [ "automatic/file.txt", "--parser=bar", - "--plugin=automatic/node_modules/prettier-plugin-bar/index.js" + "--plugin=automatic/node_modules/prettier-plugin-bar/index.js", ]).test({ stdout: "content from `prettier-plugin-bar` package + contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -158,12 +158,12 @@ describe("loads --plugin by relative path to its directory (assuming index.js)", runPrettier("plugins", [ "automatic/file.txt", "--parser=bar", - "--plugin=./automatic/node_modules/prettier-plugin-bar" + "--plugin=./automatic/node_modules/prettier-plugin-bar", ]).test({ stdout: "content from `prettier-plugin-bar` package + contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -171,12 +171,12 @@ describe("loads --plugin by relative path to its directory without leading ./ (a runPrettier("plugins", [ "automatic/file.txt", "--parser=bar", - "--plugin=automatic/node_modules/prettier-plugin-bar" + "--plugin=automatic/node_modules/prettier-plugin-bar", ]).test({ stdout: "content from `prettier-plugin-bar` package + contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -184,12 +184,12 @@ describe("loads --plugin by filename without leading ./ and ext, should resolve runPrettier("plugins/automatic", [ "file.txt", "--parser=bar", - "--plugin=prettier-plugin-bar" + "--plugin=prettier-plugin-bar", ]).test({ stdout: "content from `prettier-plugin-bar.js` file + contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); @@ -197,11 +197,11 @@ describe("loads --plugin by bespoke plugin name (assuming it is installed in cwd runPrettier("plugins/bespoke", [ "../automatic/file.txt", "--parser=bespoke", - "--plugin=@company/prettier-plugin-bespoke" + "--plugin=@company/prettier-plugin-bespoke", ]).test({ stdout: "bespoke+contents" + EOL, stderr: "", status: 0, - write: [] + write: [], }); }); diff --git a/tests_integration/__tests__/plugin-virtual-directory.js b/tests_integration/__tests__/plugin-virtual-directory.js index 87275e437..4602eb013 100644 --- a/tests_integration/__tests__/plugin-virtual-directory.js +++ b/tests_integration/__tests__/plugin-virtual-directory.js @@ -11,6 +11,6 @@ describe("plugin search should not crash when prettier isn't inside a directory" stdout: "", stderr: "", status: 0, - write: [] + write: [], }); }); diff --git a/tests_integration/__tests__/skip-folders.js b/tests_integration/__tests__/skip-folders.js index a2403bbf8..193781c9e 100644 --- a/tests_integration/__tests__/skip-folders.js +++ b/tests_integration/__tests__/skip-folders.js @@ -7,7 +7,7 @@ expect.addSnapshotSerializer(require("../path-serializer")); describe("skips folders in glob", () => { runPrettier("cli/skip-folders", ["**/*", "-l"]).test({ status: 1, - stderr: "" + stderr: "", }); }); @@ -17,6 +17,6 @@ describe("skip folders passed specifically", () => { "a/file.js", "b", "b/file.js", - "-l" + "-l", ]).test({ status: 1, stderr: "" }); }); diff --git a/tests_integration/__tests__/stdin-filepath.js b/tests_integration/__tests__/stdin-filepath.js index 983b6a64a..863151be3 100644 --- a/tests_integration/__tests__/stdin-filepath.js +++ b/tests_integration/__tests__/stdin-filepath.js @@ -8,7 +8,7 @@ describe("format correctly if stdin content compatible with stdin-filepath", () ["--stdin-filepath", "abc.css"], { input: ".name { display: none; }" } // css ).test({ - status: 0 + status: 0, }); }); @@ -18,7 +18,7 @@ describe("throw error if stdin content incompatible with stdin-filepath", () => ["--stdin-filepath", "abc.js"], { input: ".name { display: none; }" } // css ).test({ - status: "non-zero" + status: "non-zero", }); }); @@ -28,7 +28,7 @@ describe("gracefully handle stdin-filepath with nonexistent directory", () => { ["--stdin-filepath", "definitely/nonexistent/path.css"], { input: ".name { display: none; }" } // css ).test({ - status: 0 + status: 0, }); }); @@ -41,10 +41,10 @@ describe("apply editorconfig for stdin-filepath with nonexistent file", () => { function f() { console.log("should be indented with a tab"); } -`.trim() // js +`.trim(), // js } ).test({ - status: 0 + status: 0, }); }); @@ -57,10 +57,10 @@ describe("apply editorconfig for stdin-filepath with nonexistent directory", () function f() { console.log("should be indented with a tab"); } -`.trim() // js +`.trim(), // js } ).test({ - status: 0 + status: 0, }); }); @@ -69,25 +69,25 @@ describe("don’t apply editorconfig outside project for stdin-filepath with non "cli", [ "--stdin-filepath", - "config/editorconfig/repo-root/nonexistent/one/two/three.js" + "config/editorconfig/repo-root/nonexistent/one/two/three.js", ], { input: ` function f() { console.log("should be indented with 2 spaces"); } -`.trim() // js +`.trim(), // js } ).test({ - status: 0 + status: 0, }); }); describe("output file as-is if stdin-filepath matched patterns in ignore-path", () => { runPrettier("cli/stdin-ignore", ["--stdin-filepath", "ignore/example.js"], { - input: "hello_world( );" + input: "hello_world( );", }).test({ stdout: "hello_world( );", - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/support-info.js b/tests_integration/__tests__/support-info.js index 52bf4c033..13e0782c9 100644 --- a/tests_integration/__tests__/support-info.js +++ b/tests_integration/__tests__/support-info.js @@ -25,10 +25,10 @@ function getCoreInfo() { ...(option.type === "int" ? { range: option.range } : option.type === "choice" - ? { choices: option.choices.map(choice => choice.value) } - : null) + ? { choices: option.choices.map((choice) => choice.value) } + : null), }, - ...obj + ...obj, }), {} ); diff --git a/tests_integration/__tests__/syntax-error.js b/tests_integration/__tests__/syntax-error.js index 969d74066..362ffab40 100644 --- a/tests_integration/__tests__/syntax-error.js +++ b/tests_integration/__tests__/syntax-error.js @@ -4,8 +4,8 @@ const runPrettier = require("../runPrettier"); describe("exits with non-zero code when input has a syntax error", () => { runPrettier("cli/with-shebang", ["--parser", "babel"], { - input: "a.2" + input: "a.2", }).test({ - status: 2 + status: 2, }); }); diff --git a/tests_integration/__tests__/util-shared.js b/tests_integration/__tests__/util-shared.js index c8b6dd780..d6d537b56 100644 --- a/tests_integration/__tests__/util-shared.js +++ b/tests_integration/__tests__/util-shared.js @@ -37,7 +37,7 @@ test("sharedUtil.getMaxContinuousCount", () => { "([a-f])([a-f])", "[a-f][a-f][a-f]", "a-fa-fa-fa-f", - "bbbbbbbbbbbbbbbbbb" // neither `a-f` `[a-f]` `([a-f])` should matches `b` + "bbbbbbbbbbbbbbbbbb", // neither `a-f` `[a-f]` `([a-f])` should matches `b` ].join(""); expect(getMaxContinuousCount(fixture, "([a-f])")).toEqual(2); expect(getMaxContinuousCount(fixture, "[a-f]")).toEqual(3); diff --git a/tests_integration/__tests__/with-config-precedence.js b/tests_integration/__tests__/with-config-precedence.js index 5cf57023f..22a2e69b9 100644 --- a/tests_integration/__tests__/with-config-precedence.js +++ b/tests_integration/__tests__/with-config-precedence.js @@ -8,9 +8,9 @@ describe("CLI overrides take precedence without --config-precedence", () => { "lf", "--print-width", "1", - "**/*.js" + "**/*.js", ]).test({ - status: 0 + status: 0, }); }); @@ -22,9 +22,9 @@ describe("CLI overrides take precedence with --config-precedence cli-override", "1", "--config-precedence", "cli-override", - "**/*.js" + "**/*.js", ]).test({ - status: 0 + status: 0, }); }); @@ -36,9 +36,9 @@ describe("CLI overrides take lower precedence with --config-precedence file-over "1", "--config-precedence", "file-override", - "**/*.js" + "**/*.js", ]).test({ - status: 0 + status: 0, }); }); @@ -51,9 +51,9 @@ describe("CLI overrides are still applied when no config is found with --config- "--config-precedence", "file-override", "**/*.js", - "--no-editorconfig" + "--no-editorconfig", ]).test({ - status: 0 + status: 0, }); }); @@ -65,9 +65,9 @@ describe("CLI overrides gets ignored when config exists with --config-precedence "1", "--config-precedence", "prefer-file", - "**/*.js" + "**/*.js", ]).test({ - status: 0 + status: 0, }); }); @@ -82,36 +82,36 @@ describe("CLI overrides gets applied when no config exists with --config-precede "--no-config", "--config-precedence", "prefer-file", - "**/*.js" + "**/*.js", ]).test({ - status: 0 + status: 0, }); }); describe("CLI validate options with --config-precedence cli-override", () => { runPrettier("cli/config-precedence", [ "--config-precedence", - "cli-override" + "cli-override", ]).test({ - status: "non-zero" + status: "non-zero", }); }); describe("CLI validate options with --config-precedence file-override", () => { runPrettier("cli/config-precedence", [ "--config-precedence", - "file-override" + "file-override", ]).test({ - status: "non-zero" + status: "non-zero", }); }); describe("CLI validate options with --config-precedence prefer-file", () => { runPrettier("cli/config-precedence", [ "--config-precedence", - "prefer-file" + "prefer-file", ]).test({ - status: "non-zero" + status: "non-zero", }); }); @@ -122,7 +122,7 @@ describe("CLI --stdin-filepath works with --config-precedence prefer-file", () = { input: "let x: keyof Y = foo()" } // typescript ).test({ stderr: "", - status: 0 + status: 0, }); }); @@ -132,12 +132,12 @@ describe("CLI --stdin-filepath works with --config-precedence file-override", () [ "--stdin-filepath=abc.ts", "--no-semi", - "--config-precedence=file-override" + "--config-precedence=file-override", ], { input: "let x: keyof Y = foo()" } // typescript ).test({ stderr: "", - status: 0 + status: 0, }); }); @@ -147,11 +147,11 @@ describe("CLI --stdin-filepath works with --config-precedence cli-override", () [ "--stdin-filepath=abc.ts", "--no-semi", - "--config-precedence=cli-override" + "--config-precedence=cli-override", ], { input: "let x: keyof Y = foo()" } // typescript ).test({ stderr: "", - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/with-node-modules.js b/tests_integration/__tests__/with-node-modules.js index 26529d1a9..212d80d5c 100644 --- a/tests_integration/__tests__/with-node-modules.js +++ b/tests_integration/__tests__/with-node-modules.js @@ -6,13 +6,13 @@ expect.addSnapshotSerializer(require("../path-serializer")); describe("ignores node_modules by default", () => { runPrettier("cli/with-node-modules", ["**/*.js", "-l"]).test({ - status: 1 + status: 1, }); }); describe("ignores node_modules by with ./**/*.js", () => { runPrettier("cli/with-node-modules", ["./**/*.js", "-l"]).test({ - status: 1 + status: 1, }); }); @@ -20,9 +20,9 @@ describe("doesn't ignore node_modules with --with-node-modules flag", () => { runPrettier("cli/with-node-modules", [ "**/*.js", "-l", - "--with-node-modules" + "--with-node-modules", ]).test({ - status: 1 + status: 1, }); }); @@ -32,9 +32,9 @@ describe("ignores node_modules by default for file list", () => { "not_node_modules/file.js", "nested/node_modules/node-module.js", "regular-module.js", - "-l" + "-l", ]).test({ - status: 1 + status: 1, }); }); @@ -45,8 +45,8 @@ describe("doesn't ignore node_modules with --with-node-modules flag for file lis "nested/node_modules/node-module.js", "regular-module.js", "-l", - "--with-node-modules" + "--with-node-modules", ]).test({ - status: 1 + status: 1, }); }); diff --git a/tests_integration/__tests__/with-parser-inference.js b/tests_integration/__tests__/with-parser-inference.js index 9bc773e55..ecf3b2cde 100644 --- a/tests_integration/__tests__/with-parser-inference.js +++ b/tests_integration/__tests__/with-parser-inference.js @@ -5,19 +5,19 @@ const prettier = require("prettier/local"); describe("infers postcss parser", () => { runPrettier("cli/with-parser-inference", ["--end-of-line", "lf", "*"]).test({ - status: 0 + status: 0, }); }); describe("infers postcss parser with --check", () => { runPrettier("cli/with-parser-inference", ["--check", "*"]).test({ - status: 0 + status: 0, }); }); describe("infers postcss parser with --list-different", () => { runPrettier("cli/with-parser-inference", ["--list-different", "*"]).test({ - status: 0 + status: 0, }); }); diff --git a/tests_integration/__tests__/with-shebang.js b/tests_integration/__tests__/with-shebang.js index ceda4c5c9..62c78f744 100644 --- a/tests_integration/__tests__/with-shebang.js +++ b/tests_integration/__tests__/with-shebang.js @@ -5,7 +5,7 @@ const runPrettier = require("../runPrettier"); describe("preserves shebang", () => { runPrettier("cli/with-shebang", ["--end-of-line", "lf", "issue1890.js"]).test( { - status: 0 + status: 0, } ); }); diff --git a/tests_integration/__tests__/write.js b/tests_integration/__tests__/write.js index 6cee65156..0d1a7ce36 100644 --- a/tests_integration/__tests__/write.js +++ b/tests_integration/__tests__/write.js @@ -4,20 +4,20 @@ const runPrettier = require("../runPrettier"); describe("write file with --write + unformatted file", () => { runPrettier("cli/write", ["--write", "unformatted.js"]).test({ - status: 0 + status: 0, }); }); describe("do not write file with --write + formatted file", () => { runPrettier("cli/write", ["--write", "formatted.js"]).test({ write: [], - status: 0 + status: 0, }); }); describe("do not write file with --write + invalid file", () => { runPrettier("cli/write", ["--write", "invalid.js"]).test({ write: [], - status: "non-zero" + status: "non-zero", }); }); diff --git a/tests_integration/custom-parsers/custom-rename-parser.js b/tests_integration/custom-parsers/custom-rename-parser.js index 958629c55..900161184 100644 --- a/tests_integration/custom-parsers/custom-rename-parser.js +++ b/tests_integration/custom-parsers/custom-rename-parser.js @@ -1,6 +1,6 @@ "use strict"; -module.exports = function(text, parsers) { +module.exports = function (text, parsers) { const ast = parsers.babel(text); ast.program.body[0].expression.callee.name = "bar"; return ast; diff --git a/tests_integration/env.js b/tests_integration/env.js index 01084f41c..9f8f35bfd 100644 --- a/tests_integration/env.js +++ b/tests_integration/env.js @@ -17,5 +17,5 @@ const thirdParty = isProduction module.exports = { thirdParty, - prettierCli + prettierCli, }; diff --git a/tests_integration/path-serializer.js b/tests_integration/path-serializer.js index 6f0ab353b..e1d6592b1 100644 --- a/tests_integration/path-serializer.js +++ b/tests_integration/path-serializer.js @@ -1,12 +1,12 @@ "use strict"; -const replaceCWD = text => { +const replaceCWD = (text) => { const cwd = process.cwd(); const variants = /^[a-z]:\\/i.test(cwd) ? [ cwd.charAt(0).toLowerCase() + cwd.slice(1), - cwd.charAt(0).toUpperCase() + cwd.slice(1) + cwd.charAt(0).toUpperCase() + cwd.slice(1), ] : [cwd]; @@ -20,9 +20,9 @@ const replaceCWD = text => { }; module.exports = { - test: value => + test: (value) => typeof value === "string" && (value.includes("\\") || value.includes(process.cwd())), print: (value, serializer) => - serializer(replaceCWD(value).replace(/\\/g, "/")) + serializer(replaceCWD(value).replace(/\\/g, "/")), }; diff --git a/tests_integration/runPrettier.js b/tests_integration/runPrettier.js index 1f6db542a..9b3a6de18 100644 --- a/tests_integration/runPrettier.js +++ b/tests_integration/runPrettier.js @@ -14,7 +14,7 @@ function runPrettier(dir, args, options) { let stdout = ""; let stderr = ""; - jest.spyOn(process, "exit").mockImplementation(exitCode => { + jest.spyOn(process, "exit").mockImplementation((exitCode) => { if (status === undefined) { status = exitCode || 0; } @@ -22,23 +22,23 @@ function runPrettier(dir, args, options) { jest .spyOn(process.stdout, "write") - .mockImplementation(text => appendStdout(text)); + .mockImplementation((text) => appendStdout(text)); jest .spyOn(process.stderr, "write") - .mockImplementation(text => appendStderr(text)); + .mockImplementation((text) => appendStderr(text)); jest .spyOn(console, "log") - .mockImplementation(text => appendStdout(text + "\n")); + .mockImplementation((text) => appendStdout(text + "\n")); jest .spyOn(console, "warn") - .mockImplementation(text => appendStderr(text + "\n")); + .mockImplementation((text) => appendStderr(text + "\n")); jest .spyOn(console, "error") - .mockImplementation(text => appendStderr(text + "\n")); + .mockImplementation((text) => appendStderr(text + "\n")); jest.spyOn(Date, "now").mockImplementation(() => 0); @@ -50,7 +50,7 @@ function runPrettier(dir, args, options) { const origStatSync = fs.statSync; - jest.spyOn(fs, "statSync").mockImplementation(filename => { + jest.spyOn(fs, "statSync").mockImplementation((filename) => { if (path.basename(filename) === "virtualDirectory") { return origStatSync(path.join(__dirname, __filename)); } @@ -86,7 +86,7 @@ function runPrettier(dir, args, options) { .mockImplementation((moduleName, options) => require("cosmiconfig").cosmiconfig(moduleName, { ...options, - stopDir: __dirname + stopDir: __dirname, }) ); jest @@ -94,7 +94,7 @@ function runPrettier(dir, args, options) { .mockImplementation((moduleName, options) => require("cosmiconfig").cosmiconfigSync(moduleName, { ...options, - stopDir: __dirname + stopDir: __dirname, }) ); jest @@ -119,10 +119,10 @@ function runPrettier(dir, args, options) { const result = { status, stdout, stderr, write }; - const testResult = testOptions => { + const testResult = (testOptions) => { testOptions = testOptions || {}; - Object.keys(result).forEach(name => { + Object.keys(result).forEach((name) => { test(`(${name})`, () => { const value = // \r is trimmed from jest snapshots by default; diff --git a/website/blog/2019-01-20-1.16.0.md b/website/blog/2019-01-20-1.16.0.md index 7acb28d7c..1465ab0c3 100644 --- a/website/blog/2019-01-20-1.16.0.md +++ b/website/blog/2019-01-20-1.16.0.md @@ -199,7 +199,7 @@ const prettier = require("prettier"); const fooPlugin = require("./path/to/foo-plugin"); const formatted = prettier.format("foo-code", { plugins: [fooPlugin], - parser: "foo-parser" + parser: "foo-parser", }); // Prettier 1.15: Error // Prettier 1.16: No error diff --git a/website/blog/2019-04-12-1.17.0.md b/website/blog/2019-04-12-1.17.0.md index 9de115bdc..f674cb190 100644 --- a/website/blog/2019-04-12-1.17.0.md +++ b/website/blog/2019-04-12-1.17.0.md @@ -80,7 +80,7 @@ If you don't want to use `package.json`, you can use any of the supported extens > ```js > module.exports = { > ...require("@company/prettier-config"), -> semi: false +> semi: false, > }; > ``` diff --git a/website/core/Footer.js b/website/core/Footer.js index 4b1bb4e2a..32a4f5abd 100644 --- a/website/core/Footer.js +++ b/website/core/Footer.js @@ -3,7 +3,7 @@ const React = require("react"); const PropTypes = require("prop-types"); -const GithubButton = props => ( +const GithubButton = (props) => ( ( ); GithubButton.propTypes = { - config: PropTypes.object + config: PropTypes.object, }; class Footer extends React.Component { @@ -90,7 +90,7 @@ class Footer extends React.Component { Footer.propTypes = { language: PropTypes.string, - config: PropTypes.object + config: PropTypes.object, }; module.exports = Footer; diff --git a/website/pages/en/help/index.js b/website/pages/en/help/index.js index f08b2986b..ce9059eda 100755 --- a/website/pages/en/help/index.js +++ b/website/pages/en/help/index.js @@ -9,16 +9,16 @@ class Help extends React.Component { { content: "Learn more using the [documentation on this site.](/docs/en/why-prettier.html)\n", - title: "Browse Docs" + title: "Browse Docs", }, { content: "Ask questions about the documentation and project\n", - title: "Join the community" + title: "Join the community", }, { content: "Find out what's new with this project\n", - title: "Stay up to date" - } + title: "Stay up to date", + }, ]; return ( @@ -40,7 +40,7 @@ class Help extends React.Component { } Help.defaultProps = { - language: "en" + language: "en", }; module.exports = Help; diff --git a/website/pages/en/index.js b/website/pages/en/index.js index 6910b0114..b76393036 100755 --- a/website/pages/en/index.js +++ b/website/pages/en/index.js @@ -7,12 +7,12 @@ const AnimatedLogo = require("@sandhose/prettier-animated-logo"); const siteConfig = require(process.cwd() + "/siteConfig.js"); -const ButtonGroup = props => ( +const ButtonGroup = (props) => (
{props.children}
); ButtonGroup.propTypes = { - children: PropTypes.node + children: PropTypes.node, }; class Button extends React.Component { @@ -28,13 +28,13 @@ class Button extends React.Component { } Button.defaultProps = { - target: "_self" + target: "_self", }; Button.propTypes = { href: PropTypes.string, target: PropTypes.string, - children: PropTypes.any + children: PropTypes.any, }; function Tidelift() { @@ -45,7 +45,7 @@ function Tidelift() { ); } -const HomeSplash = props => { +const HomeSplash = (props) => { return (
@@ -76,7 +76,7 @@ const HomeSplash = props => { }; HomeSplash.propTypes = { - language: PropTypes.string + language: PropTypes.string, }; const TldrSection = ({ language }) => ( @@ -86,7 +86,7 @@ const TldrSection = ({ language }) => ( style={{ display: "flex", flexFlow: "row wrap", - justifyContent: "space-evenly" + justifyContent: "space-evenly", }} >
@@ -115,7 +115,7 @@ const TldrSection = ({ language }) => ( ); TldrSection.propTypes = { - language: PropTypes.string + language: PropTypes.string, }; const Language = ({ name, nameLink, showName, image, variants }) => ( @@ -124,7 +124,7 @@ const Language = ({ name, nameLink, showName, image, variants }) => ( style={{ display: "flex", alignItems: "flex-start", - paddingBottom: "1em" + paddingBottom: "1em", }} > @@ -134,7 +134,7 @@ const Language = ({ name, nameLink, showName, image, variants }) => ( {nameLink ? {name} : name} )} - {variants.map(variant => ( + {variants.map((variant) => (
  • {variant}
  • @@ -148,7 +148,7 @@ Language.propTypes = { nameLink: PropTypes.string, showName: PropTypes.bool, image: PropTypes.string, - variants: PropTypes.array + variants: PropTypes.array, }; const LanguagesSection = () => { @@ -182,12 +182,12 @@ const LanguagesSection = () => { style={{ display: "flex", flexFlow: "row wrap", - justifyContent: "space-around" + justifyContent: "space-around", }} > {languageChunks.map((languageChunk, index) => (
    - {languageChunk.map(language => ( + {languageChunk.map((language) => ( ))}
    @@ -211,7 +211,7 @@ const Editor = ({ content = "", image, name }) => ( Editor.propTypes = { content: PropTypes.string, image: PropTypes.string.isRequired, - name: PropTypes.string.isRequired + name: PropTypes.string.isRequired, }; const EditorSupportSection = () => ( @@ -222,10 +222,10 @@ const EditorSupportSection = () => ( style={{ display: "flex", flexFlow: "row wrap", - justifyContent: "space-around" + justifyContent: "space-around", }} > - {siteConfig.editors.map(editor => ( + {siteConfig.editors.map((editor) => ( ))}
    @@ -245,13 +245,13 @@ const EditorSupportSection = () => ( const bash = (...args) => `~~~bash\n${String.raw(...args)}\n~~~`; -const json = object => `~~~json\n${JSON.stringify(object, null, 2)}\n~~~`; +const json = (object) => `~~~json\n${JSON.stringify(object, null, 2)}\n~~~`; class GetStartedSection extends React.Component { constructor(props) { super(props); this.state = { - npmClient: "yarn" + npmClient: "yarn", }; } @@ -265,7 +265,7 @@ class GetStartedSection extends React.Component { display: "flex", flexFlow: "row", alignItems: "baseline", - justifyContent: "space-between" + justifyContent: "space-between", }} >
    @@ -314,9 +314,9 @@ class GetStartedSection extends React.Component { {json({ husky: { hooks: { - "pre-commit": "pretty-quick --staged" - } - } + "pre-commit": "pretty-quick --staged", + }, + }, })} @@ -328,7 +328,7 @@ class GetStartedSection extends React.Component { flexDirection: "column", alignItems: "flex-end", flexGrow: 1, - marginLeft: "-75px" + marginLeft: "-75px", }} > @@ -342,7 +342,7 @@ class GetStartedSection extends React.Component { @@ -356,7 +356,7 @@ class GetStartedSection extends React.Component { const UsersSection = ({ language }) => { const showcase = siteConfig.users - .filter(user => { + .filter((user) => { return user.pinned; }) .map((user, i) => { @@ -376,7 +376,7 @@ const UsersSection = ({ language }) => { style={{ display: "flex", flexFlow: "row wrap", - justifyContent: "space-around" + justifyContent: "space-around", }} > {showcase} @@ -403,7 +403,7 @@ const UsersSection = ({ language }) => { style={{ display: "flex", justifyContent: "space-around", - flexFlow: "row wrap" + flexFlow: "row wrap", }} >
    @@ -446,7 +446,7 @@ const UsersSection = ({ language }) => { }; UsersSection.propTypes = { - language: PropTypes.string + language: PropTypes.string, }; class Index extends React.Component { @@ -470,7 +470,7 @@ class Index extends React.Component { } Index.propTypes = { - language: PropTypes.string + language: PropTypes.string, }; module.exports = Index; diff --git a/website/pages/en/users/index.js b/website/pages/en/users/index.js index 2a7dbd835..3e2a55281 100644 --- a/website/pages/en/users/index.js +++ b/website/pages/en/users/index.js @@ -52,7 +52,7 @@ class Users extends React.Component { } Users.defaultProps = { - language: "en" + language: "en", }; Users.title = "Who's using Prettier?"; diff --git a/website/playground/BottomBar.js b/website/playground/BottomBar.js index 52219bbfb..365479e95 100644 --- a/website/playground/BottomBar.js +++ b/website/playground/BottomBar.js @@ -3,7 +3,7 @@ import ReactDOM from "react-dom"; const root = document.getElementById("bottom-bar"); -export default function({ left, right }) { +export default function ({ left, right }) { return ReactDOM.createPortal(
    {left}
    diff --git a/website/playground/EditorState.js b/website/playground/EditorState.js index 9b4c73630..034b8a06f 100644 --- a/website/playground/EditorState.js +++ b/website/playground/EditorState.js @@ -15,7 +15,7 @@ export default class extends React.Component { toggleAst: () => this.setState(stateToggler("showAst")), toggleDoc: () => this.setState(stateToggler("showDoc")), toggleSecondFormat: () => this.setState(stateToggler("showSecondFormat")), - ...storage.get("editor_state") + ...storage.get("editor_state"), }; } diff --git a/website/playground/Playground.js b/website/playground/Playground.js index 4b0f90831..55e910af9 100644 --- a/website/playground/Playground.js +++ b/website/playground/Playground.js @@ -21,7 +21,7 @@ const CATEGORIES_ORDER = [ "JavaScript", "Markdown", "HTML", - "Special" + "Special", ]; const ENABLED_OPTIONS = [ "parser", @@ -40,7 +40,7 @@ const ENABLED_OPTIONS = [ "htmlWhitespaceSensitivity", "insertPragma", "requirePragma", - "vueIndentScriptAndStyle" + "vueIndentScriptAndStyle", ]; const ISSUES_URL = "https://github.com/prettier/prettier/issues/new?body="; const MAX_LENGTH = 8000 - ISSUES_URL.length; // it seems that GitHub limit is 8195 @@ -65,16 +65,16 @@ class Playground extends React.Component { this.handleOptionValueChange = this.handleOptionValueChange.bind(this); - this.setContent = content => this.setState({ content }); + this.setContent = (content) => this.setState({ content }); this.clearContent = this.setContent.bind(this, ""); this.resetOptions = () => this.setState({ options: defaultOptions }); this.enabledOptions = orderOptions(props.availableOptions, ENABLED_OPTIONS); this.rangeStartOption = props.availableOptions.find( - opt => opt.name === "rangeStart" + (opt) => opt.name === "rangeStart" ); this.rangeEndOption = props.availableOptions.find( - opt => opt.name === "rangeEnd" + (opt) => opt.name === "rangeEnd" ); } @@ -89,7 +89,7 @@ class Playground extends React.Component { } handleOptionValueChange(option, value) { - this.setState(state => { + this.setState((state) => { const options = { ...state.options }; if (option.type === "int" && isNaN(value)) { @@ -130,7 +130,7 @@ class Playground extends React.Component { return ( - {editorState => ( + {(editorState) => ( optionsByName[name]); + return order.map((name) => optionsByName[name]); } function getReportLink(reportBody) { diff --git a/website/playground/PrettierFormat.js b/website/playground/PrettierFormat.js index bb29d81fe..16cd4c268 100644 --- a/website/playground/PrettierFormat.js +++ b/website/playground/PrettierFormat.js @@ -26,12 +26,12 @@ export default class PrettierFormat extends React.Component { options, debugAst: ast, debugDoc: doc, - reformat + reformat, } = this.props; worker .format(code, options, { ast, doc, reformat }) - .then(result => this.setState(result)); + .then((result) => this.setState(result)); } render() { diff --git a/website/playground/VersionLink.js b/website/playground/VersionLink.js index 060b557d5..c6d8b5b68 100644 --- a/website/playground/VersionLink.js +++ b/website/playground/VersionLink.js @@ -3,7 +3,7 @@ import ReactDOM from "react-dom"; const root = document.getElementById("version"); -export default function({ version }) { +export default function ({ version }) { const match = version.match(/^pr-(\d+)$/); let href; if (match) { diff --git a/website/playground/WorkerApi.js b/website/playground/WorkerApi.js index d85055f92..8deae41df 100644 --- a/website/playground/WorkerApi.js +++ b/website/playground/WorkerApi.js @@ -1,9 +1,9 @@ -export default function(source) { +export default function (source) { const worker = new Worker(source); let counter = 0; const handlers = {}; - worker.addEventListener("message", event => { + worker.addEventListener("message", (event) => { const { uid, message, error } = event.data; if (!handlers[uid]) { @@ -35,6 +35,6 @@ export default function(source) { format(code, options, debug) { return postMessage({ type: "format", code, options, debug }); }, - postMessage + postMessage, }; } diff --git a/website/playground/buttons.js b/website/playground/buttons.js index c7dbcc65a..f104752c7 100644 --- a/website/playground/buttons.js +++ b/website/playground/buttons.js @@ -18,7 +18,7 @@ export class ClipboardButton extends React.Component { text: () => { const { copy } = this.props; return typeof copy === "function" ? copy() : copy; - } + }, }); this.clipboard.on("success", () => this.showTooltip("Copied!")); this.clipboard.on("error", () => this.showTooltip("Press ctrl+c to copy")); diff --git a/website/playground/codeSamples.js b/website/playground/codeSamples.js index f2fa576f8..74b170a72 100644 --- a/website/playground/codeSamples.js +++ b/website/playground/codeSamples.js @@ -1,4 +1,4 @@ -export default function(parser) { +export default function (parser) { switch (parser) { case "babel": return [ @@ -22,7 +22,7 @@ export default function(parser) { "", "
    ;", "", - "}" + "}", ].join("\n"); case "flow": case "babel-flow": @@ -34,7 +34,7 @@ export default function(parser) { " mutate: Function|void", " }>>", "", - 'declare type FetchPolicy = "cache-first" | "cache-and-network" | "network-only" | "cache-only"' + 'declare type FetchPolicy = "cache-first" | "cache-and-network" | "network-only" | "cache-only"', ].join("\n"); case "typescript": case "babel-ts": @@ -57,7 +57,7 @@ export default function(parser) { " }", "}", "", - "type RequestType = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'OPTIONS' | 'CONNECT' | 'DELETE' | 'TRACE'" + "type RequestType = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'OPTIONS' | 'CONNECT' | 'DELETE' | 'TRACE'", ].join("\n"); case "css": // Excerpted from the Bootstrap source, which is licensed under the MIT license: @@ -72,7 +72,7 @@ export default function(parser) { " padding-left: .75rem;", " ", " }", - "}" + "}", ].join("\n"); case "scss": // Excerpted from the Bootstrap source, which is licensed under the MIT license: @@ -95,7 +95,7 @@ export default function(parser) { " color: color-yiq($value);", " background-color: #{$value};", " }", - "}" + "}", ].join("\n"); case "less": // Copied from http://lesscss.org/features/#detached-rulesets-feature @@ -109,7 +109,7 @@ export default function(parser) { " };", "@media (orientation:portrait) {", " @my-ruleset();", - "}" + "}", ].join("\n"); case "json": case "json5": @@ -129,7 +129,7 @@ export default function(parser) { ' {"type": "office",', ' "trailing": "commas by accident"},', " ],", - "}" + "}", ].join("\n"); case "graphql": return [ @@ -141,7 +141,7 @@ export default function(parser) { " price", " }", " }", - "}" + "}", ].join("\n"); case "markdown": return [ @@ -169,7 +169,7 @@ export default function(parser) { " [another one]: http://example.com 'Example title'", "", "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - "Curabitur consectetur maximus risus, sed maximus tellus tincidunt et." + "Curabitur consectetur maximus risus, sed maximus tellus tincidunt et.", ].join("\n"); case "mdx": // modified from https://github.com/mdx-js/mdx/blob/master/packages/mdx/test/fixtures/blog-post.md @@ -215,7 +215,7 @@ export default function(parser) { "| Col1 | Col2 |", "", "export default ({children }) => < div>{ children}
    ", - "" + "", ].join("\n"); case "vue": return [ @@ -230,7 +230,7 @@ export default function(parser) { "", "" + "", ].join("\n"); case "yaml": // modified from http://yaml.org/start.html @@ -273,7 +273,7 @@ export default function(parser) { " Late afternoon is best.", " Backup contact is Nancy", " Billsmer @ 338-4338.", - "" + "", ].join("\n"); case "glimmer": // modified from http://handlebarsjs.com/ @@ -282,7 +282,7 @@ export default function(parser) { "

    {{ title }}

    ", '
    ', " {{ body }}", - "
    " + " ", ].join("\n"); case "html": case "angular": @@ -303,7 +303,7 @@ export default function(parser) { " ", ' ', " ", - "" + "", ].join("\n"); default: return ""; diff --git a/website/playground/helpers.js b/website/playground/helpers.js index 6af48b37c..36363cd17 100644 --- a/website/playground/helpers.js +++ b/website/playground/helpers.js @@ -1,5 +1,5 @@ export function stateToggler(key) { - return state => ({ [key]: !state[key] }); + return (state) => ({ [key]: !state[key] }); } const { hasOwnProperty } = Object.prototype; diff --git a/website/playground/index.js b/website/playground/index.js index bd1bf8b10..70e1cec89 100644 --- a/website/playground/index.js +++ b/website/playground/index.js @@ -20,7 +20,7 @@ class App extends React.Component { this.setState({ loaded: true, availableOptions: supportInfo.options.map(augmentOption), - version: fixPrettierVersion(version) + version: fixPrettierVersion(version), }); }); } diff --git a/website/playground/markdown.js b/website/playground/markdown.js index e02e6985f..ad04510e7 100644 --- a/website/playground/markdown.js +++ b/website/playground/markdown.js @@ -21,13 +21,13 @@ function formatMarkdown( codeBlock(input, syntax), "", "**Output:**", - codeBlock(output, syntax) + codeBlock(output, syntax), ] .concat( isIdempotent ? [] : ["", "**Second Output:**", codeBlock(output2, syntax)] ) .concat(full ? ["", "**Expected behavior:**", ""] : []) - .filter(part => { + .filter((part) => { return part != null; }) .join("\n"); diff --git a/website/playground/panels.js b/website/playground/panels.js index 0452ff9e5..5abbe9229 100644 --- a/website/playground/panels.js +++ b/website/playground/panels.js @@ -69,7 +69,7 @@ class CodeMirrorPanel extends React.Component { } const [start, end] = getIndexPosition(this.props.value, [ this.props.overlayStart, - this.props.overlayEnd + this.props.overlayEnd, ]); this._overlay = createOverlay(start, end); this._codeMirror.addOverlay(this._overlay); @@ -142,7 +142,7 @@ function createOverlay(start, end) { stream.skipToEnd(); return "searching"; } - } + }, }; } diff --git a/website/playground/sidebar/SidebarOptions.js b/website/playground/sidebar/SidebarOptions.js index 9d24644e8..ca7150496 100644 --- a/website/playground/sidebar/SidebarOptions.js +++ b/website/playground/sidebar/SidebarOptions.js @@ -4,17 +4,17 @@ import groupBy from "lodash/groupBy"; import { SidebarCategory } from "./components"; import Option from "./options"; -export default function({ +export default function ({ categories, availableOptions, optionValues, - onOptionValueChange + onOptionValueChange, }) { const options = groupBy(availableOptions, "category"); - return categories.map(category => + return categories.map((category) => options[category] ? ( - {options[category].map(option => ( + {options[category].map((option) => (