prettier / prettier-regression-testing

Automates the prettier/prettier regression checks with GitHub Actions.
11 stars 9 forks source link

pr 8300 -- Functional composition experiments #42

Open thorn0 opened 3 years ago

thorn0 commented 3 years ago

run #8300

github-actions[bot] commented 3 years ago

prettier/prettier#8300 VS prettier/prettier@main

Diff (2988 lines) ```diff diff --git ORI/babel/packages/babel-cli/src/babel/util.js ALT/babel/packages/babel-cli/src/babel/util.js index fc1bf2b58..6840b8071 100644 --- ORI/babel/packages/babel-cli/src/babel/util.js +++ ALT/babel/packages/babel-cli/src/babel/util.js @@ -16,15 +16,19 @@ export function readdir( includeDotfiles: boolean, filter?: ReaddirFilter, ): Array { - return readdirRecursive(dirname, (filename, _index, currentDirectory) => { - const stat = fs.statSync(path.join(currentDirectory, filename)); - - if (stat.isDirectory()) return true; - - return ( - (includeDotfiles || filename[0] !== ".") && (!filter || filter(filename)) - ); - }); + return readdirRecursive( + dirname, + (filename, _index, currentDirectory) => { + const stat = fs.statSync(path.join(currentDirectory, filename)); + + if (stat.isDirectory()) return true; + + return ( + (includeDotfiles || filename[0] !== ".") && + (!filter || filter(filename)) + ); + }, + ); } export function readdirForCompilable( @@ -32,9 +36,13 @@ export function readdirForCompilable( includeDotfiles: boolean, altExts?: Array, ): Array { - return readdir(dirname, includeDotfiles, function (filename) { - return isCompilableExtension(filename, altExts); - }); + return readdir( + dirname, + includeDotfiles, + function (filename) { + return isCompilableExtension(filename, altExts); + }, + ); } /** diff --git ORI/babel/packages/babel-compat-data/scripts/utils-build-data.js ALT/babel/packages/babel-compat-data/scripts/utils-build-data.js index e8a21f4f2..4a82857d6 100644 --- ORI/babel/packages/babel-compat-data/scripts/utils-build-data.js +++ ALT/babel/packages/babel-compat-data/scripts/utils-build-data.js @@ -35,17 +35,22 @@ exports.environments = [ "samsung", ]; -const compatibilityTests = flatMap(compatSources, data => - flatMap(data.tests, test => { - if (!test.subtests) return test; - - return test.subtests.map(subtest => - Object.assign({}, subtest, { - name: test.name + " / " + subtest.name, - group: test.name, - }) - ); - }) +const compatibilityTests = flatMap( + compatSources, + data => + flatMap( + data.tests, + test => { + if (!test.subtests) return test; + + return test.subtests.map(subtest => + Object.assign({}, subtest, { + name: test.name + " / " + subtest.name, + group: test.name, + }) + ); + } + ) ); exports.getLowestImplementedVersion = ( @@ -85,23 +90,26 @@ exports.getLowestImplementedVersion = ( }; exports.generateData = (environments, features) => { - return mapValues(features, options => { - if (!options.features) { - options = { - features: [options], - }; + return mapValues( + features, + options => { + if (!options.features) { + options = { + features: [options], + }; + } + + const plugin = {}; + + environments.forEach(env => { + const version = exports.getLowestImplementedVersion(options, env); + if (version) plugin[env] = version; + }); + addElectronSupportFromChromium(plugin); + + return plugin; } - - const plugin = {}; - - environments.forEach(env => { - const version = exports.getLowestImplementedVersion(options, env); - if (version) plugin[env] = version; - }); - addElectronSupportFromChromium(plugin); - - return plugin; - }); + ); }; exports.writeFile = function (data, dataPath, name) { diff --git ORI/babel/packages/babel-core/src/config/caching.js ALT/babel/packages/babel-core/src/config/caching.js index 050c59d85..d60bc3874 100644 --- ORI/babel/packages/babel-core/src/config/caching.js +++ ALT/babel/packages/babel-core/src/config/caching.js @@ -128,9 +128,12 @@ function makeCachedFunction( // Flow refines handlerResult to Generator const gen = (handlerResult: Generator<*, ResultT, *>); - value = yield* onFirstPause(gen, () => { - finishLock = setupAsyncLocks(cache, futureCache, arg); - }); + value = yield* onFirstPause( + gen, + () => { + finishLock = setupAsyncLocks(cache, futureCache, arg); + }, + ); } else { // $FlowIgnore doesn't refine handlerResult to ResultT value = (handlerResult: ResultT); diff --git ORI/babel/packages/babel-core/src/config/full.js ALT/babel/packages/babel-core/src/config/full.js index 75fbe293c..9d8ac3fb9 100644 --- ORI/babel/packages/babel-core/src/config/full.js +++ ALT/babel/packages/babel-core/src/config/full.js @@ -161,29 +161,32 @@ export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig( const opts: Object = optionDefaults; mergeOptions(opts, options); - yield* enhanceError(context, function* loadPluginDescriptors() { - pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); - - for (const descs of pluginDescriptorsByPass) { - const pass = []; - passes.push(pass); - - for (let i = 0; i < descs.length; i++) { - const descriptor: UnloadedDescriptor = descs[i]; - if (descriptor.options !== false) { - try { - pass.push(yield* loadPluginDescriptor(descriptor, context)); - } catch (e) { - if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { - // print special message for `plugins: ["@babel/foo", { foo: "option" }]` - checkNoUnwrappedItemOptionPairs(descs, i, "plugin", e); + yield* enhanceError( + context, + function* loadPluginDescriptors() { + pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); + + for (const descs of pluginDescriptorsByPass) { + const pass = []; + passes.push(pass); + + for (let i = 0; i < descs.length; i++) { + const descriptor: UnloadedDescriptor = descs[i]; + if (descriptor.options !== false) { + try { + pass.push(yield* loadPluginDescriptor(descriptor, context)); + } catch (e) { + if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { + // print special message for `plugins: ["@babel/foo", { foo: "option" }]` + checkNoUnwrappedItemOptionPairs(descs, i, "plugin", e); + } + throw e; } - throw e; } } } - } - })(); + }, + )(); opts.plugins = passes[0]; opts.presets = passes @@ -307,10 +310,13 @@ const instantiatePlugin = makeWeakCache(function* ( dirname, }; - const inherits = yield* forwardAsync(loadPluginDescriptor, run => { - // If the inherited plugin changes, reinstantiate this plugin. - return cache.invalidate(data => run(inheritsDescriptor, data)); - }); + const inherits = yield* forwardAsync( + loadPluginDescriptor, + run => { + // If the inherited plugin changes, reinstantiate this plugin. + return cache.invalidate(data => run(inheritsDescriptor, data)); + }, + ); plugin.pre = chain(inherits.pre, plugin.pre); plugin.post = chain(inherits.post, plugin.post); diff --git ORI/babel/packages/babel-core/src/transformation/block-hoist-plugin.js ALT/babel/packages/babel-core/src/transformation/block-hoist-plugin.js index 477d2d5c3..5901aaf22 100644 --- ORI/babel/packages/babel-core/src/transformation/block-hoist-plugin.js +++ ALT/babel/packages/babel-core/src/transformation/block-hoist-plugin.js @@ -51,14 +51,17 @@ const blockHoistPlugin = { } if (!hasChange) return; - node.body = sortBy(node.body, function (bodyNode) { - let priority = bodyNode?._blockHoist; - if (priority == null) priority = 1; - if (priority === true) priority = 2; + node.body = sortBy( + node.body, + function (bodyNode) { + let priority = bodyNode?._blockHoist; + if (priority == null) priority = 1; + if (priority === true) priority = 2; - // Higher priorities should move toward the top. - return -1 * priority; - }); + // Higher priorities should move toward the top. + return -1 * priority; + }, + ); }, }, }, diff --git ORI/babel/packages/babel-core/src/transformation/file/merge-map.js ALT/babel/packages/babel-core/src/transformation/file/merge-map.js index 911867d96..02825f678 100644 --- ORI/babel/packages/babel-core/src/transformation/file/merge-map.js +++ ALT/babel/packages/babel-core/src/transformation/file/merge-map.js @@ -123,15 +123,18 @@ function filterApplicableOriginalRanges( ): OriginalMappings { // The mapping array is sorted by original location, so we can // binary-search it for the overlapping ranges. - return filterSortedArray(mappings, ({ original: outOriginal }) => { - if (line > outOriginal.line) return -1; - if (line < outOriginal.line) return 1; + return filterSortedArray( + mappings, + ({ original: outOriginal }) => { + if (line > outOriginal.line) return -1; + if (line < outOriginal.line) return 1; - if (columnStart >= outOriginal.columnEnd) return -1; - if (columnEnd <= outOriginal.columnStart) return 1; + if (columnStart >= outOriginal.columnEnd) return -1; + if (columnEnd <= outOriginal.columnStart) return 1; - return 0; - }); + return 0; + }, + ); } function eachInputGeneratedRange( diff --git ORI/babel/packages/babel-core/test/api.js ALT/babel/packages/babel-core/test/api.js index a8aed41cc..4d2a57901 100644 --- ORI/babel/packages/babel-core/test/api.js +++ ALT/babel/packages/babel-core/test/api.js @@ -454,24 +454,36 @@ describe("api", function () { // Writes value properly. expect( - doTransform("", file => { - file.shebang = "env node"; - }), + doTransform( + "", + file => { + file.shebang = "env node"; + }, + ), ).toBe(`#!env node`); expect( - doTransform("#!env node", file => { - file.shebang = "env node2"; - }), + doTransform( + "#!env node", + file => { + file.shebang = "env node2"; + }, + ), ).toBe(`#!env node2`); expect( - doTransform("", file => { - file.shebang = ""; - }), + doTransform( + "", + file => { + file.shebang = ""; + }, + ), ).toBe(``); expect( - doTransform("#!env node", file => { - file.shebang = ""; - }), + doTransform( + "#!env node", + file => { + file.shebang = ""; + }, + ), ).toBe(``); // Reads value properly. @@ -484,14 +496,17 @@ describe("api", function () { // Reads and writes properly. expect( - doTransform("#!env node", file => { - expect(file.shebang).toBe("env node"); + doTransform( + "#!env node", + file => { + expect(file.shebang).toBe("env node"); - file.shebang = "env node2"; - expect(file.shebang).toBe("env node2"); + file.shebang = "env node2"; + expect(file.shebang).toBe("env node2"); - file.shebang = "env node3"; - }), + file.shebang = "env node3"; + }, + ), ).toBe(`#!env node3`); }); diff --git ORI/babel/packages/babel-helper-module-imports/test/index.js ALT/babel/packages/babel-helper-module-imports/test/index.js index 7f6a2206c..6f9f38070 100644 --- ORI/babel/packages/babel-helper-module-imports/test/index.js +++ ALT/babel/packages/babel-helper-module-imports/test/index.js @@ -24,11 +24,13 @@ function test(sourceType, opts, initializer, inputCode, expectedCode) { function ({ types: t }) { return { pre(file) { - file.set("helperGenerator", name => - t.memberExpression( - t.identifier("babelHelpers"), - t.identifier(name), - ), + file.set( + "helperGenerator", + name => + t.memberExpression( + t.identifier("babelHelpers"), + t.identifier(name), + ), ); }, visitor: { @@ -1134,8 +1136,9 @@ describe("@babel/helper-module-imports", () => { it("is disallowed in CJS modules", () => { expect(() => - testScript({ importPosition: "after" }, m => - m.addNamed("read", "source"), + testScript( + { importPosition: "after" }, + m => m.addNamed("read", "source"), ), ).toThrow(`"importPosition": "after" is only supported in modules`); }); diff --git ORI/babel/packages/babel-parser/src/plugins/flow.js ALT/babel/packages/babel-parser/src/plugins/flow.js index 6dfbe03ea..c830daae8 100644 --- ORI/babel/packages/babel-parser/src/plugins/flow.js +++ ALT/babel/packages/babel-parser/src/plugins/flow.js @@ -1696,8 +1696,9 @@ export default (superClass: Class): Class => isMethod?: boolean = false, ): void { if (allowExpressionBody) { - return this.forwardNoArrowParamsConversionAt(node, () => - super.parseFunctionBody(node, true, isMethod), + return this.forwardNoArrowParamsConversionAt( + node, + () => super.parseFunctionBody(node, true, isMethod), ); } @@ -1888,8 +1889,9 @@ export default (superClass: Class): Class => node.test = expr; node.consequent = consequent; - node.alternate = this.forwardNoArrowParamsConversionAt(node, () => - this.parseMaybeAssign(undefined, undefined, undefined), + node.alternate = this.forwardNoArrowParamsConversionAt( + node, + () => this.parseMaybeAssign(undefined, undefined, undefined), ); return this.finishNode(node, "ConditionalExpression"); @@ -1944,8 +1946,9 @@ export default (superClass: Class): Class => return [arrows, []]; } - return partition(arrows, node => - node.params.every(param => this.isAssignable(param, true)), + return partition( + arrows, + node => node.params.every(param => this.isAssignable(param, true)), ); } diff --git ORI/babel/packages/babel-register/src/node.js ALT/babel/packages/babel-register/src/node.js index ff5209b63..6c8d18907 100644 --- ORI/babel/packages/babel-register/src/node.js +++ ALT/babel/packages/babel-register/src/node.js @@ -43,14 +43,12 @@ function mtime(filename) { function compile(code, filename) { // merge in base options and resolve all the plugins and presets relative to this file - const opts = new OptionManager().init( - // sourceRoot can be overwritten - { - sourceRoot: path.dirname(filename) + path.sep, - ...deepClone(transformOpts), - filename, - }, - ); + const opts = new OptionManager().init(// sourceRoot can be overwritten + { + sourceRoot: path.dirname(filename) + path.sep, + ...deepClone(transformOpts), + filename, + }); // Bail out ASAP if the file has been ignored. if (opts === null) return code; diff --git ORI/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js ALT/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js index d215a27..1ab212c 100644 --- ORI/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js +++ ALT/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js @@ -57,9 +57,11 @@ module.exports = { let eslintScope try { - eslintScope = getESLintModule('eslint-scope', () => - // @ts-ignore - require('eslint-scope') + eslintScope = getESLintModule( + 'eslint-scope', + () => + // @ts-ignore + require('eslint-scope') ) } catch (_e) { context.report({ @@ -70,9 +72,11 @@ module.exports = { } let espree try { - espree = getESLintModule('espree', () => - // @ts-ignore - require('espree') + espree = getESLintModule( + 'espree', + () => + // @ts-ignore + require('espree') ) } catch (_e) { context.report({ diff --git ORI/eslint-plugin-vue/lib/rules/no-unused-properties.js ALT/eslint-plugin-vue/lib/rules/no-unused-properties.js index f89c518..ff66c1b 100644 --- ORI/eslint-plugin-vue/lib/rules/no-unused-properties.js +++ ALT/eslint-plugin-vue/lib/rules/no-unused-properties.js @@ -381,8 +381,9 @@ function extractPatternOrThisProperties(node, context, withInTemplate) { // `arg.foo` const name = utils.getStaticPropertyName(parent) if (name) { - result.addUsed(name, () => - extractPatternOrThisProperties(parent, context, withInTemplate) + result.addUsed( + name, + () => extractPatternOrThisProperties(parent, context, withInTemplate) ) } else { result.unknown = true diff --git ORI/eslint-plugin-vue/lib/rules/require-valid-default-prop.js ALT/eslint-plugin-vue/lib/rules/require-valid-default-prop.js index ef9453b..66e62bc 100644 --- ORI/eslint-plugin-vue/lib/rules/require-valid-default-prop.js +++ ALT/eslint-plugin-vue/lib/rules/require-valid-default-prop.js @@ -219,14 +219,11 @@ module.exports = { return utils.defineVueVisitor(context, { onVueObjectEnter(obj) { /** @type {ComponentObjectDefineProp[]} */ - const props = utils.getComponentProps(obj).filter( - /** - * @param {ComponentObjectProp | ComponentArrayProp} prop - * @returns {prop is ComponentObjectDefineProp} - */ - (prop) => - Boolean(prop.value && prop.value.type === 'ObjectExpression') - ) + const props = utils.getComponentProps(obj).filter(/** + * @param {ComponentObjectProp | ComponentArrayProp} prop + * @returns {prop is ComponentObjectDefineProp} + */ + (prop) => Boolean(prop.value && prop.value.type === 'ObjectExpression')) /** @type {PropDefaultFunctionContext[]} */ const propContexts = [] for (const prop of props) { diff --git ORI/eslint-plugin-vue/lib/utils/index.js ALT/eslint-plugin-vue/lib/utils/index.js index 055ffb4..0201e64 100644 --- ORI/eslint-plugin-vue/lib/utils/index.js +++ ALT/eslint-plugin-vue/lib/utils/index.js @@ -465,20 +465,18 @@ module.exports = { */ getAttribute(node, name, value) { return ( - node.startTag.attributes.find( - /** - * @param {VAttribute | VDirective} node - * @returns {node is VAttribute} - */ - (node) => { - return ( - !node.directive && - node.key.name === name && - (value === undefined || - (node.value != null && node.value.value === value)) - ) - } - ) || null + node.startTag.attributes.find(/** + * @param {VAttribute | VDirective} node + * @returns {node is VAttribute} + */ + (node) => { + return ( + !node.directive && + node.key.name === name && + (value === undefined || + (node.value != null && node.value.value === value)) + ) + }) || null ) }, @@ -491,15 +489,13 @@ module.exports = { getDirectives(node, name) { const attributes = node.type === 'VElement' ? node.startTag.attributes : node.attributes - return attributes.filter( - /** - * @param {VAttribute | VDirective} node - * @returns {node is VDirective} - */ - (node) => { - return node.directive && node.key.name.name === name - } - ) + return attributes.filter(/** + * @param {VAttribute | VDirective} node + * @returns {node is VDirective} + */ + (node) => { + return node.directive && node.key.name.name === name + }) }, /** * Get the directive which has the given name. @@ -510,22 +506,20 @@ module.exports = { */ getDirective(node, name, argument) { return ( - node.startTag.attributes.find( - /** - * @param {VAttribute | VDirective} node - * @returns {node is VDirective} - */ - (node) => { - return ( - node.directive && - node.key.name.name === name && - (argument === undefined || - (node.key.argument && - node.key.argument.type === 'VIdentifier' && - node.key.argument.name) === argument) - ) - } - ) || null + node.startTag.attributes.find(/** + * @param {VAttribute | VDirective} node + * @returns {node is VDirective} + */ + (node) => { + return ( + node.directive && + node.key.name.name === name && + (argument === undefined || + (node.key.argument && + node.key.argument.type === 'VIdentifier' && + node.key.argument.name) === argument) + ) + }) || null ) }, @@ -535,19 +529,17 @@ module.exports = { * @returns { { node: Property, name: string }[] } Array of ASTNodes */ getRegisteredComponents(componentObject) { - const componentsNode = componentObject.properties.find( - /** - * @param {ESNode} p - * @returns {p is (Property & { key: Identifier & {name: 'components'}, value: ObjectExpression })} - */ - (p) => { - return ( - p.type === 'Property' && - getStaticPropertyName(p) === 'components' && - p.value.type === 'ObjectExpression' - ) - } - ) + const componentsNode = componentObject.properties.find(/** + * @param {ESNode} p + * @returns {p is (Property & { key: Identifier & {name: 'components'}, value: ObjectExpression })} + */ + (p) => { + return ( + p.type === 'Property' && + getStaticPropertyName(p) === 'components' && + p.value.type === 'ObjectExpression' + ) + }) if (!componentsNode) { return [] @@ -667,20 +659,18 @@ module.exports = { * @return {(ComponentArrayProp | ComponentObjectProp)[]} Array of component props in format: [{key?: String, value?: ASTNode, node: ASTNod}] */ getComponentProps(componentObject) { - const propsNode = componentObject.properties.find( - /** - * @param {ESNode} p - * @returns {p is (Property & { key: Identifier & {name: 'props'}, value: ObjectExpression | ArrayExpression })} - */ - (p) => { - return ( - p.type === 'Property' && - getStaticPropertyName(p) === 'props' && - (p.value.type === 'ObjectExpression' || - p.value.type === 'ArrayExpression') - ) - } - ) + const propsNode = componentObject.properties.find(/** + * @param {ESNode} p + * @returns {p is (Property & { key: Identifier & {name: 'props'}, value: ObjectExpression | ArrayExpression })} + */ + (p) => { + return ( + p.type === 'Property' && + getStaticPropertyName(p) === 'props' && + (p.value.type === 'ObjectExpression' || + p.value.type === 'ArrayExpression') + ) + }) if (!propsNode) { return [] @@ -737,20 +727,18 @@ module.exports = { * @return {(ComponentArrayEmit | ComponentObjectEmit)[]} Array of component emits in format: [{key?: String, value?: ASTNode, node: ASTNod}] */ getComponentEmits(componentObject) { - const emitsNode = componentObject.properties.find( - /** - * @param {ESNode} p - * @returns {p is (Property & { key: Identifier & {name: 'emits'}, value: ObjectExpression | ArrayExpression })} - */ - (p) => { - return ( - p.type === 'Property' && - getStaticPropertyName(p) === 'emits' && - (p.value.type === 'ObjectExpression' || - p.value.type === 'ArrayExpression') - ) - } - ) + const emitsNode = componentObject.properties.find(/** + * @param {ESNode} p + * @returns {p is (Property & { key: Identifier & {name: 'emits'}, value: ObjectExpression | ArrayExpression })} + */ + (p) => { + return ( + p.type === 'Property' && + getStaticPropertyName(p) === 'emits' && + (p.value.type === 'ObjectExpression' || + p.value.type === 'ArrayExpression') + ) + }) if (!emitsNode) { return [] @@ -807,19 +795,17 @@ module.exports = { * @return {ComponentComputedProperty[]} Array of computed properties in format: [{key: String, value: ASTNode}] */ getComputedProperties(componentObject) { - const computedPropertiesNode = componentObject.properties.find( - /** - * @param {ESNode} p - * @returns {p is (Property & { key: Identifier & {name: 'computed'}, value: ObjectExpression })} - */ - (p) => { - return ( - p.type === 'Property' && - getStaticPropertyName(p) === 'computed' && - p.value.type === 'ObjectExpression' - ) - } - ) + const computedPropertiesNode = componentObject.properties.find(/** + * @param {ESNode} p + * @returns {p is (Property & { key: Identifier & {name: 'computed'}, value: ObjectExpression })} + */ + (p) => { + return ( + p.type === 'Property' && + getStaticPropertyName(p) === 'computed' && + p.value.type === 'ObjectExpression' + ) + }) if (!computedPropertiesNode) { return [] diff --git ORI/eslint-plugin-vue/tests/lib/utils/html-comments.js ALT/eslint-plugin-vue/tests/lib/utils/html-comments.js index 066c73e..6a0297e 100644 --- ORI/eslint-plugin-vue/tests/lib/utils/html-comments.js +++ ALT/eslint-plugin-vue/tests/lib/utils/html-comments.js @@ -37,10 +37,12 @@ function tokenize(code, option) { const linter = new Linter() const result = [] - linter.defineRule('vue/html-comments-test', (content) => - htmlComments.defineVisitor(content, option, (commentTokens) => { - result.push(commentTokens) - }) + linter.defineRule( + 'vue/html-comments-test', + (content) => + htmlComments.defineVisitor(content, option, (commentTokens) => { + result.push(commentTokens) + }) ) linter.defineParser('vue-eslint-parser', require('vue-eslint-parser')) linter.verify( diff --git ORI/prettier/scripts/release/steps/update-dependents-count.js ALT/prettier/scripts/release/steps/update-dependents-count.js index b8e717537..066fa9ffc 100644 --- ORI/prettier/scripts/release/steps/update-dependents-count.js +++ ALT/prettier/scripts/release/steps/update-dependents-count.js @@ -41,16 +41,18 @@ async function update() { ); } - processFile("website/pages/en/index.js", (content) => - content - .replace( - /()(.*?)(<\/strong>)/, - `$1${formatNumber(dependentsCountNpm)}$3` - ) - .replace( - /()(.*?)(<\/strong>)/, - `$1${formatNumber(dependentsCountGithub)}$3` - ) + processFile( + "website/pages/en/index.js", + (content) => + content + .replace( + /()(.*?)(<\/strong>)/, + `$1${formatNumber(dependentsCountNpm)}$3` + ) + .replace( + /()(.*?)(<\/strong>)/, + `$1${formatNumber(dependentsCountGithub)}$3` + ) ); const isUpdated = await logPromise( diff --git ORI/prettier/scripts/release/steps/update-version.js ALT/prettier/scripts/release/steps/update-version.js index 081820765..cdf24f1a4 100644 --- ORI/prettier/scripts/release/steps/update-version.js +++ ALT/prettier/scripts/release/steps/update-version.js @@ -9,19 +9,25 @@ async function bump({ version }) { await writeJson("package.json", pkg, { spaces: 2 }); // Update github issue templates - processFile(".github/ISSUE_TEMPLATE/formatting.md", (content) => - content.replace(/^(\*\*Prettier ).*?(\*\*)$/m, `$1${version}$2`) + processFile( + ".github/ISSUE_TEMPLATE/formatting.md", + (content) => + content.replace(/^(\*\*Prettier ).*?(\*\*)$/m, `$1${version}$2`) ); - processFile(".github/ISSUE_TEMPLATE/integration.md", (content) => - content.replace(/^(- Prettier Version: ).*?$/m, `$1${version}`) + processFile( + ".github/ISSUE_TEMPLATE/integration.md", + (content) => content.replace(/^(- Prettier Version: ).*?$/m, `$1${version}`) ); - processFile("docs/install.md", (content) => - content.replace(/^(npx prettier@)\S+/m, `$1${version}`) + processFile( + "docs/install.md", + (content) => content.replace(/^(npx prettier@)\S+/m, `$1${version}`) ); // Update unpkg link in docs - processFile("docs/browser.md", (content) => - content.replace(/(\/\/unpkg\.com\/prettier@).*?\//g, `$1${version}/`) + processFile( + "docs/browser.md", + (content) => + content.replace(/(\/\/unpkg\.com\/prettier@).*?\//g, `$1${version}/`) ); await execa("yarn", ["update-stable-docs"], { diff --git ORI/prettier/src/document/doc-utils.js ALT/prettier/src/document/doc-utils.js index 738527336..2c3addedf 100644 --- ORI/prettier/src/document/doc-utils.js +++ ALT/prettier/src/document/doc-utils.js @@ -343,29 +343,34 @@ function normalizeParts(parts) { } function normalizeDoc(doc) { - return mapDoc(doc, (currentDoc) => { - if (Array.isArray(currentDoc)) { - return normalizeParts(currentDoc); - } - if (!currentDoc.parts) { - return currentDoc; + return mapDoc( + doc, + (currentDoc) => { + if (Array.isArray(currentDoc)) { + return normalizeParts(currentDoc); + } + if (!currentDoc.parts) { + return currentDoc; + } + return { + ...currentDoc, + parts: normalizeParts(currentDoc.parts), + }; } - return { - ...currentDoc, - parts: normalizeParts(currentDoc.parts), - }; - }); + ); } function replaceNewlinesWithLiterallines(doc) { - return mapDoc(doc, (currentDoc) => - typeof currentDoc === "string" && currentDoc.includes("\n") - ? concat( - currentDoc - .split(/(\n)/g) - .map((v, i) => (i % 2 === 0 ? v : literalline)) - ) - : currentDoc + return mapDoc( + doc, + (currentDoc) => + typeof currentDoc === "string" && currentDoc.includes("\n") + ? concat( + currentDoc + .split(/(\n)/g) + .map((v, i) => (i % 2 === 0 ? v : literalline)) + ) + : currentDoc ); } diff --git ORI/prettier/src/language-css/index.js ALT/prettier/src/language-css/index.js index c69c43461..1f881d51d 100644 --- ORI/prettier/src/language-css/index.js +++ ALT/prettier/src/language-css/index.js @@ -5,32 +5,44 @@ const printer = require("./printer-postcss"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/CSS.json"), (data) => ({ - since: "1.4.0", - parsers: ["css"], - vscodeLanguageIds: ["css"], - extensions: [ - ...data.extensions, - // `WeiXin Style Sheets`(Weixin Mini Programs) - // https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/ - ".wxss", - ], - })), - createLanguage(require("linguist-languages/data/PostCSS.json"), () => ({ - since: "1.4.0", - parsers: ["css"], - vscodeLanguageIds: ["postcss"], - })), - createLanguage(require("linguist-languages/data/Less.json"), () => ({ - since: "1.4.0", - parsers: ["less"], - vscodeLanguageIds: ["less"], - })), - createLanguage(require("linguist-languages/data/SCSS.json"), () => ({ - since: "1.4.0", - parsers: ["scss"], - vscodeLanguageIds: ["scss"], - })), + createLanguage( + require("linguist-languages/data/CSS.json"), + (data) => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["css"], + extensions: [ + ...data.extensions, + // `WeiXin Style Sheets`(Weixin Mini Programs) + // https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/ + ".wxss", + ], + }) + ), + createLanguage( + require("linguist-languages/data/PostCSS.json"), + () => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["postcss"], + }) + ), + createLanguage( + require("linguist-languages/data/Less.json"), + () => ({ + since: "1.4.0", + parsers: ["less"], + vscodeLanguageIds: ["less"], + }) + ), + createLanguage( + require("linguist-languages/data/SCSS.json"), + () => ({ + since: "1.4.0", + parsers: ["scss"], + vscodeLanguageIds: ["scss"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-graphql/index.js ALT/prettier/src/language-graphql/index.js index b991a850f..c3f9a6367 100644 --- ORI/prettier/src/language-graphql/index.js +++ ALT/prettier/src/language-graphql/index.js @@ -5,11 +5,14 @@ const printer = require("./printer-graphql"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/GraphQL.json"), () => ({ - since: "1.5.0", - parsers: ["graphql"], - vscodeLanguageIds: ["graphql"], - })), + createLanguage( + require("linguist-languages/data/GraphQL.json"), + () => ({ + since: "1.5.0", + parsers: ["graphql"], + vscodeLanguageIds: ["graphql"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-handlebars/index.js ALT/prettier/src/language-handlebars/index.js index 01e35dd96..be3e56fbb 100644 --- ORI/prettier/src/language-handlebars/index.js +++ ALT/prettier/src/language-handlebars/index.js @@ -4,11 +4,14 @@ const createLanguage = require("../utils/create-language"); const printer = require("./printer-glimmer"); const languages = [ - createLanguage(require("linguist-languages/data/Handlebars.json"), () => ({ - since: null, // unreleased - parsers: ["glimmer"], - vscodeLanguageIds: ["handlebars"], - })), + createLanguage( + require("linguist-languages/data/Handlebars.json"), + () => ({ + since: null, // unreleased + parsers: ["glimmer"], + vscodeLanguageIds: ["handlebars"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-html/index.js ALT/prettier/src/language-html/index.js index 1caf94c65..20e9d77b6 100644 --- ORI/prettier/src/language-html/index.js +++ ALT/prettier/src/language-html/index.js @@ -5,36 +5,48 @@ const printer = require("./printer-html"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/HTML.json"), () => ({ - name: "Angular", - since: "1.15.0", - parsers: ["angular"], - vscodeLanguageIds: ["html"], - extensions: [".component.html"], - filenames: [], - })), - createLanguage(require("linguist-languages/data/HTML.json"), (data) => ({ - since: "1.15.0", - parsers: ["html"], - vscodeLanguageIds: ["html"], - extensions: [ - ...data.extensions, - ".mjml", // MJML is considered XML in Linguist but it should be formatted as HTML - ], - })), - createLanguage(require("linguist-languages/data/HTML.json"), () => ({ - name: "Lightning Web Components", - since: "1.17.0", - parsers: ["lwc"], - vscodeLanguageIds: ["html"], - extensions: [], - filenames: [], - })), - createLanguage(require("linguist-languages/data/Vue.json"), () => ({ - since: "1.10.0", - parsers: ["vue"], - vscodeLanguageIds: ["vue"], - })), + createLanguage( + require("linguist-languages/data/HTML.json"), + () => ({ + name: "Angular", + since: "1.15.0", + parsers: ["angular"], + vscodeLanguageIds: ["html"], + extensions: [".component.html"], + filenames: [], + }) + ), + createLanguage( + require("linguist-languages/data/HTML.json"), + (data) => ({ + since: "1.15.0", + parsers: ["html"], + vscodeLanguageIds: ["html"], + extensions: [ + ...data.extensions, + ".mjml", // MJML is considered XML in Linguist but it should be formatted as HTML + ], + }) + ), + createLanguage( + require("linguist-languages/data/HTML.json"), + () => ({ + name: "Lightning Web Components", + since: "1.17.0", + parsers: ["lwc"], + vscodeLanguageIds: ["html"], + extensions: [], + filenames: [], + }) + ), + createLanguage( + require("linguist-languages/data/Vue.json"), + () => ({ + since: "1.10.0", + parsers: ["vue"], + vscodeLanguageIds: ["vue"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-html/printer-html.js ALT/prettier/src/language-html/printer-html.js index 46aec9c30..40fbf2a41 100644 --- ORI/prettier/src/language-html/printer-html.js +++ ALT/prettier/src/language-html/printer-html.js @@ -199,8 +199,10 @@ function embed(path, print, textToDoc, options) { node.rawName, '="', group( - mapDoc(embeddedAttributeValueDoc, (doc) => - typeof doc === "string" ? doc.replace(/"/g, """) : doc + mapDoc( + embeddedAttributeValueDoc, + (doc) => + typeof doc === "string" ? doc.replace(/"/g, """) : doc ) ), '"', diff --git ORI/prettier/src/language-js/embed/css.js ALT/prettier/src/language-js/embed/css.js index 7ff50144c..15bf46eeb 100644 --- ORI/prettier/src/language-js/embed/css.js +++ ALT/prettier/src/language-js/embed/css.js @@ -57,23 +57,28 @@ function replacePlaceholders(quasisDoc, expressionDocs) { return quasisDoc; } let replaceCounter = 0; - const newDoc = mapDoc(cleanDoc(quasisDoc), (doc) => { - if (typeof doc !== "string" || !doc.includes("@prettier-placeholder")) { - return doc; - } - // When we have multiple placeholders in one line, like: - // ${Child}${Child2}:not(:first-child) - return doc.split(/@prettier-placeholder-(\d+)-id/).map((component, idx) => { - // The placeholder is always at odd indices - if (idx % 2 === 0) { - return replaceNewlinesWithLiterallines(component); + const newDoc = mapDoc( + cleanDoc(quasisDoc), + (doc) => { + if (typeof doc !== "string" || !doc.includes("@prettier-placeholder")) { + return doc; } + // When we have multiple placeholders in one line, like: + // ${Child}${Child2}:not(:first-child) + return doc + .split(/@prettier-placeholder-(\d+)-id/) + .map((component, idx) => { + // The placeholder is always at odd indices + if (idx % 2 === 0) { + return replaceNewlinesWithLiterallines(component); + } - // The component will always be a number at odd index - replaceCounter++; - return expressionDocs[component]; - }); - }); + // The component will always be a number at odd index + replaceCounter++; + return expressionDocs[component]; + }); + } + ); return expressionDocs.length === replaceCounter ? newDoc : null; } diff --git ORI/prettier/src/language-js/embed/html.js ALT/prettier/src/language-js/embed/html.js index cb2e41306..b4fbd9610 100644 --- ORI/prettier/src/language-js/embed/html.js +++ ALT/prettier/src/language-js/embed/html.js @@ -45,34 +45,37 @@ function format(path, print, textToDoc, options, { parser }) { { stripTrailingHardline: true } ); - const contentDoc = mapDoc(doc, (doc) => { - if (typeof doc !== "string") { - return doc; - } + const contentDoc = mapDoc( + doc, + (doc) => { + if (typeof doc !== "string") { + return doc; + } - const parts = []; + const parts = []; - const components = doc.split(placeholderRegex); - for (let i = 0; i < components.length; i++) { - let component = components[i]; + const components = doc.split(placeholderRegex); + for (let i = 0; i < components.length; i++) { + let component = components[i]; - if (i % 2 === 0) { - if (component) { - component = uncookTemplateElementValue(component); - if (options.embeddedInHtml) { - component = component.replace(/<\/(script)\b/gi, "<\\/$1"); + if (i % 2 === 0) { + if (component) { + component = uncookTemplateElementValue(component); + if (options.embeddedInHtml) { + component = component.replace(/<\/(script)\b/gi, "<\\/$1"); + } + parts.push(component); } - parts.push(component); + continue; } - continue; + + const placeholderIndex = +component; + parts.push(expressionDocs[placeholderIndex]); } - const placeholderIndex = +component; - parts.push(expressionDocs[placeholderIndex]); + return parts; } - - return parts; - }); + ); const leadingWhitespace = /^\s/.test(text) ? " " : ""; const trailingWhitespace = /\s$/.test(text) ? " " : ""; diff --git ORI/prettier/src/language-js/index.js ALT/prettier/src/language-js/index.js index dd35ccd6c..e4e2493cb 100644 --- ORI/prettier/src/language-js/index.js +++ ALT/prettier/src/language-js/index.js @@ -28,52 +28,70 @@ const languages = [ ], }) ), - createLanguage(require("linguist-languages/data/JavaScript.json"), () => ({ - name: "Flow", - since: "0.0.0", - parsers: ["flow", "babel-flow"], - vscodeLanguageIds: ["javascript"], - aliases: [], - filenames: [], - extensions: [".js.flow"], - })), - createLanguage(require("linguist-languages/data/JSX.json"), () => ({ - since: "0.0.0", - parsers: [ - "babel", - "babel-flow", - "babel-ts", - "flow", - "typescript", - "espree", - "meriyah", - ], - vscodeLanguageIds: ["javascriptreact"], - })), - createLanguage(require("linguist-languages/data/TypeScript.json"), () => ({ - since: "1.4.0", - parsers: ["typescript", "babel-ts"], - vscodeLanguageIds: ["typescript"], - })), - createLanguage(require("linguist-languages/data/TSX.json"), () => ({ - since: "1.4.0", - parsers: ["typescript", "babel-ts"], - vscodeLanguageIds: ["typescriptreact"], - })), - createLanguage(require("linguist-languages/data/JSON.json"), () => ({ - name: "JSON.stringify", - since: "1.13.0", - parsers: ["json-stringify"], - vscodeLanguageIds: ["json"], - extensions: [], // .json file defaults to json instead of json-stringify - filenames: ["package.json", "package-lock.json", "composer.json"], - })), - createLanguage(require("linguist-languages/data/JSON.json"), (data) => ({ - since: "1.5.0", - parsers: ["json"], - vscodeLanguageIds: ["json"], - extensions: data.extensions.filter((extension) => extension !== ".jsonl"), - })), + createLanguage( + require("linguist-languages/data/JavaScript.json"), + () => ({ + name: "Flow", + since: "0.0.0", + parsers: ["flow", "babel-flow"], + vscodeLanguageIds: ["javascript"], + aliases: [], + filenames: [], + extensions: [".js.flow"], + }) + ), + createLanguage( + require("linguist-languages/data/JSX.json"), + () => ({ + since: "0.0.0", + parsers: [ + "babel", + "babel-flow", + "babel-ts", + "flow", + "typescript", + "espree", + "meriyah", + ], + vscodeLanguageIds: ["javascriptreact"], + }) + ), + createLanguage( + require("linguist-languages/data/TypeScript.json"), + () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescript"], + }) + ), + createLanguage( + require("linguist-languages/data/TSX.json"), + () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescriptreact"], + }) + ), + createLanguage( + require("linguist-languages/data/JSON.json"), + () => ({ + name: "JSON.stringify", + since: "1.13.0", + parsers: ["json-stringify"], + vscodeLanguageIds: ["json"], + extensions: [], // .json file defaults to json instead of json-stringify + filenames: ["package.json", "package-lock.json", "composer.json"], + }) + ), + createLanguage( + require("linguist-languages/data/JSON.json"), + (data) => ({ + since: "1.5.0", + parsers: ["json"], + vscodeLanguageIds: ["json"], + extensions: data.extensions.filter((extension) => extension !== ".jsonl"), + }) + ), createLanguage( require("linguist-languages/data/JSON with Comments.json"), (data) => ({ @@ -83,11 +101,14 @@ const languages = [ filenames: [...data.filenames, ".eslintrc"], }) ), - createLanguage(require("linguist-languages/data/JSON5.json"), () => ({ - since: "1.13.0", - parsers: ["json5"], - vscodeLanguageIds: ["json5"], - })), + createLanguage( + require("linguist-languages/data/JSON5.json"), + () => ({ + since: "1.13.0", + parsers: ["json5"], + vscodeLanguageIds: ["json5"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-js/parse-postprocess.js ALT/prettier/src/language-js/parse-postprocess.js index d74e063cc..2876a7d05 100644 --- ORI/prettier/src/language-js/parse-postprocess.js +++ ALT/prettier/src/language-js/parse-postprocess.js @@ -23,41 +23,44 @@ function postprocess(ast, options) { if (options.parser === "typescript" && options.originalText.includes("@")) { const { esTreeNodeToTSNodeMap, tsNodeToESTreeNodeMap } = options.tsParseResult; - ast = visitNode(ast, (node) => { - const tsNode = esTreeNodeToTSNodeMap.get(node); - if (!tsNode) { - return; - } - const tsDecorators = tsNode.decorators; - if (!Array.isArray(tsDecorators)) { - return; - } - // `esTreeNodeToTSNodeMap.get(ClassBody)` and `esTreeNodeToTSNodeMap.get(ClassDeclaration)` has the same tsNode - const esTreeNode = tsNodeToESTreeNodeMap.get(tsNode); - if (esTreeNode !== node) { - return; - } - const esTreeDecorators = esTreeNode.decorators; - if ( - !Array.isArray(esTreeDecorators) || - esTreeDecorators.length !== tsDecorators.length || - tsDecorators.some((tsDecorator) => { - const esTreeDecorator = tsNodeToESTreeNodeMap.get(tsDecorator); - return ( - !esTreeDecorator || !esTreeDecorators.includes(esTreeDecorator) + ast = visitNode( + ast, + (node) => { + const tsNode = esTreeNodeToTSNodeMap.get(node); + if (!tsNode) { + return; + } + const tsDecorators = tsNode.decorators; + if (!Array.isArray(tsDecorators)) { + return; + } + // `esTreeNodeToTSNodeMap.get(ClassBody)` and `esTreeNodeToTSNodeMap.get(ClassDeclaration)` has the same tsNode + const esTreeNode = tsNodeToESTreeNodeMap.get(tsNode); + if (esTreeNode !== node) { + return; + } + const esTreeDecorators = esTreeNode.decorators; + if ( + !Array.isArray(esTreeDecorators) || + esTreeDecorators.length !== tsDecorators.length || + tsDecorators.some((tsDecorator) => { + const esTreeDecorator = tsNodeToESTreeNodeMap.get(tsDecorator); + return ( + !esTreeDecorator || !esTreeDecorators.includes(esTreeDecorator) + ); + }) + ) { + const { start, end } = esTreeNode.loc; + throw createError( + "Leading decorators must be attached to a class declaration", + { + start: { line: start.line, column: start.column + 1 }, + end: { line: end.line, column: end.column + 1 }, + } ); - }) - ) { - const { start, end } = esTreeNode.loc; - throw createError( - "Leading decorators must be attached to a class declaration", - { - start: { line: start.line, column: start.column + 1 }, - end: { line: end.line, column: end.column + 1 }, - } - ); + } } - }); + ); } // Keep Babel's non-standard ParenthesizedExpression nodes only if they have Closure-style type cast comments. @@ -73,105 +76,114 @@ 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. - ast = visitNode(ast, (node) => { - if ( - node.leadingComments && - node.leadingComments.some(isTypeCastComment) - ) { - startOffsetsOfTypeCastedNodes.add(locStart(node)); + ast = visitNode( + ast, + (node) => { + if ( + node.leadingComments && + node.leadingComments.some(isTypeCastComment) + ) { + startOffsetsOfTypeCastedNodes.add(locStart(node)); + } } - }); + ); - ast = visitNode(ast, (node) => { - if (node.type === "ParenthesizedExpression") { - const { expression } = node; + ast = visitNode( + ast, + (node) => { + if (node.type === "ParenthesizedExpression") { + const { expression } = node; - // Align range with `flow` - if (expression.type === "TypeCastExpression") { - expression.range = node.range; - return expression; - } + // Align range with `flow` + if (expression.type === "TypeCastExpression") { + expression.range = node.range; + return expression; + } - const start = locStart(node); - if (!startOffsetsOfTypeCastedNodes.has(start)) { - expression.extra = { ...expression.extra, parenthesized: true }; - return expression; + const start = locStart(node); + if (!startOffsetsOfTypeCastedNodes.has(start)) { + expression.extra = { ...expression.extra, parenthesized: true }; + return expression; + } } } - }); + ); } - ast = visitNode(ast, (node) => { - switch (node.type) { - // Espree - case "ChainExpression": { - return transformChainExpression(node.expression); - } - case "LogicalExpression": { - // We remove unneeded parens around same-operator LogicalExpressions - if (isUnbalancedLogicalTree(node)) { - return rebalanceLogicalTree(node); + ast = visitNode( + ast, + (node) => { + switch (node.type) { + // Espree + case "ChainExpression": { + return transformChainExpression(node.expression); } - break; - } - // fix unexpected locEnd caused by --no-semi style - case "VariableDeclaration": { - const lastDeclaration = getLast(node.declarations); - if (lastDeclaration && lastDeclaration.init) { - overrideLocEnd(node, lastDeclaration); + case "LogicalExpression": { + // We remove unneeded parens around same-operator LogicalExpressions + if (isUnbalancedLogicalTree(node)) { + return rebalanceLogicalTree(node); + } + break; } - break; - } - // remove redundant TypeScript nodes - case "TSParenthesizedType": { - node.typeAnnotation.range = [locStart(node), locEnd(node)]; - return node.typeAnnotation; - } - case "TSUnionType": - case "TSIntersectionType": - if (node.types.length === 1) { - const [firstType] = node.types; - // override loc, so that comments are attached properly - firstType.range = [locStart(node), locEnd(node)]; - return firstType; + // fix unexpected locEnd caused by --no-semi style + case "VariableDeclaration": { + const lastDeclaration = getLast(node.declarations); + if (lastDeclaration && lastDeclaration.init) { + overrideLocEnd(node, lastDeclaration); + } + break; } - break; - case "TSTypeParameter": - // babel-ts - if (typeof node.name === "string") { - const start = locStart(node); - node.name = { - type: "Identifier", - name: node.name, - range: [start, start + node.name.length], - }; + // remove redundant TypeScript nodes + case "TSParenthesizedType": { + node.typeAnnotation.range = [locStart(node), locEnd(node)]; + return node.typeAnnotation; } - break; - case "SequenceExpression": { - // Babel (unlike other parsers) includes spaces and comments in the range. Let's unify this. - const lastExpression = getLast(node.expressions); - node.range = [ - locStart(node), - Math.min(locEnd(lastExpression), locEnd(node)), - ]; - break; - } - case "ClassProperty": - // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields. - if ( - node.key && - node.key.type === "TSPrivateIdentifier" && - getNextNonSpaceNonCommentCharacter( - options.originalText, - node.key, - locEnd - ) === "?" - ) { - node.optional = true; + case "TSUnionType": + case "TSIntersectionType": + if (node.types.length === 1) { + const [firstType] = node.types; + // override loc, so that comments are attached properly + firstType.range = [locStart(node), locEnd(node)]; + return firstType; + } + break; + case "TSTypeParameter": + // babel-ts + if (typeof node.name === "string") { + const start = locStart(node); + node.name = { + type: "Identifier", + name: node.name, + range: [start, start + node.name.length], + }; + } + break; + case "SequenceExpression": { + // Babel (unlike other parsers) includes spaces and comments in the range. Let's unify this. + const lastExpression = getLast(node.expressions); + node.range = [ + locStart(node), + Math.min(locEnd(lastExpression), locEnd(node)), + ]; + break; } - break; + case "ClassProperty": + // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields. + if ( + node.key && + node.key.type === "TSPrivateIdentifier" && + getNextNonSpaceNonCommentCharacter( + options.originalText, + node.key, + locEnd + ) === "?" + ) { + node.optional = true; + } + break; + } } - }); + ); return ast; diff --git ORI/prettier/src/language-js/print/angular.js ALT/prettier/src/language-js/print/angular.js index d95da9c40..6372218df 100644 --- ORI/prettier/src/language-js/print/angular.js +++ ALT/prettier/src/language-js/print/angular.js @@ -103,16 +103,19 @@ function isNgForOf(node, index, parentNode) { * @returns {boolean} */ function hasNgSideEffect(path) { - return hasNode(path.getValue(), (node) => { - switch (node.type) { - case undefined: - return false; - case "CallExpression": - case "OptionalCallExpression": - case "AssignmentExpression": - return true; + return hasNode( + path.getValue(), + (node) => { + switch (node.type) { + case undefined: + return false; + case "CallExpression": + case "OptionalCallExpression": + case "AssignmentExpression": + return true; + } } - }); + ); } module.exports = { printAngular }; diff --git ORI/prettier/src/language-js/print/template-literal.js ALT/prettier/src/language-js/print/template-literal.js index 23e5d5692..b24e51bb0 100644 --- ORI/prettier/src/language-js/print/template-literal.js +++ ALT/prettier/src/language-js/print/template-literal.js @@ -216,15 +216,18 @@ function printTemplateExpressions(path, print) { } function escapeTemplateCharacters(doc, raw) { - return mapDoc(doc, (currentDoc) => { - if (typeof currentDoc === "string") { - return raw - ? currentDoc.replace(/(\\*)`/g, "$1$1\\`") - : uncookTemplateElementValue(currentDoc); - } + return mapDoc( + doc, + (currentDoc) => { + if (typeof currentDoc === "string") { + return raw + ? currentDoc.replace(/(\\*)`/g, "$1$1\\`") + : uncookTemplateElementValue(currentDoc); + } - return currentDoc; - }); + return currentDoc; + } + ); } function uncookTemplateElementValue(cookedValue) { diff --git ORI/prettier/src/language-js/utils.js ALT/prettier/src/language-js/utils.js index 744685678..0b4fde320 100644 --- ORI/prettier/src/language-js/utils.js +++ ALT/prettier/src/language-js/utils.js @@ -684,8 +684,10 @@ function hasLeadingOwnLineComment(text, node) { return hasNodeIgnoreComment(node); } - return hasComment(node, CommentCheckFlags.Leading, (comment) => - hasNewline(text, locEnd(comment)) + return hasComment( + node, + CommentCheckFlags.Leading, + (comment) => hasNewline(text, locEnd(comment)) ); } diff --git ORI/prettier/src/language-markdown/index.js ALT/prettier/src/language-markdown/index.js index 994023c43..3ce09f693 100644 --- ORI/prettier/src/language-markdown/index.js +++ ALT/prettier/src/language-markdown/index.js @@ -5,21 +5,27 @@ const printer = require("./printer-markdown"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/Markdown.json"), (data) => ({ - since: "1.8.0", - parsers: ["markdown"], - vscodeLanguageIds: ["markdown"], - filenames: [...data.filenames, "README"], - extensions: data.extensions.filter((extension) => extension !== ".mdx"), - })), - createLanguage(require("linguist-languages/data/Markdown.json"), () => ({ - name: "MDX", - since: "1.15.0", - parsers: ["mdx"], - vscodeLanguageIds: ["mdx"], - filenames: [], - extensions: [".mdx"], - })), + createLanguage( + require("linguist-languages/data/Markdown.json"), + (data) => ({ + since: "1.8.0", + parsers: ["markdown"], + vscodeLanguageIds: ["markdown"], + filenames: [...data.filenames, "README"], + extensions: data.extensions.filter((extension) => extension !== ".mdx"), + }) + ), + createLanguage( + require("linguist-languages/data/Markdown.json"), + () => ({ + name: "MDX", + since: "1.15.0", + parsers: ["mdx"], + vscodeLanguageIds: ["mdx"], + filenames: [], + extensions: [".mdx"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-markdown/parser-markdown.js ALT/prettier/src/language-markdown/parser-markdown.js index 494b77977..7927cc7ff 100644 --- ORI/prettier/src/language-markdown/parser-markdown.js +++ ALT/prettier/src/language-markdown/parser-markdown.js @@ -49,17 +49,20 @@ function identity(x) { function htmlToJsx() { return (ast) => - mapAst(ast, (node, _index, [parent]) => { - if ( - node.type !== "html" || - mdx.COMMENT_REGEX.test(node.value) || - INLINE_NODE_WRAPPER_TYPES.includes(parent.type) - ) { - return node; + mapAst( + ast, + (node, _index, [parent]) => { + if ( + node.type !== "html" || + mdx.COMMENT_REGEX.test(node.value) || + INLINE_NODE_WRAPPER_TYPES.includes(parent.type) + ) { + return node; + } + + return { ...node, type: "jsx" }; } - - return { ...node, type: "jsx" }; - }); + ); } function frontMatter() { diff --git ORI/prettier/src/language-markdown/print-preprocess.js ALT/prettier/src/language-markdown/print-preprocess.js index fcbac279a..502573676 100644 --- ORI/prettier/src/language-markdown/print-preprocess.js +++ ALT/prettier/src/language-markdown/print-preprocess.js @@ -19,40 +19,49 @@ function preprocess(ast, options) { } function transformImportExport(ast) { - return mapAst(ast, (node) => { - if (node.type !== "import" && node.type !== "export") { - return node; - } + return mapAst( + ast, + (node) => { + if (node.type !== "import" && node.type !== "export") { + return node; + } - return { ...node, type: "importExport" }; - }); + return { ...node, type: "importExport" }; + } + ); } function transformInlineCode(ast) { - return mapAst(ast, (node) => { - if (node.type !== "inlineCode") { - return node; - } + return mapAst( + ast, + (node) => { + if (node.type !== "inlineCode") { + return node; + } - return { ...node, value: node.value.replace(/\s+/g, " ") }; - }); + return { ...node, value: node.value.replace(/\s+/g, " ") }; + } + ); } function restoreUnescapedCharacter(ast, options) { - return mapAst(ast, (node) => - node.type !== "text" || - node.value === "*" || - node.value === "_" || // handle these cases in printer - !isSingleCharRegex.test(node.value) || - node.position.end.offset - node.position.start.offset === node.value.length - ? node - : { - ...node, - value: options.originalText.slice( - node.position.start.offset, - node.position.end.offset - ), - } + return mapAst( + ast, + (node) => + node.type !== "text" || + node.value === "*" || + node.value === "_" || // handle these cases in printer + !isSingleCharRegex.test(node.value) || + node.position.end.offset - node.position.start.offset === + node.value.length + ? node + : { + ...node, + value: options.originalText.slice( + node.position.start.offset, + node.position.end.offset + ), + } ); } @@ -73,21 +82,24 @@ function mergeContinuousImportExport(ast) { } function mergeChildren(ast, shouldMerge, mergeNode) { - return mapAst(ast, (node) => { - if (!node.children) { - return node; - } - const children = node.children.reduce((current, child) => { - const lastChild = current[current.length - 1]; - if (lastChild && shouldMerge(lastChild, child)) { - current.splice(-1, 1, mergeNode(lastChild, child)); - } else { - current.push(child); + return mapAst( + ast, + (node) => { + if (!node.children) { + return node; } - return current; - }, []); - return { ...node, children }; - }); + const children = node.children.reduce((current, child) => { + const lastChild = current[current.length - 1]; + if (lastChild && shouldMerge(lastChild, child)) { + current.splice(-1, 1, mergeNode(lastChild, child)); + } else { + current.push(child); + } + return current; + }, []); + return { ...node, children }; + } + ); } function mergeContinuousTexts(ast) { @@ -106,79 +118,88 @@ function mergeContinuousTexts(ast) { } function splitTextIntoSentences(ast, options) { - return mapAst(ast, (node, index, [parentNode]) => { - if (node.type !== "text") { - return node; - } + return mapAst( + ast, + (node, index, [parentNode]) => { + if (node.type !== "text") { + return node; + } - let { value } = node; + let { value } = node; - if (parentNode.type === "paragraph") { - if (index === 0) { - value = value.trimStart(); - } - if (index === parentNode.children.length - 1) { - value = value.trimEnd(); + if (parentNode.type === "paragraph") { + if (index === 0) { + value = value.trimStart(); + } + if (index === parentNode.children.length - 1) { + value = value.trimEnd(); + } } - } - return { - type: "sentence", - position: node.position, - children: splitText(value, options), - }; - }); + return { + type: "sentence", + position: node.position, + children: splitText(value, options), + }; + } + ); } function transformIndentedCodeblockAndMarkItsParentList(ast, options) { - return mapAst(ast, (node, index, parentStack) => { - if (node.type === "code") { - // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it - const isIndented = /^\n?( {4,}|\t)/.test( - options.originalText.slice( - node.position.start.offset, - node.position.end.offset - ) - ); - - node.isIndented = isIndented; - - if (isIndented) { - for (let i = 0; i < parentStack.length; i++) { - const parent = parentStack[i]; + return mapAst( + ast, + (node, index, parentStack) => { + if (node.type === "code") { + // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it + const isIndented = /^\n?( {4,}|\t)/.test( + options.originalText.slice( + node.position.start.offset, + node.position.end.offset + ) + ); - // no need to check checked items - if (parent.hasIndentedCodeblock) { - break; - } + node.isIndented = isIndented; - if (parent.type === "list") { - parent.hasIndentedCodeblock = true; + if (isIndented) { + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; + + // no need to check checked items + if (parent.hasIndentedCodeblock) { + break; + } + + if (parent.type === "list") { + parent.hasIndentedCodeblock = true; + } } } } + return node; } - return node; - }); + ); } function markAlignedList(ast, options) { - return mapAst(ast, (node, index, parentStack) => { - if (node.type === "list" && node.children.length > 0) { - // if one of its parents is not aligned, it's not possible to be aligned in sub-lists - for (let i = 0; i < parentStack.length; i++) { - const parent = parentStack[i]; - if (parent.type === "list" && !parent.isAligned) { - node.isAligned = false; - return node; + return mapAst( + ast, + (node, index, parentStack) => { + if (node.type === "list" && node.children.length > 0) { + // if one of its parents is not aligned, it's not possible to be aligned in sub-lists + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; + if (parent.type === "list" && !parent.isAligned) { + node.isAligned = false; + return node; + } } + + node.isAligned = isAligned(node); } - node.isAligned = isAligned(node); + return node; } - - return node; - }); + ); function getListItemStart(listItem) { return listItem.children.length === 0 diff --git ORI/prettier/src/language-markdown/printer-markdown.js ALT/prettier/src/language-markdown/printer-markdown.js index 179132dc2..7f346feac 100644 --- ORI/prettier/src/language-markdown/printer-markdown.js +++ ALT/prettier/src/language-markdown/printer-markdown.js @@ -129,8 +129,9 @@ function genericPrint(path, options, print) { )) ) { // backslash is parsed as part of autolinks, so we need to remove it - escapedValue = escapedValue.replace(/^(\\?[*_])+/, (prefix) => - prefix.replace(/\\/g, "") + escapedValue = escapedValue.replace( + /^(\\?[*_])+/, + (prefix) => prefix.replace(/\\/g, "") ); } diff --git ORI/prettier/src/language-yaml/index.js ALT/prettier/src/language-yaml/index.js index 7205e75d8..b74e7514f 100644 --- ORI/prettier/src/language-yaml/index.js +++ ALT/prettier/src/language-yaml/index.js @@ -5,16 +5,19 @@ const printer = require("./printer-yaml"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/YAML.json"), (data) => ({ - since: "1.14.0", - parsers: ["yaml"], - vscodeLanguageIds: ["yaml", "ansible", "home-assistant"], - // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629 - filenames: [ - ...data.filenames.filter((filename) => filename !== "yarn.lock"), - ".prettierrc", - ], - })), + createLanguage( + require("linguist-languages/data/YAML.json"), + (data) => ({ + since: "1.14.0", + parsers: ["yaml"], + vscodeLanguageIds: ["yaml", "ansible", "home-assistant"], + // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629 + filenames: [ + ...data.filenames.filter((filename) => filename !== "yarn.lock"), + ".prettierrc", + ], + }) + ), ]; const parsers = { diff --git ORI/prettier/src/language-yaml/print/block.js ALT/prettier/src/language-yaml/print/block.js index fcb603908..0b24de0f1 100644 --- ORI/prettier/src/language-yaml/print/block.js +++ ALT/prettier/src/language-yaml/print/block.js @@ -26,8 +26,9 @@ const { alignWithSpaces } = require("./misc"); function printBlock(path, print, options) { const node = path.getValue(); - const parentIndent = getAncestorCount(path, (ancestorNode) => - isNode(ancestorNode, ["sequence", "mapping"]) + const parentIndent = getAncestorCount( + path, + (ancestorNode) => isNode(ancestorNode, ["sequence", "mapping"]) ); const isLastDescendant = isLastDescendantNode(path); /** @type {Doc[]} */ diff --git ORI/prettier/tests_config/utils/stringify-options-for-title.js ALT/prettier/tests_config/utils/stringify-options-for-title.js index dbc95627f..b08780695 100644 --- ORI/prettier/tests_config/utils/stringify-options-for-title.js +++ ALT/prettier/tests_config/utils/stringify-options-for-title.js @@ -1,12 +1,14 @@ "use strict"; function stringifyOptions(options) { - const string = JSON.stringify(options || {}, (key, value) => - key === "plugins" || key === "errors" - ? undefined - : value === Number.POSITIVE_INFINITY - ? "Infinity" - : value + const string = JSON.stringify( + options || {}, + (key, value) => + key === "plugins" || key === "errors" + ? undefined + : value === Number.POSITIVE_INFINITY + ? "Infinity" + : value ); return string === "{}" ? "" : string; diff --git ORI/prettier/tests_integration/__tests__/stdin-filepath.js ALT/prettier/tests_integration/__tests__/stdin-filepath.js index 32cb97e23..51ab37825 100644 --- ORI/prettier/tests_integration/__tests__/stdin-filepath.js +++ ALT/prettier/tests_integration/__tests__/stdin-filepath.js @@ -4,31 +4,25 @@ const { isCI } = require("ci-info"); const runPrettier = require("../runPrettier"); describe("format correctly if stdin content compatible with stdin-filepath", () => { - runPrettier( - "cli", - ["--stdin-filepath", "abc.css"], - { input: ".name { display: none; }" } // css - ).test({ + runPrettier("cli", ["--stdin-filepath", "abc.css"], { + input: ".name { display: none; }", + }).test({ // css status: 0, }); }); describe("throw error if stdin content incompatible with stdin-filepath", () => { - runPrettier( - "cli", - ["--stdin-filepath", "abc.js"], - { input: ".name { display: none; }" } // css - ).test({ + runPrettier("cli", ["--stdin-filepath", "abc.js"], { + input: ".name { display: none; }", + }).test({ // css status: "non-zero", }); }); describe("gracefully handle stdin-filepath with nonexistent directory", () => { - runPrettier( - "cli", - ["--stdin-filepath", "definitely/nonexistent/path.css"], - { input: ".name { display: none; }" } // css - ).test({ + runPrettier("cli", ["--stdin-filepath", "definitely/nonexistent/path.css"], { + input: ".name { display: none; }", + }).test({ // css status: 0, }); }); diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/explicit-function-return-type.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/explicit-function-return-type.ts index f0904f07..b7987274 100644 --- ORI/typescript-eslint/packages/eslint-plugin/src/rules/explicit-function-return-type.ts +++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/explicit-function-return-type.ts @@ -82,21 +82,29 @@ export default util.createRule({ return; } - checkFunctionExpressionReturnType(node, options, sourceCode, loc => - context.report({ - node, - loc, - messageId: 'missingReturnType', - }), + checkFunctionExpressionReturnType( + node, + options, + sourceCode, + loc => + context.report({ + node, + loc, + messageId: 'missingReturnType', + }), ); }, FunctionDeclaration(node): void { - checkFunctionReturnType(node, options, sourceCode, loc => - context.report({ - node, - loc, - messageId: 'missingReturnType', - }), + checkFunctionReturnType( + node, + options, + sourceCode, + loc => + context.report({ + node, + loc, + messageId: 'missingReturnType', + }), ); }, }; diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts index 2ff89c59..9a3d132c 100644 --- ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts +++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts @@ -117,12 +117,14 @@ function getTypeParametersFromType( return undefined; } - return findFirstResult(declarations, decl => - tsutils.isClassLikeDeclaration(decl) || - ts.isTypeAliasDeclaration(decl) || - ts.isInterfaceDeclaration(decl) - ? decl.typeParameters - : undefined, + return findFirstResult( + declarations, + decl => + tsutils.isClassLikeDeclaration(decl) || + ts.isTypeAliasDeclaration(decl) || + ts.isInterfaceDeclaration(decl) + ? decl.typeParameters + : undefined, ); } diff --git ORI/typescript-eslint/packages/typescript-estree/src/node-utils.ts ALT/typescript-eslint/packages/typescript-estree/src/node-utils.ts index 74c58666..b976e9c9 100644 --- ORI/typescript-eslint/packages/typescript-estree/src/node-utils.ts +++ ALT/typescript-eslint/packages/typescript-estree/src/node-utils.ts @@ -367,16 +367,19 @@ export function findNextToken( // this is token that starts at the end of previous token - return it return n; } - return firstDefined(n.getChildren(ast), (child: ts.Node) => { - const shouldDiveInChildNode = - // previous token is enclosed somewhere in the child - (child.pos <= previousToken.pos && child.end > previousToken.end) || - // previous token ends exactly at the beginning of child - child.pos === previousToken.end; - return shouldDiveInChildNode && nodeHasTokens(child, ast) - ? find(child) - : undefined; - }); + return firstDefined( + n.getChildren(ast), + (child: ts.Node) => { + const shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + child.pos === previousToken.end; + return shouldDiveInChildNode && nodeHasTokens(child, ast) + ? find(child) + : undefined; + }, + ); } } diff --git ORI/vega-lite/src/compile/legend/encode.ts ALT/vega-lite/src/compile/legend/encode.ts index 180d8758e..c88a64f1f 100644 --- ORI/vega-lite/src/compile/legend/encode.ts +++ ALT/vega-lite/src/compile/legend/encode.ts @@ -181,9 +181,12 @@ function getMaxValue(channelDef: Encoding['opacity']) { export function getFirstConditionValue( channelDef: Encoding['fill' | 'stroke' | 'shape'] ): V { - return getConditionValue(channelDef, (v: V, conditionalDef: Conditional>) => { - return getFirstDefined(v, conditionalDef.value); - }); + return getConditionValue( + channelDef, + (v: V, conditionalDef: Conditional>) => { + return getFirstDefined(v, conditionalDef.value); + } + ); } function getConditionValue( diff --git ORI/vega-lite/src/compile/mark/encode/nonposition.ts ALT/vega-lite/src/compile/mark/encode/nonposition.ts index e6c5d58a3..390856f51 100644 --- ORI/vega-lite/src/compile/mark/encode/nonposition.ts +++ ALT/vega-lite/src/compile/mark/encode/nonposition.ts @@ -34,16 +34,21 @@ export function nonPosition( const channelDef = encoding[channel]; - return wrapCondition(model, channelDef, vgChannel ?? channel, cDef => { - return ref.midPoint({ - channel, - channelDef: cDef, - markDef, - config, - scaleName: model.scaleName(channel), - scale: model.getScaleComponent(channel), - stack: null, // No need to provide stack for non-position as it does not affect mid point - defaultRef - }); - }); + return wrapCondition( + model, + channelDef, + vgChannel ?? channel, + cDef => { + return ref.midPoint({ + channel, + channelDef: cDef, + markDef, + config, + scaleName: model.scaleName(channel), + scale: model.getScaleComponent(channel), + stack: null, // No need to provide stack for non-position as it does not affect mid point + defaultRef + }); + } + ); } diff --git ORI/vega-lite/src/compile/mark/encode/tooltip.ts ALT/vega-lite/src/compile/mark/encode/tooltip.ts index 1bf44ff88..9c24ac9cf 100644 --- ORI/vega-lite/src/compile/mark/encode/tooltip.ts +++ ALT/vega-lite/src/compile/mark/encode/tooltip.ts @@ -30,39 +30,44 @@ export function tooltip(model: UnitModel, opt: {reactiveGeom?: boolean} = {}) { return {tooltip: tooltipRefForEncoding({tooltip: channelDef}, stack, config, opt)}; } else { const datum = opt.reactiveGeom ? 'datum.datum' : 'datum'; - return wrapCondition(model, channelDef, 'tooltip', cDef => { - // use valueRef based on channelDef first - const tooltipRefFromChannelDef = textRef(cDef, config, datum); - if (tooltipRefFromChannelDef) { - return tooltipRefFromChannelDef; - } + return wrapCondition( + model, + channelDef, + 'tooltip', + cDef => { + // use valueRef based on channelDef first + const tooltipRefFromChannelDef = textRef(cDef, config, datum); + if (tooltipRefFromChannelDef) { + return tooltipRefFromChannelDef; + } - if (cDef === null) { - // Allow using encoding.tooltip = null to disable tooltip - return undefined; - } + if (cDef === null) { + // Allow using encoding.tooltip = null to disable tooltip + return undefined; + } - let markTooltip = getMarkPropOrConfig('tooltip', markDef, config); + let markTooltip = getMarkPropOrConfig('tooltip', markDef, config); - if (markTooltip === true) { - markTooltip = {content: 'encoding'}; - } + if (markTooltip === true) { + markTooltip = {content: 'encoding'}; + } - if (isString(markTooltip)) { - return {value: markTooltip}; - } else if (isObject(markTooltip)) { - // `tooltip` is `{fields: 'encodings' | 'fields'}` - if (isSignalRef(markTooltip)) { - return markTooltip; - } else if (markTooltip.content === 'encoding') { - return tooltipRefForEncoding(encoding, stack, config, opt); - } else { - return {signal: datum}; + if (isString(markTooltip)) { + return {value: markTooltip}; + } else if (isObject(markTooltip)) { + // `tooltip` is `{fields: 'encodings' | 'fields'}` + if (isSignalRef(markTooltip)) { + return markTooltip; + } else if (markTooltip.content === 'encoding') { + return tooltipRefForEncoding(encoding, stack, config, opt); + } else { + return {signal: datum}; + } } - } - return undefined; - }); + return undefined; + } + ); } } diff --git ORI/vega-lite/src/compile/predicate.ts ALT/vega-lite/src/compile/predicate.ts index 75335af3b..ea332b01b 100644 --- ORI/vega-lite/src/compile/predicate.ts +++ ALT/vega-lite/src/compile/predicate.ts @@ -11,14 +11,17 @@ import {parseSelectionPredicate} from './selection/parse'; */ // model is only used for selection filters. export function expression(model: Model, filterOp: LogicalComposition, node?: DataFlowNode): string { - return logicalExpr(filterOp, (predicate: Predicate) => { - if (isString(predicate)) { - return predicate; - } else if (isSelectionPredicate(predicate)) { - return parseSelectionPredicate(model, predicate, node); - } else { - // Filter Object - return fieldFilterExpression(predicate); + return logicalExpr( + filterOp, + (predicate: Predicate) => { + if (isString(predicate)) { + return predicate; + } else if (isSelectionPredicate(predicate)) { + return parseSelectionPredicate(model, predicate, node); + } else { + // Filter Object + return fieldFilterExpression(predicate); + } } - }); + ); } diff --git ORI/vega-lite/src/compile/projection/parse.ts ALT/vega-lite/src/compile/projection/parse.ts index 21c41693e..44f4e77ac 100644 --- ORI/vega-lite/src/compile/projection/parse.ts +++ ALT/vega-lite/src/compile/projection/parse.ts @@ -73,22 +73,25 @@ function gatherFitData(model: UnitModel) { } function mergeIfNoConflict(first: ProjectionComponent, second: ProjectionComponent): ProjectionComponent { - const allPropertiesShared = every(PROJECTION_PROPERTIES, prop => { - // neither has the property - if (!hasOwnProperty(first.explicit, prop) && !hasOwnProperty(second.explicit, prop)) { - return true; - } - // both have property and an equal value for property - if ( - hasOwnProperty(first.explicit, prop) && - hasOwnProperty(second.explicit, prop) && - // some properties might be signals or objects and require hashing for comparison - deepEqual(first.get(prop), second.get(prop)) - ) { - return true; + const allPropertiesShared = every( + PROJECTION_PROPERTIES, + prop => { + // neither has the property + if (!hasOwnProperty(first.explicit, prop) && !hasOwnProperty(second.explicit, prop)) { + return true; + } + // both have property and an equal value for property + if ( + hasOwnProperty(first.explicit, prop) && + hasOwnProperty(second.explicit, prop) && + // some properties might be signals or objects and require hashing for comparison + deepEqual(first.get(prop), second.get(prop)) + ) { + return true; + } + return false; } - return false; - }); + ); const size = deepEqual(first.size, second.size); if (size) { @@ -118,23 +121,26 @@ function parseNonUnitProjections(model: Model): ProjectionComponent { } // analyze parsed projections, attempt to merge - const mergable = every(model.children, child => { - const projection = child.component.projection; - if (!projection) { - // child layer does not use a projection - return true; - } else if (!nonUnitProjection) { - // cached 'projection' is null, cache this one - nonUnitProjection = projection; - return true; - } else { - const merge = mergeIfNoConflict(nonUnitProjection, projection); - if (merge) { - nonUnitProjection = merge; + const mergable = every( + model.children, + child => { + const projection = child.component.projection; + if (!projection) { + // child layer does not use a projection + return true; + } else if (!nonUnitProjection) { + // cached 'projection' is null, cache this one + nonUnitProjection = projection; + return true; + } else { + const merge = mergeIfNoConflict(nonUnitProjection, projection); + if (merge) { + nonUnitProjection = merge; + } + return !!merge; } - return !!merge; } - }); + ); // if cached one and all other children share the same projection, if (nonUnitProjection && mergable) { diff --git ORI/vega-lite/src/compile/selection/interval.ts ALT/vega-lite/src/compile/selection/interval.ts index 7dd7b69b1..2ebde45f0 100644 --- ORI/vega-lite/src/compile/selection/interval.ts +++ ALT/vega-lite/src/compile/selection/interval.ts @@ -200,13 +200,16 @@ function channelSignals( const size = model.getSizeSignalRef(channel === X ? 'width' : 'height').signal; const coord = `${channel}(unit)`; - const on = events(selCmpt, (def: OnEvent[], evt: Stream) => { - return [ - ...def, - {events: evt.between[0], update: `[${coord}, ${coord}]`}, // Brush Start - {events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]`} // Brush End - ]; - }); + const on = events( + selCmpt, + (def: OnEvent[], evt: Stream) => { + return [ + ...def, + {events: evt.between[0], update: `[${coord}, ${coord}]`}, // Brush Start + {events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]`} // Brush End + ]; + } + ); // React to pan/zooms of continuous scales. Non-continuous scales // (band, point) cannot be pan/zoomed and any other changes diff --git ORI/vega-lite/src/encoding.ts ALT/vega-lite/src/encoding.ts index 0e6b222da..9bdc3677e 100644 --- ORI/vega-lite/src/encoding.ts +++ ALT/vega-lite/src/encoding.ts @@ -324,18 +324,21 @@ export function channelHasField( } export function isAggregate(encoding: EncodingWithFacet) { - return some(CHANNELS, channel => { - if (channelHasField(encoding, channel)) { - const channelDef = encoding[channel]; - if (isArray(channelDef)) { - return some(channelDef, fieldDef => !!fieldDef.aggregate); - } else { - const fieldDef = getFieldDef(channelDef); - return fieldDef && !!fieldDef.aggregate; + return some( + CHANNELS, + channel => { + if (channelHasField(encoding, channel)) { + const channelDef = encoding[channel]; + if (isArray(channelDef)) { + return some(channelDef, fieldDef => !!fieldDef.aggregate); + } else { + const fieldDef = getFieldDef(channelDef); + return fieldDef && !!fieldDef.aggregate; + } } + return false; } - return false; - }); + ); } export function extractTransformsFromEncoding(oldEncoding: Encoding, config: Config) { diff --git ORI/vega-lite/src/normalize/selectioncompat.ts ALT/vega-lite/src/normalize/selectioncompat.ts index f5e64df73..b78d40119 100644 --- ORI/vega-lite/src/normalize/selectioncompat.ts +++ ALT/vega-lite/src/normalize/selectioncompat.ts @@ -142,18 +142,22 @@ function normalizeBinExtent(bin: BinParams): BinParams { function normalizePredicate(op: any, normParams: NormalizerParams) { // Normalize old compositions of selection names (e.g., selection: {and: ["one", "two"]}) const normalizeSelectionComposition = (o: LogicalComposition) => { - return normalizeLogicalComposition(o, param => { - const empty = normParams.emptySelections[param] ?? true; - const pred = {param, empty}; - normParams.selectionPredicates[param] ??= []; - normParams.selectionPredicates[param].push(pred); - return pred as any; - }); + return normalizeLogicalComposition( + o, + param => { + const empty = normParams.emptySelections[param] ?? true; + const pred = {param, empty}; + normParams.selectionPredicates[param] ??= []; + normParams.selectionPredicates[param].push(pred); + return pred as any; + } + ); }; return op.selection ? normalizeSelectionComposition(op.selection) - : normalizeLogicalComposition(op.test || op.filter, o => - o.selection ? normalizeSelectionComposition(o.selection) : o + : normalizeLogicalComposition( + op.test || op.filter, + o => (o.selection ? normalizeSelectionComposition(o.selection) : o) ); } diff --git ORI/vega-lite/test/compositemark/common.test.ts ALT/vega-lite/test/compositemark/common.test.ts index 845a89a47..8cc9eeba5 100644 --- ORI/vega-lite/test/compositemark/common.test.ts +++ ALT/vega-lite/test/compositemark/common.test.ts @@ -167,12 +167,15 @@ describe('common', () => { expect(isAggregate(aggregateTransform)).toBeTruthy(); expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return ( - aggregateFieldDef.field === aggField && - (aggregateFieldDef.op === 'mean' || aggregateFieldDef.op === 'median') - ); - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return ( + aggregateFieldDef.field === aggField && + (aggregateFieldDef.op === 'mean' || aggregateFieldDef.op === 'median') + ); + } + ) ).toBe(true); }); } diff --git ORI/vega-lite/test/compositemark/errorband.test.ts ALT/vega-lite/test/compositemark/errorband.test.ts index 4466d3a7f..249078a73 100644 --- ORI/vega-lite/test/compositemark/errorband.test.ts +++ ALT/vega-lite/test/compositemark/errorband.test.ts @@ -91,14 +91,20 @@ describe('normalizeErrorBand', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; if (layer) { expect( - some(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'rect'; - }) + some( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'rect'; + } + ) ).toBe(true); expect( - some(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'rule'; - }) + some( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'rule'; + } + ) ).toBe(true); } else { expect(false).toBe(true); @@ -121,14 +127,20 @@ describe('normalizeErrorBand', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; if (layer) { expect( - some(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'area'; - }) + some( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'area'; + } + ) ).toBe(true); expect( - some(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'line'; - }) + some( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'line'; + } + ) ).toBe(true); } else { expect(false).toBe(true); @@ -151,9 +163,12 @@ describe('normalizeErrorBand', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; if (layer) { expect( - every(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.interpolate === 'monotone'; - }) + every( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.interpolate === 'monotone'; + } + ) ).toBe(true); } else { expect(false).toBe(true); @@ -176,9 +191,12 @@ describe('normalizeErrorBand', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; expect( - every(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && !unitSpec.mark.interpolate; - }) + every( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && !unitSpec.mark.interpolate; + } + ) ).toBe(true); expect(localLogger.warns[0]).toEqual(log.message.errorBand1DNotSupport('interpolate')); }) diff --git ORI/vega-lite/test/compositemark/errorbar.test.ts ALT/vega-lite/test/compositemark/errorbar.test.ts index f9d14a294..8d1a52a64 100644 --- ORI/vega-lite/test/compositemark/errorbar.test.ts +++ ALT/vega-lite/test/compositemark/errorbar.test.ts @@ -228,16 +228,19 @@ describe('normalizeErrorBar with raw data input', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; if (layer) { expect( - some(layer, unitSpec => { - return ( - isUnitSpec(unitSpec) && - isMarkDef(unitSpec.mark) && - unitSpec.mark.type === 'tick' && - unitSpec.mark.size === size && - unitSpec.mark.color === color && - unitSpec.mark.opacity === opacity - ); - }) + some( + layer, + unitSpec => { + return ( + isUnitSpec(unitSpec) && + isMarkDef(unitSpec.mark) && + unitSpec.mark.type === 'tick' && + unitSpec.mark.size === size && + unitSpec.mark.color === color && + unitSpec.mark.opacity === opacity + ); + } + ) ).toBe(true); } else { expect(false).toBe(true); @@ -537,54 +540,78 @@ describe('normalizeErrorBar for all possible extents and centers with raw data i if (isAggregate(aggregateTransform)) { if (extent === 'iqr' || (center === 'median' && !extent)) { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === 'median'; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === 'median'; + } + ) ).toBe(true); } else if (extent === 'ci') { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === 'mean'; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === 'mean'; + } + ) ).toBe(true); } else { if (center) { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === center; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === center; + } + ) ).toBe(true); } else { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === 'mean'; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === 'mean'; + } + ) ).toBe(true); } if (extent) { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return isPartOfExtent(extent, aggregateFieldDef.op); - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return isPartOfExtent(extent, aggregateFieldDef.op); + } + ) ).toBe(true); } else if (center === 'median') { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return isPartOfExtent('iqr', aggregateFieldDef.op); - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return isPartOfExtent('iqr', aggregateFieldDef.op); + } + ) ).toBe(true); expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === 'median'; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === 'median'; + } + ) ).toBe(false); } else { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return isPartOfExtent('stderr', aggregateFieldDef.op); - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return isPartOfExtent('stderr', aggregateFieldDef.op); + } + ) ).toBe(true); } } diff --git ORI/vega-lite/test/scale.test.ts ALT/vega-lite/test/scale.test.ts index 7f167e049..28bbfe81b 100644 --- ORI/vega-lite/test/scale.test.ts +++ ALT/vega-lite/test/scale.test.ts @@ -16,9 +16,12 @@ describe('scale', () => { it('should have at least one supported scale types for all scale properties', () => { for (const prop of scale.SCALE_PROPERTIES) { expect( - some(scale.SCALE_TYPES, scaleType => { - return scale.scaleTypeSupportProperty(scaleType, prop); - }) + some( + scale.SCALE_TYPES, + scaleType => { + return scale.scaleTypeSupportProperty(scaleType, prop); + } + ) ).toBeTruthy(); } }); @@ -39,9 +42,12 @@ describe('scale', () => { it('should have at least one supported scale types for all channels with scale', () => { for (const channel of SCALE_CHANNELS) { expect( - some(SCALE_TYPES, scaleType => { - return channelSupportScaleType(channel, scaleType); - }) + some( + SCALE_TYPES, + scaleType => { + return channelSupportScaleType(channel, scaleType); + } + ) ).toBeTruthy(); } }); @@ -50,9 +56,12 @@ describe('scale', () => { it('should have at least one supported channel for all scale types', () => { for (const scaleType of SCALE_TYPES) { expect( - some(SCALE_CHANNELS, channel => { - return channelSupportScaleType(channel, scaleType); - }) + some( + SCALE_CHANNELS, + channel => { + return channelSupportScaleType(channel, scaleType); + } + ) ).toBeTruthy(); } }); ```
thorn0 commented 3 years ago

run #8300

github-actions[bot] commented 3 years ago

prettier/prettier#8300 VS prettier/prettier@main

  • babel/babel@b63be942cef487fa31a7fa35bd7694076d5b7ad9
  • vuejs/eslint-plugin-vue@cc9c14003390dccf358cbda042e359ecfda8432a
  • excalidraw/excalidraw@1973ae9444027cc97eea87e1c0cbbf98c1d1160b
  • prettier/prettier@2c1b8f6fab1f9c63ab5d937908d090d8e75e8072
  • typescript-eslint/typescript-eslint@7b701a3091eca0eef5a1e3a7cbcadbabdc54104d
  • vega/vega-lite@e89e9e6f1f32a106bf7e7f9091dff863e754c79a
Diff (2669 lines) ```diff diff --git ORI/babel/packages/babel-cli/src/babel/util.js ALT/babel/packages/babel-cli/src/babel/util.js index fc1bf2b58..6840b8071 100644 --- ORI/babel/packages/babel-cli/src/babel/util.js +++ ALT/babel/packages/babel-cli/src/babel/util.js @@ -16,15 +16,19 @@ export function readdir( includeDotfiles: boolean, filter?: ReaddirFilter, ): Array { - return readdirRecursive(dirname, (filename, _index, currentDirectory) => { - const stat = fs.statSync(path.join(currentDirectory, filename)); - - if (stat.isDirectory()) return true; - - return ( - (includeDotfiles || filename[0] !== ".") && (!filter || filter(filename)) - ); - }); + return readdirRecursive( + dirname, + (filename, _index, currentDirectory) => { + const stat = fs.statSync(path.join(currentDirectory, filename)); + + if (stat.isDirectory()) return true; + + return ( + (includeDotfiles || filename[0] !== ".") && + (!filter || filter(filename)) + ); + }, + ); } export function readdirForCompilable( @@ -32,9 +36,13 @@ export function readdirForCompilable( includeDotfiles: boolean, altExts?: Array, ): Array { - return readdir(dirname, includeDotfiles, function (filename) { - return isCompilableExtension(filename, altExts); - }); + return readdir( + dirname, + includeDotfiles, + function (filename) { + return isCompilableExtension(filename, altExts); + }, + ); } /** diff --git ORI/babel/packages/babel-compat-data/scripts/utils-build-data.js ALT/babel/packages/babel-compat-data/scripts/utils-build-data.js index e8a21f4f2..4a82857d6 100644 --- ORI/babel/packages/babel-compat-data/scripts/utils-build-data.js +++ ALT/babel/packages/babel-compat-data/scripts/utils-build-data.js @@ -35,17 +35,22 @@ exports.environments = [ "samsung", ]; -const compatibilityTests = flatMap(compatSources, data => - flatMap(data.tests, test => { - if (!test.subtests) return test; - - return test.subtests.map(subtest => - Object.assign({}, subtest, { - name: test.name + " / " + subtest.name, - group: test.name, - }) - ); - }) +const compatibilityTests = flatMap( + compatSources, + data => + flatMap( + data.tests, + test => { + if (!test.subtests) return test; + + return test.subtests.map(subtest => + Object.assign({}, subtest, { + name: test.name + " / " + subtest.name, + group: test.name, + }) + ); + } + ) ); exports.getLowestImplementedVersion = ( @@ -85,23 +90,26 @@ exports.getLowestImplementedVersion = ( }; exports.generateData = (environments, features) => { - return mapValues(features, options => { - if (!options.features) { - options = { - features: [options], - }; + return mapValues( + features, + options => { + if (!options.features) { + options = { + features: [options], + }; + } + + const plugin = {}; + + environments.forEach(env => { + const version = exports.getLowestImplementedVersion(options, env); + if (version) plugin[env] = version; + }); + addElectronSupportFromChromium(plugin); + + return plugin; } - - const plugin = {}; - - environments.forEach(env => { - const version = exports.getLowestImplementedVersion(options, env); - if (version) plugin[env] = version; - }); - addElectronSupportFromChromium(plugin); - - return plugin; - }); + ); }; exports.writeFile = function (data, dataPath, name) { diff --git ORI/babel/packages/babel-core/src/config/caching.js ALT/babel/packages/babel-core/src/config/caching.js index 050c59d85..d60bc3874 100644 --- ORI/babel/packages/babel-core/src/config/caching.js +++ ALT/babel/packages/babel-core/src/config/caching.js @@ -128,9 +128,12 @@ function makeCachedFunction( // Flow refines handlerResult to Generator const gen = (handlerResult: Generator<*, ResultT, *>); - value = yield* onFirstPause(gen, () => { - finishLock = setupAsyncLocks(cache, futureCache, arg); - }); + value = yield* onFirstPause( + gen, + () => { + finishLock = setupAsyncLocks(cache, futureCache, arg); + }, + ); } else { // $FlowIgnore doesn't refine handlerResult to ResultT value = (handlerResult: ResultT); diff --git ORI/babel/packages/babel-core/src/config/full.js ALT/babel/packages/babel-core/src/config/full.js index 75fbe293c..9d8ac3fb9 100644 --- ORI/babel/packages/babel-core/src/config/full.js +++ ALT/babel/packages/babel-core/src/config/full.js @@ -161,29 +161,32 @@ export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig( const opts: Object = optionDefaults; mergeOptions(opts, options); - yield* enhanceError(context, function* loadPluginDescriptors() { - pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); - - for (const descs of pluginDescriptorsByPass) { - const pass = []; - passes.push(pass); - - for (let i = 0; i < descs.length; i++) { - const descriptor: UnloadedDescriptor = descs[i]; - if (descriptor.options !== false) { - try { - pass.push(yield* loadPluginDescriptor(descriptor, context)); - } catch (e) { - if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { - // print special message for `plugins: ["@babel/foo", { foo: "option" }]` - checkNoUnwrappedItemOptionPairs(descs, i, "plugin", e); + yield* enhanceError( + context, + function* loadPluginDescriptors() { + pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); + + for (const descs of pluginDescriptorsByPass) { + const pass = []; + passes.push(pass); + + for (let i = 0; i < descs.length; i++) { + const descriptor: UnloadedDescriptor = descs[i]; + if (descriptor.options !== false) { + try { + pass.push(yield* loadPluginDescriptor(descriptor, context)); + } catch (e) { + if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { + // print special message for `plugins: ["@babel/foo", { foo: "option" }]` + checkNoUnwrappedItemOptionPairs(descs, i, "plugin", e); + } + throw e; } - throw e; } } } - } - })(); + }, + )(); opts.plugins = passes[0]; opts.presets = passes @@ -307,10 +310,13 @@ const instantiatePlugin = makeWeakCache(function* ( dirname, }; - const inherits = yield* forwardAsync(loadPluginDescriptor, run => { - // If the inherited plugin changes, reinstantiate this plugin. - return cache.invalidate(data => run(inheritsDescriptor, data)); - }); + const inherits = yield* forwardAsync( + loadPluginDescriptor, + run => { + // If the inherited plugin changes, reinstantiate this plugin. + return cache.invalidate(data => run(inheritsDescriptor, data)); + }, + ); plugin.pre = chain(inherits.pre, plugin.pre); plugin.post = chain(inherits.post, plugin.post); diff --git ORI/babel/packages/babel-core/src/transformation/block-hoist-plugin.js ALT/babel/packages/babel-core/src/transformation/block-hoist-plugin.js index 477d2d5c3..5901aaf22 100644 --- ORI/babel/packages/babel-core/src/transformation/block-hoist-plugin.js +++ ALT/babel/packages/babel-core/src/transformation/block-hoist-plugin.js @@ -51,14 +51,17 @@ const blockHoistPlugin = { } if (!hasChange) return; - node.body = sortBy(node.body, function (bodyNode) { - let priority = bodyNode?._blockHoist; - if (priority == null) priority = 1; - if (priority === true) priority = 2; + node.body = sortBy( + node.body, + function (bodyNode) { + let priority = bodyNode?._blockHoist; + if (priority == null) priority = 1; + if (priority === true) priority = 2; - // Higher priorities should move toward the top. - return -1 * priority; - }); + // Higher priorities should move toward the top. + return -1 * priority; + }, + ); }, }, }, diff --git ORI/babel/packages/babel-core/src/transformation/file/merge-map.js ALT/babel/packages/babel-core/src/transformation/file/merge-map.js index 911867d96..02825f678 100644 --- ORI/babel/packages/babel-core/src/transformation/file/merge-map.js +++ ALT/babel/packages/babel-core/src/transformation/file/merge-map.js @@ -123,15 +123,18 @@ function filterApplicableOriginalRanges( ): OriginalMappings { // The mapping array is sorted by original location, so we can // binary-search it for the overlapping ranges. - return filterSortedArray(mappings, ({ original: outOriginal }) => { - if (line > outOriginal.line) return -1; - if (line < outOriginal.line) return 1; + return filterSortedArray( + mappings, + ({ original: outOriginal }) => { + if (line > outOriginal.line) return -1; + if (line < outOriginal.line) return 1; - if (columnStart >= outOriginal.columnEnd) return -1; - if (columnEnd <= outOriginal.columnStart) return 1; + if (columnStart >= outOriginal.columnEnd) return -1; + if (columnEnd <= outOriginal.columnStart) return 1; - return 0; - }); + return 0; + }, + ); } function eachInputGeneratedRange( diff --git ORI/babel/packages/babel-core/test/api.js ALT/babel/packages/babel-core/test/api.js index a8aed41cc..4d2a57901 100644 --- ORI/babel/packages/babel-core/test/api.js +++ ALT/babel/packages/babel-core/test/api.js @@ -454,24 +454,36 @@ describe("api", function () { // Writes value properly. expect( - doTransform("", file => { - file.shebang = "env node"; - }), + doTransform( + "", + file => { + file.shebang = "env node"; + }, + ), ).toBe(`#!env node`); expect( - doTransform("#!env node", file => { - file.shebang = "env node2"; - }), + doTransform( + "#!env node", + file => { + file.shebang = "env node2"; + }, + ), ).toBe(`#!env node2`); expect( - doTransform("", file => { - file.shebang = ""; - }), + doTransform( + "", + file => { + file.shebang = ""; + }, + ), ).toBe(``); expect( - doTransform("#!env node", file => { - file.shebang = ""; - }), + doTransform( + "#!env node", + file => { + file.shebang = ""; + }, + ), ).toBe(``); // Reads value properly. @@ -484,14 +496,17 @@ describe("api", function () { // Reads and writes properly. expect( - doTransform("#!env node", file => { - expect(file.shebang).toBe("env node"); + doTransform( + "#!env node", + file => { + expect(file.shebang).toBe("env node"); - file.shebang = "env node2"; - expect(file.shebang).toBe("env node2"); + file.shebang = "env node2"; + expect(file.shebang).toBe("env node2"); - file.shebang = "env node3"; - }), + file.shebang = "env node3"; + }, + ), ).toBe(`#!env node3`); }); diff --git ORI/babel/packages/babel-helper-module-imports/test/index.js ALT/babel/packages/babel-helper-module-imports/test/index.js index 7f6a2206c..6f9f38070 100644 --- ORI/babel/packages/babel-helper-module-imports/test/index.js +++ ALT/babel/packages/babel-helper-module-imports/test/index.js @@ -24,11 +24,13 @@ function test(sourceType, opts, initializer, inputCode, expectedCode) { function ({ types: t }) { return { pre(file) { - file.set("helperGenerator", name => - t.memberExpression( - t.identifier("babelHelpers"), - t.identifier(name), - ), + file.set( + "helperGenerator", + name => + t.memberExpression( + t.identifier("babelHelpers"), + t.identifier(name), + ), ); }, visitor: { @@ -1134,8 +1136,9 @@ describe("@babel/helper-module-imports", () => { it("is disallowed in CJS modules", () => { expect(() => - testScript({ importPosition: "after" }, m => - m.addNamed("read", "source"), + testScript( + { importPosition: "after" }, + m => m.addNamed("read", "source"), ), ).toThrow(`"importPosition": "after" is only supported in modules`); }); diff --git ORI/babel/packages/babel-parser/src/plugins/flow.js ALT/babel/packages/babel-parser/src/plugins/flow.js index 6dfbe03ea..c830daae8 100644 --- ORI/babel/packages/babel-parser/src/plugins/flow.js +++ ALT/babel/packages/babel-parser/src/plugins/flow.js @@ -1696,8 +1696,9 @@ export default (superClass: Class): Class => isMethod?: boolean = false, ): void { if (allowExpressionBody) { - return this.forwardNoArrowParamsConversionAt(node, () => - super.parseFunctionBody(node, true, isMethod), + return this.forwardNoArrowParamsConversionAt( + node, + () => super.parseFunctionBody(node, true, isMethod), ); } @@ -1888,8 +1889,9 @@ export default (superClass: Class): Class => node.test = expr; node.consequent = consequent; - node.alternate = this.forwardNoArrowParamsConversionAt(node, () => - this.parseMaybeAssign(undefined, undefined, undefined), + node.alternate = this.forwardNoArrowParamsConversionAt( + node, + () => this.parseMaybeAssign(undefined, undefined, undefined), ); return this.finishNode(node, "ConditionalExpression"); @@ -1944,8 +1946,9 @@ export default (superClass: Class): Class => return [arrows, []]; } - return partition(arrows, node => - node.params.every(param => this.isAssignable(param, true)), + return partition( + arrows, + node => node.params.every(param => this.isAssignable(param, true)), ); } diff --git ORI/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js ALT/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js index d215a27..1ab212c 100644 --- ORI/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js +++ ALT/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js @@ -57,9 +57,11 @@ module.exports = { let eslintScope try { - eslintScope = getESLintModule('eslint-scope', () => - // @ts-ignore - require('eslint-scope') + eslintScope = getESLintModule( + 'eslint-scope', + () => + // @ts-ignore + require('eslint-scope') ) } catch (_e) { context.report({ @@ -70,9 +72,11 @@ module.exports = { } let espree try { - espree = getESLintModule('espree', () => - // @ts-ignore - require('espree') + espree = getESLintModule( + 'espree', + () => + // @ts-ignore + require('espree') ) } catch (_e) { context.report({ diff --git ORI/eslint-plugin-vue/lib/rules/no-unused-properties.js ALT/eslint-plugin-vue/lib/rules/no-unused-properties.js index f89c518..ff66c1b 100644 --- ORI/eslint-plugin-vue/lib/rules/no-unused-properties.js +++ ALT/eslint-plugin-vue/lib/rules/no-unused-properties.js @@ -381,8 +381,9 @@ function extractPatternOrThisProperties(node, context, withInTemplate) { // `arg.foo` const name = utils.getStaticPropertyName(parent) if (name) { - result.addUsed(name, () => - extractPatternOrThisProperties(parent, context, withInTemplate) + result.addUsed( + name, + () => extractPatternOrThisProperties(parent, context, withInTemplate) ) } else { result.unknown = true diff --git ORI/eslint-plugin-vue/tests/lib/utils/html-comments.js ALT/eslint-plugin-vue/tests/lib/utils/html-comments.js index 066c73e..6a0297e 100644 --- ORI/eslint-plugin-vue/tests/lib/utils/html-comments.js +++ ALT/eslint-plugin-vue/tests/lib/utils/html-comments.js @@ -37,10 +37,12 @@ function tokenize(code, option) { const linter = new Linter() const result = [] - linter.defineRule('vue/html-comments-test', (content) => - htmlComments.defineVisitor(content, option, (commentTokens) => { - result.push(commentTokens) - }) + linter.defineRule( + 'vue/html-comments-test', + (content) => + htmlComments.defineVisitor(content, option, (commentTokens) => { + result.push(commentTokens) + }) ) linter.defineParser('vue-eslint-parser', require('vue-eslint-parser')) linter.verify( diff --git ORI/prettier/scripts/release/steps/update-dependents-count.js ALT/prettier/scripts/release/steps/update-dependents-count.js index b8e717537..066fa9ffc 100644 --- ORI/prettier/scripts/release/steps/update-dependents-count.js +++ ALT/prettier/scripts/release/steps/update-dependents-count.js @@ -41,16 +41,18 @@ async function update() { ); } - processFile("website/pages/en/index.js", (content) => - content - .replace( - /()(.*?)(<\/strong>)/, - `$1${formatNumber(dependentsCountNpm)}$3` - ) - .replace( - /()(.*?)(<\/strong>)/, - `$1${formatNumber(dependentsCountGithub)}$3` - ) + processFile( + "website/pages/en/index.js", + (content) => + content + .replace( + /()(.*?)(<\/strong>)/, + `$1${formatNumber(dependentsCountNpm)}$3` + ) + .replace( + /()(.*?)(<\/strong>)/, + `$1${formatNumber(dependentsCountGithub)}$3` + ) ); const isUpdated = await logPromise( diff --git ORI/prettier/scripts/release/steps/update-version.js ALT/prettier/scripts/release/steps/update-version.js index 081820765..cdf24f1a4 100644 --- ORI/prettier/scripts/release/steps/update-version.js +++ ALT/prettier/scripts/release/steps/update-version.js @@ -9,19 +9,25 @@ async function bump({ version }) { await writeJson("package.json", pkg, { spaces: 2 }); // Update github issue templates - processFile(".github/ISSUE_TEMPLATE/formatting.md", (content) => - content.replace(/^(\*\*Prettier ).*?(\*\*)$/m, `$1${version}$2`) + processFile( + ".github/ISSUE_TEMPLATE/formatting.md", + (content) => + content.replace(/^(\*\*Prettier ).*?(\*\*)$/m, `$1${version}$2`) ); - processFile(".github/ISSUE_TEMPLATE/integration.md", (content) => - content.replace(/^(- Prettier Version: ).*?$/m, `$1${version}`) + processFile( + ".github/ISSUE_TEMPLATE/integration.md", + (content) => content.replace(/^(- Prettier Version: ).*?$/m, `$1${version}`) ); - processFile("docs/install.md", (content) => - content.replace(/^(npx prettier@)\S+/m, `$1${version}`) + processFile( + "docs/install.md", + (content) => content.replace(/^(npx prettier@)\S+/m, `$1${version}`) ); // Update unpkg link in docs - processFile("docs/browser.md", (content) => - content.replace(/(\/\/unpkg\.com\/prettier@).*?\//g, `$1${version}/`) + processFile( + "docs/browser.md", + (content) => + content.replace(/(\/\/unpkg\.com\/prettier@).*?\//g, `$1${version}/`) ); await execa("yarn", ["update-stable-docs"], { diff --git ORI/prettier/src/document/doc-utils.js ALT/prettier/src/document/doc-utils.js index 738527336..2c3addedf 100644 --- ORI/prettier/src/document/doc-utils.js +++ ALT/prettier/src/document/doc-utils.js @@ -343,29 +343,34 @@ function normalizeParts(parts) { } function normalizeDoc(doc) { - return mapDoc(doc, (currentDoc) => { - if (Array.isArray(currentDoc)) { - return normalizeParts(currentDoc); - } - if (!currentDoc.parts) { - return currentDoc; + return mapDoc( + doc, + (currentDoc) => { + if (Array.isArray(currentDoc)) { + return normalizeParts(currentDoc); + } + if (!currentDoc.parts) { + return currentDoc; + } + return { + ...currentDoc, + parts: normalizeParts(currentDoc.parts), + }; } - return { - ...currentDoc, - parts: normalizeParts(currentDoc.parts), - }; - }); + ); } function replaceNewlinesWithLiterallines(doc) { - return mapDoc(doc, (currentDoc) => - typeof currentDoc === "string" && currentDoc.includes("\n") - ? concat( - currentDoc - .split(/(\n)/g) - .map((v, i) => (i % 2 === 0 ? v : literalline)) - ) - : currentDoc + return mapDoc( + doc, + (currentDoc) => + typeof currentDoc === "string" && currentDoc.includes("\n") + ? concat( + currentDoc + .split(/(\n)/g) + .map((v, i) => (i % 2 === 0 ? v : literalline)) + ) + : currentDoc ); } diff --git ORI/prettier/src/language-css/index.js ALT/prettier/src/language-css/index.js index c69c43461..1f881d51d 100644 --- ORI/prettier/src/language-css/index.js +++ ALT/prettier/src/language-css/index.js @@ -5,32 +5,44 @@ const printer = require("./printer-postcss"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/CSS.json"), (data) => ({ - since: "1.4.0", - parsers: ["css"], - vscodeLanguageIds: ["css"], - extensions: [ - ...data.extensions, - // `WeiXin Style Sheets`(Weixin Mini Programs) - // https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/ - ".wxss", - ], - })), - createLanguage(require("linguist-languages/data/PostCSS.json"), () => ({ - since: "1.4.0", - parsers: ["css"], - vscodeLanguageIds: ["postcss"], - })), - createLanguage(require("linguist-languages/data/Less.json"), () => ({ - since: "1.4.0", - parsers: ["less"], - vscodeLanguageIds: ["less"], - })), - createLanguage(require("linguist-languages/data/SCSS.json"), () => ({ - since: "1.4.0", - parsers: ["scss"], - vscodeLanguageIds: ["scss"], - })), + createLanguage( + require("linguist-languages/data/CSS.json"), + (data) => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["css"], + extensions: [ + ...data.extensions, + // `WeiXin Style Sheets`(Weixin Mini Programs) + // https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/ + ".wxss", + ], + }) + ), + createLanguage( + require("linguist-languages/data/PostCSS.json"), + () => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["postcss"], + }) + ), + createLanguage( + require("linguist-languages/data/Less.json"), + () => ({ + since: "1.4.0", + parsers: ["less"], + vscodeLanguageIds: ["less"], + }) + ), + createLanguage( + require("linguist-languages/data/SCSS.json"), + () => ({ + since: "1.4.0", + parsers: ["scss"], + vscodeLanguageIds: ["scss"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-graphql/index.js ALT/prettier/src/language-graphql/index.js index b991a850f..c3f9a6367 100644 --- ORI/prettier/src/language-graphql/index.js +++ ALT/prettier/src/language-graphql/index.js @@ -5,11 +5,14 @@ const printer = require("./printer-graphql"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/GraphQL.json"), () => ({ - since: "1.5.0", - parsers: ["graphql"], - vscodeLanguageIds: ["graphql"], - })), + createLanguage( + require("linguist-languages/data/GraphQL.json"), + () => ({ + since: "1.5.0", + parsers: ["graphql"], + vscodeLanguageIds: ["graphql"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-handlebars/index.js ALT/prettier/src/language-handlebars/index.js index 01e35dd96..be3e56fbb 100644 --- ORI/prettier/src/language-handlebars/index.js +++ ALT/prettier/src/language-handlebars/index.js @@ -4,11 +4,14 @@ const createLanguage = require("../utils/create-language"); const printer = require("./printer-glimmer"); const languages = [ - createLanguage(require("linguist-languages/data/Handlebars.json"), () => ({ - since: null, // unreleased - parsers: ["glimmer"], - vscodeLanguageIds: ["handlebars"], - })), + createLanguage( + require("linguist-languages/data/Handlebars.json"), + () => ({ + since: null, // unreleased + parsers: ["glimmer"], + vscodeLanguageIds: ["handlebars"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-html/index.js ALT/prettier/src/language-html/index.js index 1caf94c65..20e9d77b6 100644 --- ORI/prettier/src/language-html/index.js +++ ALT/prettier/src/language-html/index.js @@ -5,36 +5,48 @@ const printer = require("./printer-html"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/HTML.json"), () => ({ - name: "Angular", - since: "1.15.0", - parsers: ["angular"], - vscodeLanguageIds: ["html"], - extensions: [".component.html"], - filenames: [], - })), - createLanguage(require("linguist-languages/data/HTML.json"), (data) => ({ - since: "1.15.0", - parsers: ["html"], - vscodeLanguageIds: ["html"], - extensions: [ - ...data.extensions, - ".mjml", // MJML is considered XML in Linguist but it should be formatted as HTML - ], - })), - createLanguage(require("linguist-languages/data/HTML.json"), () => ({ - name: "Lightning Web Components", - since: "1.17.0", - parsers: ["lwc"], - vscodeLanguageIds: ["html"], - extensions: [], - filenames: [], - })), - createLanguage(require("linguist-languages/data/Vue.json"), () => ({ - since: "1.10.0", - parsers: ["vue"], - vscodeLanguageIds: ["vue"], - })), + createLanguage( + require("linguist-languages/data/HTML.json"), + () => ({ + name: "Angular", + since: "1.15.0", + parsers: ["angular"], + vscodeLanguageIds: ["html"], + extensions: [".component.html"], + filenames: [], + }) + ), + createLanguage( + require("linguist-languages/data/HTML.json"), + (data) => ({ + since: "1.15.0", + parsers: ["html"], + vscodeLanguageIds: ["html"], + extensions: [ + ...data.extensions, + ".mjml", // MJML is considered XML in Linguist but it should be formatted as HTML + ], + }) + ), + createLanguage( + require("linguist-languages/data/HTML.json"), + () => ({ + name: "Lightning Web Components", + since: "1.17.0", + parsers: ["lwc"], + vscodeLanguageIds: ["html"], + extensions: [], + filenames: [], + }) + ), + createLanguage( + require("linguist-languages/data/Vue.json"), + () => ({ + since: "1.10.0", + parsers: ["vue"], + vscodeLanguageIds: ["vue"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-html/printer-html.js ALT/prettier/src/language-html/printer-html.js index 46aec9c30..40fbf2a41 100644 --- ORI/prettier/src/language-html/printer-html.js +++ ALT/prettier/src/language-html/printer-html.js @@ -199,8 +199,10 @@ function embed(path, print, textToDoc, options) { node.rawName, '="', group( - mapDoc(embeddedAttributeValueDoc, (doc) => - typeof doc === "string" ? doc.replace(/"/g, """) : doc + mapDoc( + embeddedAttributeValueDoc, + (doc) => + typeof doc === "string" ? doc.replace(/"/g, """) : doc ) ), '"', diff --git ORI/prettier/src/language-js/embed/css.js ALT/prettier/src/language-js/embed/css.js index 7ff50144c..15bf46eeb 100644 --- ORI/prettier/src/language-js/embed/css.js +++ ALT/prettier/src/language-js/embed/css.js @@ -57,23 +57,28 @@ function replacePlaceholders(quasisDoc, expressionDocs) { return quasisDoc; } let replaceCounter = 0; - const newDoc = mapDoc(cleanDoc(quasisDoc), (doc) => { - if (typeof doc !== "string" || !doc.includes("@prettier-placeholder")) { - return doc; - } - // When we have multiple placeholders in one line, like: - // ${Child}${Child2}:not(:first-child) - return doc.split(/@prettier-placeholder-(\d+)-id/).map((component, idx) => { - // The placeholder is always at odd indices - if (idx % 2 === 0) { - return replaceNewlinesWithLiterallines(component); + const newDoc = mapDoc( + cleanDoc(quasisDoc), + (doc) => { + if (typeof doc !== "string" || !doc.includes("@prettier-placeholder")) { + return doc; } + // When we have multiple placeholders in one line, like: + // ${Child}${Child2}:not(:first-child) + return doc + .split(/@prettier-placeholder-(\d+)-id/) + .map((component, idx) => { + // The placeholder is always at odd indices + if (idx % 2 === 0) { + return replaceNewlinesWithLiterallines(component); + } - // The component will always be a number at odd index - replaceCounter++; - return expressionDocs[component]; - }); - }); + // The component will always be a number at odd index + replaceCounter++; + return expressionDocs[component]; + }); + } + ); return expressionDocs.length === replaceCounter ? newDoc : null; } diff --git ORI/prettier/src/language-js/embed/html.js ALT/prettier/src/language-js/embed/html.js index cb2e41306..b4fbd9610 100644 --- ORI/prettier/src/language-js/embed/html.js +++ ALT/prettier/src/language-js/embed/html.js @@ -45,34 +45,37 @@ function format(path, print, textToDoc, options, { parser }) { { stripTrailingHardline: true } ); - const contentDoc = mapDoc(doc, (doc) => { - if (typeof doc !== "string") { - return doc; - } + const contentDoc = mapDoc( + doc, + (doc) => { + if (typeof doc !== "string") { + return doc; + } - const parts = []; + const parts = []; - const components = doc.split(placeholderRegex); - for (let i = 0; i < components.length; i++) { - let component = components[i]; + const components = doc.split(placeholderRegex); + for (let i = 0; i < components.length; i++) { + let component = components[i]; - if (i % 2 === 0) { - if (component) { - component = uncookTemplateElementValue(component); - if (options.embeddedInHtml) { - component = component.replace(/<\/(script)\b/gi, "<\\/$1"); + if (i % 2 === 0) { + if (component) { + component = uncookTemplateElementValue(component); + if (options.embeddedInHtml) { + component = component.replace(/<\/(script)\b/gi, "<\\/$1"); + } + parts.push(component); } - parts.push(component); + continue; } - continue; + + const placeholderIndex = +component; + parts.push(expressionDocs[placeholderIndex]); } - const placeholderIndex = +component; - parts.push(expressionDocs[placeholderIndex]); + return parts; } - - return parts; - }); + ); const leadingWhitespace = /^\s/.test(text) ? " " : ""; const trailingWhitespace = /\s$/.test(text) ? " " : ""; diff --git ORI/prettier/src/language-js/index.js ALT/prettier/src/language-js/index.js index dd35ccd6c..e4e2493cb 100644 --- ORI/prettier/src/language-js/index.js +++ ALT/prettier/src/language-js/index.js @@ -28,52 +28,70 @@ const languages = [ ], }) ), - createLanguage(require("linguist-languages/data/JavaScript.json"), () => ({ - name: "Flow", - since: "0.0.0", - parsers: ["flow", "babel-flow"], - vscodeLanguageIds: ["javascript"], - aliases: [], - filenames: [], - extensions: [".js.flow"], - })), - createLanguage(require("linguist-languages/data/JSX.json"), () => ({ - since: "0.0.0", - parsers: [ - "babel", - "babel-flow", - "babel-ts", - "flow", - "typescript", - "espree", - "meriyah", - ], - vscodeLanguageIds: ["javascriptreact"], - })), - createLanguage(require("linguist-languages/data/TypeScript.json"), () => ({ - since: "1.4.0", - parsers: ["typescript", "babel-ts"], - vscodeLanguageIds: ["typescript"], - })), - createLanguage(require("linguist-languages/data/TSX.json"), () => ({ - since: "1.4.0", - parsers: ["typescript", "babel-ts"], - vscodeLanguageIds: ["typescriptreact"], - })), - createLanguage(require("linguist-languages/data/JSON.json"), () => ({ - name: "JSON.stringify", - since: "1.13.0", - parsers: ["json-stringify"], - vscodeLanguageIds: ["json"], - extensions: [], // .json file defaults to json instead of json-stringify - filenames: ["package.json", "package-lock.json", "composer.json"], - })), - createLanguage(require("linguist-languages/data/JSON.json"), (data) => ({ - since: "1.5.0", - parsers: ["json"], - vscodeLanguageIds: ["json"], - extensions: data.extensions.filter((extension) => extension !== ".jsonl"), - })), + createLanguage( + require("linguist-languages/data/JavaScript.json"), + () => ({ + name: "Flow", + since: "0.0.0", + parsers: ["flow", "babel-flow"], + vscodeLanguageIds: ["javascript"], + aliases: [], + filenames: [], + extensions: [".js.flow"], + }) + ), + createLanguage( + require("linguist-languages/data/JSX.json"), + () => ({ + since: "0.0.0", + parsers: [ + "babel", + "babel-flow", + "babel-ts", + "flow", + "typescript", + "espree", + "meriyah", + ], + vscodeLanguageIds: ["javascriptreact"], + }) + ), + createLanguage( + require("linguist-languages/data/TypeScript.json"), + () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescript"], + }) + ), + createLanguage( + require("linguist-languages/data/TSX.json"), + () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescriptreact"], + }) + ), + createLanguage( + require("linguist-languages/data/JSON.json"), + () => ({ + name: "JSON.stringify", + since: "1.13.0", + parsers: ["json-stringify"], + vscodeLanguageIds: ["json"], + extensions: [], // .json file defaults to json instead of json-stringify + filenames: ["package.json", "package-lock.json", "composer.json"], + }) + ), + createLanguage( + require("linguist-languages/data/JSON.json"), + (data) => ({ + since: "1.5.0", + parsers: ["json"], + vscodeLanguageIds: ["json"], + extensions: data.extensions.filter((extension) => extension !== ".jsonl"), + }) + ), createLanguage( require("linguist-languages/data/JSON with Comments.json"), (data) => ({ @@ -83,11 +101,14 @@ const languages = [ filenames: [...data.filenames, ".eslintrc"], }) ), - createLanguage(require("linguist-languages/data/JSON5.json"), () => ({ - since: "1.13.0", - parsers: ["json5"], - vscodeLanguageIds: ["json5"], - })), + createLanguage( + require("linguist-languages/data/JSON5.json"), + () => ({ + since: "1.13.0", + parsers: ["json5"], + vscodeLanguageIds: ["json5"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-js/parse-postprocess.js ALT/prettier/src/language-js/parse-postprocess.js index d74e063cc..2876a7d05 100644 --- ORI/prettier/src/language-js/parse-postprocess.js +++ ALT/prettier/src/language-js/parse-postprocess.js @@ -23,41 +23,44 @@ function postprocess(ast, options) { if (options.parser === "typescript" && options.originalText.includes("@")) { const { esTreeNodeToTSNodeMap, tsNodeToESTreeNodeMap } = options.tsParseResult; - ast = visitNode(ast, (node) => { - const tsNode = esTreeNodeToTSNodeMap.get(node); - if (!tsNode) { - return; - } - const tsDecorators = tsNode.decorators; - if (!Array.isArray(tsDecorators)) { - return; - } - // `esTreeNodeToTSNodeMap.get(ClassBody)` and `esTreeNodeToTSNodeMap.get(ClassDeclaration)` has the same tsNode - const esTreeNode = tsNodeToESTreeNodeMap.get(tsNode); - if (esTreeNode !== node) { - return; - } - const esTreeDecorators = esTreeNode.decorators; - if ( - !Array.isArray(esTreeDecorators) || - esTreeDecorators.length !== tsDecorators.length || - tsDecorators.some((tsDecorator) => { - const esTreeDecorator = tsNodeToESTreeNodeMap.get(tsDecorator); - return ( - !esTreeDecorator || !esTreeDecorators.includes(esTreeDecorator) + ast = visitNode( + ast, + (node) => { + const tsNode = esTreeNodeToTSNodeMap.get(node); + if (!tsNode) { + return; + } + const tsDecorators = tsNode.decorators; + if (!Array.isArray(tsDecorators)) { + return; + } + // `esTreeNodeToTSNodeMap.get(ClassBody)` and `esTreeNodeToTSNodeMap.get(ClassDeclaration)` has the same tsNode + const esTreeNode = tsNodeToESTreeNodeMap.get(tsNode); + if (esTreeNode !== node) { + return; + } + const esTreeDecorators = esTreeNode.decorators; + if ( + !Array.isArray(esTreeDecorators) || + esTreeDecorators.length !== tsDecorators.length || + tsDecorators.some((tsDecorator) => { + const esTreeDecorator = tsNodeToESTreeNodeMap.get(tsDecorator); + return ( + !esTreeDecorator || !esTreeDecorators.includes(esTreeDecorator) + ); + }) + ) { + const { start, end } = esTreeNode.loc; + throw createError( + "Leading decorators must be attached to a class declaration", + { + start: { line: start.line, column: start.column + 1 }, + end: { line: end.line, column: end.column + 1 }, + } ); - }) - ) { - const { start, end } = esTreeNode.loc; - throw createError( - "Leading decorators must be attached to a class declaration", - { - start: { line: start.line, column: start.column + 1 }, - end: { line: end.line, column: end.column + 1 }, - } - ); + } } - }); + ); } // Keep Babel's non-standard ParenthesizedExpression nodes only if they have Closure-style type cast comments. @@ -73,105 +76,114 @@ 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. - ast = visitNode(ast, (node) => { - if ( - node.leadingComments && - node.leadingComments.some(isTypeCastComment) - ) { - startOffsetsOfTypeCastedNodes.add(locStart(node)); + ast = visitNode( + ast, + (node) => { + if ( + node.leadingComments && + node.leadingComments.some(isTypeCastComment) + ) { + startOffsetsOfTypeCastedNodes.add(locStart(node)); + } } - }); + ); - ast = visitNode(ast, (node) => { - if (node.type === "ParenthesizedExpression") { - const { expression } = node; + ast = visitNode( + ast, + (node) => { + if (node.type === "ParenthesizedExpression") { + const { expression } = node; - // Align range with `flow` - if (expression.type === "TypeCastExpression") { - expression.range = node.range; - return expression; - } + // Align range with `flow` + if (expression.type === "TypeCastExpression") { + expression.range = node.range; + return expression; + } - const start = locStart(node); - if (!startOffsetsOfTypeCastedNodes.has(start)) { - expression.extra = { ...expression.extra, parenthesized: true }; - return expression; + const start = locStart(node); + if (!startOffsetsOfTypeCastedNodes.has(start)) { + expression.extra = { ...expression.extra, parenthesized: true }; + return expression; + } } } - }); + ); } - ast = visitNode(ast, (node) => { - switch (node.type) { - // Espree - case "ChainExpression": { - return transformChainExpression(node.expression); - } - case "LogicalExpression": { - // We remove unneeded parens around same-operator LogicalExpressions - if (isUnbalancedLogicalTree(node)) { - return rebalanceLogicalTree(node); + ast = visitNode( + ast, + (node) => { + switch (node.type) { + // Espree + case "ChainExpression": { + return transformChainExpression(node.expression); } - break; - } - // fix unexpected locEnd caused by --no-semi style - case "VariableDeclaration": { - const lastDeclaration = getLast(node.declarations); - if (lastDeclaration && lastDeclaration.init) { - overrideLocEnd(node, lastDeclaration); + case "LogicalExpression": { + // We remove unneeded parens around same-operator LogicalExpressions + if (isUnbalancedLogicalTree(node)) { + return rebalanceLogicalTree(node); + } + break; } - break; - } - // remove redundant TypeScript nodes - case "TSParenthesizedType": { - node.typeAnnotation.range = [locStart(node), locEnd(node)]; - return node.typeAnnotation; - } - case "TSUnionType": - case "TSIntersectionType": - if (node.types.length === 1) { - const [firstType] = node.types; - // override loc, so that comments are attached properly - firstType.range = [locStart(node), locEnd(node)]; - return firstType; + // fix unexpected locEnd caused by --no-semi style + case "VariableDeclaration": { + const lastDeclaration = getLast(node.declarations); + if (lastDeclaration && lastDeclaration.init) { + overrideLocEnd(node, lastDeclaration); + } + break; } - break; - case "TSTypeParameter": - // babel-ts - if (typeof node.name === "string") { - const start = locStart(node); - node.name = { - type: "Identifier", - name: node.name, - range: [start, start + node.name.length], - }; + // remove redundant TypeScript nodes + case "TSParenthesizedType": { + node.typeAnnotation.range = [locStart(node), locEnd(node)]; + return node.typeAnnotation; } - break; - case "SequenceExpression": { - // Babel (unlike other parsers) includes spaces and comments in the range. Let's unify this. - const lastExpression = getLast(node.expressions); - node.range = [ - locStart(node), - Math.min(locEnd(lastExpression), locEnd(node)), - ]; - break; - } - case "ClassProperty": - // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields. - if ( - node.key && - node.key.type === "TSPrivateIdentifier" && - getNextNonSpaceNonCommentCharacter( - options.originalText, - node.key, - locEnd - ) === "?" - ) { - node.optional = true; + case "TSUnionType": + case "TSIntersectionType": + if (node.types.length === 1) { + const [firstType] = node.types; + // override loc, so that comments are attached properly + firstType.range = [locStart(node), locEnd(node)]; + return firstType; + } + break; + case "TSTypeParameter": + // babel-ts + if (typeof node.name === "string") { + const start = locStart(node); + node.name = { + type: "Identifier", + name: node.name, + range: [start, start + node.name.length], + }; + } + break; + case "SequenceExpression": { + // Babel (unlike other parsers) includes spaces and comments in the range. Let's unify this. + const lastExpression = getLast(node.expressions); + node.range = [ + locStart(node), + Math.min(locEnd(lastExpression), locEnd(node)), + ]; + break; } - break; + case "ClassProperty": + // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields. + if ( + node.key && + node.key.type === "TSPrivateIdentifier" && + getNextNonSpaceNonCommentCharacter( + options.originalText, + node.key, + locEnd + ) === "?" + ) { + node.optional = true; + } + break; + } } - }); + ); return ast; diff --git ORI/prettier/src/language-js/print/angular.js ALT/prettier/src/language-js/print/angular.js index d95da9c40..6372218df 100644 --- ORI/prettier/src/language-js/print/angular.js +++ ALT/prettier/src/language-js/print/angular.js @@ -103,16 +103,19 @@ function isNgForOf(node, index, parentNode) { * @returns {boolean} */ function hasNgSideEffect(path) { - return hasNode(path.getValue(), (node) => { - switch (node.type) { - case undefined: - return false; - case "CallExpression": - case "OptionalCallExpression": - case "AssignmentExpression": - return true; + return hasNode( + path.getValue(), + (node) => { + switch (node.type) { + case undefined: + return false; + case "CallExpression": + case "OptionalCallExpression": + case "AssignmentExpression": + return true; + } } - }); + ); } module.exports = { printAngular }; diff --git ORI/prettier/src/language-js/print/template-literal.js ALT/prettier/src/language-js/print/template-literal.js index 23e5d5692..b24e51bb0 100644 --- ORI/prettier/src/language-js/print/template-literal.js +++ ALT/prettier/src/language-js/print/template-literal.js @@ -216,15 +216,18 @@ function printTemplateExpressions(path, print) { } function escapeTemplateCharacters(doc, raw) { - return mapDoc(doc, (currentDoc) => { - if (typeof currentDoc === "string") { - return raw - ? currentDoc.replace(/(\\*)`/g, "$1$1\\`") - : uncookTemplateElementValue(currentDoc); - } + return mapDoc( + doc, + (currentDoc) => { + if (typeof currentDoc === "string") { + return raw + ? currentDoc.replace(/(\\*)`/g, "$1$1\\`") + : uncookTemplateElementValue(currentDoc); + } - return currentDoc; - }); + return currentDoc; + } + ); } function uncookTemplateElementValue(cookedValue) { diff --git ORI/prettier/src/language-js/utils.js ALT/prettier/src/language-js/utils.js index 744685678..0b4fde320 100644 --- ORI/prettier/src/language-js/utils.js +++ ALT/prettier/src/language-js/utils.js @@ -684,8 +684,10 @@ function hasLeadingOwnLineComment(text, node) { return hasNodeIgnoreComment(node); } - return hasComment(node, CommentCheckFlags.Leading, (comment) => - hasNewline(text, locEnd(comment)) + return hasComment( + node, + CommentCheckFlags.Leading, + (comment) => hasNewline(text, locEnd(comment)) ); } diff --git ORI/prettier/src/language-markdown/index.js ALT/prettier/src/language-markdown/index.js index 994023c43..3ce09f693 100644 --- ORI/prettier/src/language-markdown/index.js +++ ALT/prettier/src/language-markdown/index.js @@ -5,21 +5,27 @@ const printer = require("./printer-markdown"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/Markdown.json"), (data) => ({ - since: "1.8.0", - parsers: ["markdown"], - vscodeLanguageIds: ["markdown"], - filenames: [...data.filenames, "README"], - extensions: data.extensions.filter((extension) => extension !== ".mdx"), - })), - createLanguage(require("linguist-languages/data/Markdown.json"), () => ({ - name: "MDX", - since: "1.15.0", - parsers: ["mdx"], - vscodeLanguageIds: ["mdx"], - filenames: [], - extensions: [".mdx"], - })), + createLanguage( + require("linguist-languages/data/Markdown.json"), + (data) => ({ + since: "1.8.0", + parsers: ["markdown"], + vscodeLanguageIds: ["markdown"], + filenames: [...data.filenames, "README"], + extensions: data.extensions.filter((extension) => extension !== ".mdx"), + }) + ), + createLanguage( + require("linguist-languages/data/Markdown.json"), + () => ({ + name: "MDX", + since: "1.15.0", + parsers: ["mdx"], + vscodeLanguageIds: ["mdx"], + filenames: [], + extensions: [".mdx"], + }) + ), ]; const printers = { diff --git ORI/prettier/src/language-markdown/parser-markdown.js ALT/prettier/src/language-markdown/parser-markdown.js index 494b77977..7927cc7ff 100644 --- ORI/prettier/src/language-markdown/parser-markdown.js +++ ALT/prettier/src/language-markdown/parser-markdown.js @@ -49,17 +49,20 @@ function identity(x) { function htmlToJsx() { return (ast) => - mapAst(ast, (node, _index, [parent]) => { - if ( - node.type !== "html" || - mdx.COMMENT_REGEX.test(node.value) || - INLINE_NODE_WRAPPER_TYPES.includes(parent.type) - ) { - return node; + mapAst( + ast, + (node, _index, [parent]) => { + if ( + node.type !== "html" || + mdx.COMMENT_REGEX.test(node.value) || + INLINE_NODE_WRAPPER_TYPES.includes(parent.type) + ) { + return node; + } + + return { ...node, type: "jsx" }; } - - return { ...node, type: "jsx" }; - }); + ); } function frontMatter() { diff --git ORI/prettier/src/language-markdown/print-preprocess.js ALT/prettier/src/language-markdown/print-preprocess.js index fcbac279a..502573676 100644 --- ORI/prettier/src/language-markdown/print-preprocess.js +++ ALT/prettier/src/language-markdown/print-preprocess.js @@ -19,40 +19,49 @@ function preprocess(ast, options) { } function transformImportExport(ast) { - return mapAst(ast, (node) => { - if (node.type !== "import" && node.type !== "export") { - return node; - } + return mapAst( + ast, + (node) => { + if (node.type !== "import" && node.type !== "export") { + return node; + } - return { ...node, type: "importExport" }; - }); + return { ...node, type: "importExport" }; + } + ); } function transformInlineCode(ast) { - return mapAst(ast, (node) => { - if (node.type !== "inlineCode") { - return node; - } + return mapAst( + ast, + (node) => { + if (node.type !== "inlineCode") { + return node; + } - return { ...node, value: node.value.replace(/\s+/g, " ") }; - }); + return { ...node, value: node.value.replace(/\s+/g, " ") }; + } + ); } function restoreUnescapedCharacter(ast, options) { - return mapAst(ast, (node) => - node.type !== "text" || - node.value === "*" || - node.value === "_" || // handle these cases in printer - !isSingleCharRegex.test(node.value) || - node.position.end.offset - node.position.start.offset === node.value.length - ? node - : { - ...node, - value: options.originalText.slice( - node.position.start.offset, - node.position.end.offset - ), - } + return mapAst( + ast, + (node) => + node.type !== "text" || + node.value === "*" || + node.value === "_" || // handle these cases in printer + !isSingleCharRegex.test(node.value) || + node.position.end.offset - node.position.start.offset === + node.value.length + ? node + : { + ...node, + value: options.originalText.slice( + node.position.start.offset, + node.position.end.offset + ), + } ); } @@ -73,21 +82,24 @@ function mergeContinuousImportExport(ast) { } function mergeChildren(ast, shouldMerge, mergeNode) { - return mapAst(ast, (node) => { - if (!node.children) { - return node; - } - const children = node.children.reduce((current, child) => { - const lastChild = current[current.length - 1]; - if (lastChild && shouldMerge(lastChild, child)) { - current.splice(-1, 1, mergeNode(lastChild, child)); - } else { - current.push(child); + return mapAst( + ast, + (node) => { + if (!node.children) { + return node; } - return current; - }, []); - return { ...node, children }; - }); + const children = node.children.reduce((current, child) => { + const lastChild = current[current.length - 1]; + if (lastChild && shouldMerge(lastChild, child)) { + current.splice(-1, 1, mergeNode(lastChild, child)); + } else { + current.push(child); + } + return current; + }, []); + return { ...node, children }; + } + ); } function mergeContinuousTexts(ast) { @@ -106,79 +118,88 @@ function mergeContinuousTexts(ast) { } function splitTextIntoSentences(ast, options) { - return mapAst(ast, (node, index, [parentNode]) => { - if (node.type !== "text") { - return node; - } + return mapAst( + ast, + (node, index, [parentNode]) => { + if (node.type !== "text") { + return node; + } - let { value } = node; + let { value } = node; - if (parentNode.type === "paragraph") { - if (index === 0) { - value = value.trimStart(); - } - if (index === parentNode.children.length - 1) { - value = value.trimEnd(); + if (parentNode.type === "paragraph") { + if (index === 0) { + value = value.trimStart(); + } + if (index === parentNode.children.length - 1) { + value = value.trimEnd(); + } } - } - return { - type: "sentence", - position: node.position, - children: splitText(value, options), - }; - }); + return { + type: "sentence", + position: node.position, + children: splitText(value, options), + }; + } + ); } function transformIndentedCodeblockAndMarkItsParentList(ast, options) { - return mapAst(ast, (node, index, parentStack) => { - if (node.type === "code") { - // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it - const isIndented = /^\n?( {4,}|\t)/.test( - options.originalText.slice( - node.position.start.offset, - node.position.end.offset - ) - ); - - node.isIndented = isIndented; - - if (isIndented) { - for (let i = 0; i < parentStack.length; i++) { - const parent = parentStack[i]; + return mapAst( + ast, + (node, index, parentStack) => { + if (node.type === "code") { + // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it + const isIndented = /^\n?( {4,}|\t)/.test( + options.originalText.slice( + node.position.start.offset, + node.position.end.offset + ) + ); - // no need to check checked items - if (parent.hasIndentedCodeblock) { - break; - } + node.isIndented = isIndented; - if (parent.type === "list") { - parent.hasIndentedCodeblock = true; + if (isIndented) { + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; + + // no need to check checked items + if (parent.hasIndentedCodeblock) { + break; + } + + if (parent.type === "list") { + parent.hasIndentedCodeblock = true; + } } } } + return node; } - return node; - }); + ); } function markAlignedList(ast, options) { - return mapAst(ast, (node, index, parentStack) => { - if (node.type === "list" && node.children.length > 0) { - // if one of its parents is not aligned, it's not possible to be aligned in sub-lists - for (let i = 0; i < parentStack.length; i++) { - const parent = parentStack[i]; - if (parent.type === "list" && !parent.isAligned) { - node.isAligned = false; - return node; + return mapAst( + ast, + (node, index, parentStack) => { + if (node.type === "list" && node.children.length > 0) { + // if one of its parents is not aligned, it's not possible to be aligned in sub-lists + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; + if (parent.type === "list" && !parent.isAligned) { + node.isAligned = false; + return node; + } } + + node.isAligned = isAligned(node); } - node.isAligned = isAligned(node); + return node; } - - return node; - }); + ); function getListItemStart(listItem) { return listItem.children.length === 0 diff --git ORI/prettier/src/language-markdown/printer-markdown.js ALT/prettier/src/language-markdown/printer-markdown.js index 179132dc2..7f346feac 100644 --- ORI/prettier/src/language-markdown/printer-markdown.js +++ ALT/prettier/src/language-markdown/printer-markdown.js @@ -129,8 +129,9 @@ function genericPrint(path, options, print) { )) ) { // backslash is parsed as part of autolinks, so we need to remove it - escapedValue = escapedValue.replace(/^(\\?[*_])+/, (prefix) => - prefix.replace(/\\/g, "") + escapedValue = escapedValue.replace( + /^(\\?[*_])+/, + (prefix) => prefix.replace(/\\/g, "") ); } diff --git ORI/prettier/src/language-yaml/index.js ALT/prettier/src/language-yaml/index.js index 7205e75d8..b74e7514f 100644 --- ORI/prettier/src/language-yaml/index.js +++ ALT/prettier/src/language-yaml/index.js @@ -5,16 +5,19 @@ const printer = require("./printer-yaml"); const options = require("./options"); const languages = [ - createLanguage(require("linguist-languages/data/YAML.json"), (data) => ({ - since: "1.14.0", - parsers: ["yaml"], - vscodeLanguageIds: ["yaml", "ansible", "home-assistant"], - // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629 - filenames: [ - ...data.filenames.filter((filename) => filename !== "yarn.lock"), - ".prettierrc", - ], - })), + createLanguage( + require("linguist-languages/data/YAML.json"), + (data) => ({ + since: "1.14.0", + parsers: ["yaml"], + vscodeLanguageIds: ["yaml", "ansible", "home-assistant"], + // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629 + filenames: [ + ...data.filenames.filter((filename) => filename !== "yarn.lock"), + ".prettierrc", + ], + }) + ), ]; const parsers = { diff --git ORI/prettier/src/language-yaml/print/block.js ALT/prettier/src/language-yaml/print/block.js index fcb603908..0b24de0f1 100644 --- ORI/prettier/src/language-yaml/print/block.js +++ ALT/prettier/src/language-yaml/print/block.js @@ -26,8 +26,9 @@ const { alignWithSpaces } = require("./misc"); function printBlock(path, print, options) { const node = path.getValue(); - const parentIndent = getAncestorCount(path, (ancestorNode) => - isNode(ancestorNode, ["sequence", "mapping"]) + const parentIndent = getAncestorCount( + path, + (ancestorNode) => isNode(ancestorNode, ["sequence", "mapping"]) ); const isLastDescendant = isLastDescendantNode(path); /** @type {Doc[]} */ diff --git ORI/prettier/tests_config/utils/stringify-options-for-title.js ALT/prettier/tests_config/utils/stringify-options-for-title.js index dbc95627f..b08780695 100644 --- ORI/prettier/tests_config/utils/stringify-options-for-title.js +++ ALT/prettier/tests_config/utils/stringify-options-for-title.js @@ -1,12 +1,14 @@ "use strict"; function stringifyOptions(options) { - const string = JSON.stringify(options || {}, (key, value) => - key === "plugins" || key === "errors" - ? undefined - : value === Number.POSITIVE_INFINITY - ? "Infinity" - : value + const string = JSON.stringify( + options || {}, + (key, value) => + key === "plugins" || key === "errors" + ? undefined + : value === Number.POSITIVE_INFINITY + ? "Infinity" + : value ); return string === "{}" ? "" : string; diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/explicit-function-return-type.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/explicit-function-return-type.ts index f0904f07..b7987274 100644 --- ORI/typescript-eslint/packages/eslint-plugin/src/rules/explicit-function-return-type.ts +++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/explicit-function-return-type.ts @@ -82,21 +82,29 @@ export default util.createRule({ return; } - checkFunctionExpressionReturnType(node, options, sourceCode, loc => - context.report({ - node, - loc, - messageId: 'missingReturnType', - }), + checkFunctionExpressionReturnType( + node, + options, + sourceCode, + loc => + context.report({ + node, + loc, + messageId: 'missingReturnType', + }), ); }, FunctionDeclaration(node): void { - checkFunctionReturnType(node, options, sourceCode, loc => - context.report({ - node, - loc, - messageId: 'missingReturnType', - }), + checkFunctionReturnType( + node, + options, + sourceCode, + loc => + context.report({ + node, + loc, + messageId: 'missingReturnType', + }), ); }, }; diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts index 2ff89c59..9a3d132c 100644 --- ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts +++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts @@ -117,12 +117,14 @@ function getTypeParametersFromType( return undefined; } - return findFirstResult(declarations, decl => - tsutils.isClassLikeDeclaration(decl) || - ts.isTypeAliasDeclaration(decl) || - ts.isInterfaceDeclaration(decl) - ? decl.typeParameters - : undefined, + return findFirstResult( + declarations, + decl => + tsutils.isClassLikeDeclaration(decl) || + ts.isTypeAliasDeclaration(decl) || + ts.isInterfaceDeclaration(decl) + ? decl.typeParameters + : undefined, ); } diff --git ORI/typescript-eslint/packages/typescript-estree/src/node-utils.ts ALT/typescript-eslint/packages/typescript-estree/src/node-utils.ts index 74c58666..b976e9c9 100644 --- ORI/typescript-eslint/packages/typescript-estree/src/node-utils.ts +++ ALT/typescript-eslint/packages/typescript-estree/src/node-utils.ts @@ -367,16 +367,19 @@ export function findNextToken( // this is token that starts at the end of previous token - return it return n; } - return firstDefined(n.getChildren(ast), (child: ts.Node) => { - const shouldDiveInChildNode = - // previous token is enclosed somewhere in the child - (child.pos <= previousToken.pos && child.end > previousToken.end) || - // previous token ends exactly at the beginning of child - child.pos === previousToken.end; - return shouldDiveInChildNode && nodeHasTokens(child, ast) - ? find(child) - : undefined; - }); + return firstDefined( + n.getChildren(ast), + (child: ts.Node) => { + const shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + child.pos === previousToken.end; + return shouldDiveInChildNode && nodeHasTokens(child, ast) + ? find(child) + : undefined; + }, + ); } } diff --git ORI/vega-lite/src/compile/legend/encode.ts ALT/vega-lite/src/compile/legend/encode.ts index 180d8758e..c88a64f1f 100644 --- ORI/vega-lite/src/compile/legend/encode.ts +++ ALT/vega-lite/src/compile/legend/encode.ts @@ -181,9 +181,12 @@ function getMaxValue(channelDef: Encoding['opacity']) { export function getFirstConditionValue( channelDef: Encoding['fill' | 'stroke' | 'shape'] ): V { - return getConditionValue(channelDef, (v: V, conditionalDef: Conditional>) => { - return getFirstDefined(v, conditionalDef.value); - }); + return getConditionValue( + channelDef, + (v: V, conditionalDef: Conditional>) => { + return getFirstDefined(v, conditionalDef.value); + } + ); } function getConditionValue( diff --git ORI/vega-lite/src/compile/mark/encode/nonposition.ts ALT/vega-lite/src/compile/mark/encode/nonposition.ts index e6c5d58a3..390856f51 100644 --- ORI/vega-lite/src/compile/mark/encode/nonposition.ts +++ ALT/vega-lite/src/compile/mark/encode/nonposition.ts @@ -34,16 +34,21 @@ export function nonPosition( const channelDef = encoding[channel]; - return wrapCondition(model, channelDef, vgChannel ?? channel, cDef => { - return ref.midPoint({ - channel, - channelDef: cDef, - markDef, - config, - scaleName: model.scaleName(channel), - scale: model.getScaleComponent(channel), - stack: null, // No need to provide stack for non-position as it does not affect mid point - defaultRef - }); - }); + return wrapCondition( + model, + channelDef, + vgChannel ?? channel, + cDef => { + return ref.midPoint({ + channel, + channelDef: cDef, + markDef, + config, + scaleName: model.scaleName(channel), + scale: model.getScaleComponent(channel), + stack: null, // No need to provide stack for non-position as it does not affect mid point + defaultRef + }); + } + ); } diff --git ORI/vega-lite/src/compile/mark/encode/tooltip.ts ALT/vega-lite/src/compile/mark/encode/tooltip.ts index 1bf44ff88..9c24ac9cf 100644 --- ORI/vega-lite/src/compile/mark/encode/tooltip.ts +++ ALT/vega-lite/src/compile/mark/encode/tooltip.ts @@ -30,39 +30,44 @@ export function tooltip(model: UnitModel, opt: {reactiveGeom?: boolean} = {}) { return {tooltip: tooltipRefForEncoding({tooltip: channelDef}, stack, config, opt)}; } else { const datum = opt.reactiveGeom ? 'datum.datum' : 'datum'; - return wrapCondition(model, channelDef, 'tooltip', cDef => { - // use valueRef based on channelDef first - const tooltipRefFromChannelDef = textRef(cDef, config, datum); - if (tooltipRefFromChannelDef) { - return tooltipRefFromChannelDef; - } + return wrapCondition( + model, + channelDef, + 'tooltip', + cDef => { + // use valueRef based on channelDef first + const tooltipRefFromChannelDef = textRef(cDef, config, datum); + if (tooltipRefFromChannelDef) { + return tooltipRefFromChannelDef; + } - if (cDef === null) { - // Allow using encoding.tooltip = null to disable tooltip - return undefined; - } + if (cDef === null) { + // Allow using encoding.tooltip = null to disable tooltip + return undefined; + } - let markTooltip = getMarkPropOrConfig('tooltip', markDef, config); + let markTooltip = getMarkPropOrConfig('tooltip', markDef, config); - if (markTooltip === true) { - markTooltip = {content: 'encoding'}; - } + if (markTooltip === true) { + markTooltip = {content: 'encoding'}; + } - if (isString(markTooltip)) { - return {value: markTooltip}; - } else if (isObject(markTooltip)) { - // `tooltip` is `{fields: 'encodings' | 'fields'}` - if (isSignalRef(markTooltip)) { - return markTooltip; - } else if (markTooltip.content === 'encoding') { - return tooltipRefForEncoding(encoding, stack, config, opt); - } else { - return {signal: datum}; + if (isString(markTooltip)) { + return {value: markTooltip}; + } else if (isObject(markTooltip)) { + // `tooltip` is `{fields: 'encodings' | 'fields'}` + if (isSignalRef(markTooltip)) { + return markTooltip; + } else if (markTooltip.content === 'encoding') { + return tooltipRefForEncoding(encoding, stack, config, opt); + } else { + return {signal: datum}; + } } - } - return undefined; - }); + return undefined; + } + ); } } diff --git ORI/vega-lite/src/compile/predicate.ts ALT/vega-lite/src/compile/predicate.ts index 75335af3b..ea332b01b 100644 --- ORI/vega-lite/src/compile/predicate.ts +++ ALT/vega-lite/src/compile/predicate.ts @@ -11,14 +11,17 @@ import {parseSelectionPredicate} from './selection/parse'; */ // model is only used for selection filters. export function expression(model: Model, filterOp: LogicalComposition, node?: DataFlowNode): string { - return logicalExpr(filterOp, (predicate: Predicate) => { - if (isString(predicate)) { - return predicate; - } else if (isSelectionPredicate(predicate)) { - return parseSelectionPredicate(model, predicate, node); - } else { - // Filter Object - return fieldFilterExpression(predicate); + return logicalExpr( + filterOp, + (predicate: Predicate) => { + if (isString(predicate)) { + return predicate; + } else if (isSelectionPredicate(predicate)) { + return parseSelectionPredicate(model, predicate, node); + } else { + // Filter Object + return fieldFilterExpression(predicate); + } } - }); + ); } diff --git ORI/vega-lite/src/compile/projection/parse.ts ALT/vega-lite/src/compile/projection/parse.ts index 21c41693e..44f4e77ac 100644 --- ORI/vega-lite/src/compile/projection/parse.ts +++ ALT/vega-lite/src/compile/projection/parse.ts @@ -73,22 +73,25 @@ function gatherFitData(model: UnitModel) { } function mergeIfNoConflict(first: ProjectionComponent, second: ProjectionComponent): ProjectionComponent { - const allPropertiesShared = every(PROJECTION_PROPERTIES, prop => { - // neither has the property - if (!hasOwnProperty(first.explicit, prop) && !hasOwnProperty(second.explicit, prop)) { - return true; - } - // both have property and an equal value for property - if ( - hasOwnProperty(first.explicit, prop) && - hasOwnProperty(second.explicit, prop) && - // some properties might be signals or objects and require hashing for comparison - deepEqual(first.get(prop), second.get(prop)) - ) { - return true; + const allPropertiesShared = every( + PROJECTION_PROPERTIES, + prop => { + // neither has the property + if (!hasOwnProperty(first.explicit, prop) && !hasOwnProperty(second.explicit, prop)) { + return true; + } + // both have property and an equal value for property + if ( + hasOwnProperty(first.explicit, prop) && + hasOwnProperty(second.explicit, prop) && + // some properties might be signals or objects and require hashing for comparison + deepEqual(first.get(prop), second.get(prop)) + ) { + return true; + } + return false; } - return false; - }); + ); const size = deepEqual(first.size, second.size); if (size) { @@ -118,23 +121,26 @@ function parseNonUnitProjections(model: Model): ProjectionComponent { } // analyze parsed projections, attempt to merge - const mergable = every(model.children, child => { - const projection = child.component.projection; - if (!projection) { - // child layer does not use a projection - return true; - } else if (!nonUnitProjection) { - // cached 'projection' is null, cache this one - nonUnitProjection = projection; - return true; - } else { - const merge = mergeIfNoConflict(nonUnitProjection, projection); - if (merge) { - nonUnitProjection = merge; + const mergable = every( + model.children, + child => { + const projection = child.component.projection; + if (!projection) { + // child layer does not use a projection + return true; + } else if (!nonUnitProjection) { + // cached 'projection' is null, cache this one + nonUnitProjection = projection; + return true; + } else { + const merge = mergeIfNoConflict(nonUnitProjection, projection); + if (merge) { + nonUnitProjection = merge; + } + return !!merge; } - return !!merge; } - }); + ); // if cached one and all other children share the same projection, if (nonUnitProjection && mergable) { diff --git ORI/vega-lite/src/compile/selection/interval.ts ALT/vega-lite/src/compile/selection/interval.ts index 7dd7b69b1..2ebde45f0 100644 --- ORI/vega-lite/src/compile/selection/interval.ts +++ ALT/vega-lite/src/compile/selection/interval.ts @@ -200,13 +200,16 @@ function channelSignals( const size = model.getSizeSignalRef(channel === X ? 'width' : 'height').signal; const coord = `${channel}(unit)`; - const on = events(selCmpt, (def: OnEvent[], evt: Stream) => { - return [ - ...def, - {events: evt.between[0], update: `[${coord}, ${coord}]`}, // Brush Start - {events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]`} // Brush End - ]; - }); + const on = events( + selCmpt, + (def: OnEvent[], evt: Stream) => { + return [ + ...def, + {events: evt.between[0], update: `[${coord}, ${coord}]`}, // Brush Start + {events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]`} // Brush End + ]; + } + ); // React to pan/zooms of continuous scales. Non-continuous scales // (band, point) cannot be pan/zoomed and any other changes diff --git ORI/vega-lite/src/encoding.ts ALT/vega-lite/src/encoding.ts index 0e6b222da..9bdc3677e 100644 --- ORI/vega-lite/src/encoding.ts +++ ALT/vega-lite/src/encoding.ts @@ -324,18 +324,21 @@ export function channelHasField( } export function isAggregate(encoding: EncodingWithFacet) { - return some(CHANNELS, channel => { - if (channelHasField(encoding, channel)) { - const channelDef = encoding[channel]; - if (isArray(channelDef)) { - return some(channelDef, fieldDef => !!fieldDef.aggregate); - } else { - const fieldDef = getFieldDef(channelDef); - return fieldDef && !!fieldDef.aggregate; + return some( + CHANNELS, + channel => { + if (channelHasField(encoding, channel)) { + const channelDef = encoding[channel]; + if (isArray(channelDef)) { + return some(channelDef, fieldDef => !!fieldDef.aggregate); + } else { + const fieldDef = getFieldDef(channelDef); + return fieldDef && !!fieldDef.aggregate; + } } + return false; } - return false; - }); + ); } export function extractTransformsFromEncoding(oldEncoding: Encoding, config: Config) { diff --git ORI/vega-lite/src/normalize/selectioncompat.ts ALT/vega-lite/src/normalize/selectioncompat.ts index f5e64df73..b78d40119 100644 --- ORI/vega-lite/src/normalize/selectioncompat.ts +++ ALT/vega-lite/src/normalize/selectioncompat.ts @@ -142,18 +142,22 @@ function normalizeBinExtent(bin: BinParams): BinParams { function normalizePredicate(op: any, normParams: NormalizerParams) { // Normalize old compositions of selection names (e.g., selection: {and: ["one", "two"]}) const normalizeSelectionComposition = (o: LogicalComposition) => { - return normalizeLogicalComposition(o, param => { - const empty = normParams.emptySelections[param] ?? true; - const pred = {param, empty}; - normParams.selectionPredicates[param] ??= []; - normParams.selectionPredicates[param].push(pred); - return pred as any; - }); + return normalizeLogicalComposition( + o, + param => { + const empty = normParams.emptySelections[param] ?? true; + const pred = {param, empty}; + normParams.selectionPredicates[param] ??= []; + normParams.selectionPredicates[param].push(pred); + return pred as any; + } + ); }; return op.selection ? normalizeSelectionComposition(op.selection) - : normalizeLogicalComposition(op.test || op.filter, o => - o.selection ? normalizeSelectionComposition(o.selection) : o + : normalizeLogicalComposition( + op.test || op.filter, + o => (o.selection ? normalizeSelectionComposition(o.selection) : o) ); } diff --git ORI/vega-lite/test/compositemark/common.test.ts ALT/vega-lite/test/compositemark/common.test.ts index 845a89a47..8cc9eeba5 100644 --- ORI/vega-lite/test/compositemark/common.test.ts +++ ALT/vega-lite/test/compositemark/common.test.ts @@ -167,12 +167,15 @@ describe('common', () => { expect(isAggregate(aggregateTransform)).toBeTruthy(); expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return ( - aggregateFieldDef.field === aggField && - (aggregateFieldDef.op === 'mean' || aggregateFieldDef.op === 'median') - ); - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return ( + aggregateFieldDef.field === aggField && + (aggregateFieldDef.op === 'mean' || aggregateFieldDef.op === 'median') + ); + } + ) ).toBe(true); }); } diff --git ORI/vega-lite/test/compositemark/errorband.test.ts ALT/vega-lite/test/compositemark/errorband.test.ts index 4466d3a7f..249078a73 100644 --- ORI/vega-lite/test/compositemark/errorband.test.ts +++ ALT/vega-lite/test/compositemark/errorband.test.ts @@ -91,14 +91,20 @@ describe('normalizeErrorBand', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; if (layer) { expect( - some(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'rect'; - }) + some( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'rect'; + } + ) ).toBe(true); expect( - some(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'rule'; - }) + some( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'rule'; + } + ) ).toBe(true); } else { expect(false).toBe(true); @@ -121,14 +127,20 @@ describe('normalizeErrorBand', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; if (layer) { expect( - some(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'area'; - }) + some( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'area'; + } + ) ).toBe(true); expect( - some(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'line'; - }) + some( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.type === 'line'; + } + ) ).toBe(true); } else { expect(false).toBe(true); @@ -151,9 +163,12 @@ describe('normalizeErrorBand', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; if (layer) { expect( - every(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.interpolate === 'monotone'; - }) + every( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && unitSpec.mark.interpolate === 'monotone'; + } + ) ).toBe(true); } else { expect(false).toBe(true); @@ -176,9 +191,12 @@ describe('normalizeErrorBand', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; expect( - every(layer, unitSpec => { - return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && !unitSpec.mark.interpolate; - }) + every( + layer, + unitSpec => { + return isUnitSpec(unitSpec) && isMarkDef(unitSpec.mark) && !unitSpec.mark.interpolate; + } + ) ).toBe(true); expect(localLogger.warns[0]).toEqual(log.message.errorBand1DNotSupport('interpolate')); }) diff --git ORI/vega-lite/test/compositemark/errorbar.test.ts ALT/vega-lite/test/compositemark/errorbar.test.ts index f9d14a294..8d1a52a64 100644 --- ORI/vega-lite/test/compositemark/errorbar.test.ts +++ ALT/vega-lite/test/compositemark/errorbar.test.ts @@ -228,16 +228,19 @@ describe('normalizeErrorBar with raw data input', () => { const layer = isLayerSpec(outputSpec) && outputSpec.layer; if (layer) { expect( - some(layer, unitSpec => { - return ( - isUnitSpec(unitSpec) && - isMarkDef(unitSpec.mark) && - unitSpec.mark.type === 'tick' && - unitSpec.mark.size === size && - unitSpec.mark.color === color && - unitSpec.mark.opacity === opacity - ); - }) + some( + layer, + unitSpec => { + return ( + isUnitSpec(unitSpec) && + isMarkDef(unitSpec.mark) && + unitSpec.mark.type === 'tick' && + unitSpec.mark.size === size && + unitSpec.mark.color === color && + unitSpec.mark.opacity === opacity + ); + } + ) ).toBe(true); } else { expect(false).toBe(true); @@ -537,54 +540,78 @@ describe('normalizeErrorBar for all possible extents and centers with raw data i if (isAggregate(aggregateTransform)) { if (extent === 'iqr' || (center === 'median' && !extent)) { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === 'median'; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === 'median'; + } + ) ).toBe(true); } else if (extent === 'ci') { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === 'mean'; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === 'mean'; + } + ) ).toBe(true); } else { if (center) { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === center; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === center; + } + ) ).toBe(true); } else { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === 'mean'; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === 'mean'; + } + ) ).toBe(true); } if (extent) { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return isPartOfExtent(extent, aggregateFieldDef.op); - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return isPartOfExtent(extent, aggregateFieldDef.op); + } + ) ).toBe(true); } else if (center === 'median') { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return isPartOfExtent('iqr', aggregateFieldDef.op); - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return isPartOfExtent('iqr', aggregateFieldDef.op); + } + ) ).toBe(true); expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return aggregateFieldDef.op === 'median'; - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return aggregateFieldDef.op === 'median'; + } + ) ).toBe(false); } else { expect( - some(aggregateTransform.aggregate, aggregateFieldDef => { - return isPartOfExtent('stderr', aggregateFieldDef.op); - }) + some( + aggregateTransform.aggregate, + aggregateFieldDef => { + return isPartOfExtent('stderr', aggregateFieldDef.op); + } + ) ).toBe(true); } } diff --git ORI/vega-lite/test/scale.test.ts ALT/vega-lite/test/scale.test.ts index 7f167e049..28bbfe81b 100644 --- ORI/vega-lite/test/scale.test.ts +++ ALT/vega-lite/test/scale.test.ts @@ -16,9 +16,12 @@ describe('scale', () => { it('should have at least one supported scale types for all scale properties', () => { for (const prop of scale.SCALE_PROPERTIES) { expect( - some(scale.SCALE_TYPES, scaleType => { - return scale.scaleTypeSupportProperty(scaleType, prop); - }) + some( + scale.SCALE_TYPES, + scaleType => { + return scale.scaleTypeSupportProperty(scaleType, prop); + } + ) ).toBeTruthy(); } }); @@ -39,9 +42,12 @@ describe('scale', () => { it('should have at least one supported scale types for all channels with scale', () => { for (const channel of SCALE_CHANNELS) { expect( - some(SCALE_TYPES, scaleType => { - return channelSupportScaleType(channel, scaleType); - }) + some( + SCALE_TYPES, + scaleType => { + return channelSupportScaleType(channel, scaleType); + } + ) ).toBeTruthy(); } }); @@ -50,9 +56,12 @@ describe('scale', () => { it('should have at least one supported channel for all scale types', () => { for (const scaleType of SCALE_TYPES) { expect( - some(SCALE_CHANNELS, channel => { - return channelSupportScaleType(channel, scaleType); - }) + some( + SCALE_CHANNELS, + channel => { + return channelSupportScaleType(channel, scaleType); + } + ) ).toBeTruthy(); } }); ```