Improve comments (#19359)

This commit is contained in:
fisker Cheung authored and GitHub committed 2026-06-16 02:09:45 +08:00
1 parent b149a978ec
commit 96693ea007
43 files changed
+59 -58

No files matched your search

+2 -1
View File
@@ -240,6 +240,8 @@ const configs = [
/* eslint-plugin-unicorn */
"unicorn/better-dom-traversing": "off",
"unicorn/catch-error-name": "off",
// Doesn't work for code and JSDoc in comments
"unicorn/comment-content": "off",
"unicorn/consistent-class-member-order": "off",
"unicorn/consistent-compound-words": "off",
"unicorn/consistent-destructuring": "off",
@@ -308,7 +310,6 @@ const configs = [
"unicorn/template-indent": "error",
// TODO: Enable the followings
"unicorn/comment-content": "off",
"unicorn/prefer-short-arrow-method": "off",
"unicorn/no-useless-concat": "off",
"unicorn/no-computed-property-existence-check": "off",
+1 -1
View File
@@ -92,7 +92,7 @@ function getEsbuildOptions({ packageConfig, file, cliOptions, buildOptions }) {
module: "*",
process: (text, file) => transform(text, file, buildOptions),
},
// #12493, not sure what the problem is, but replace the cjs version with esm version seems fix it
// #12493, not sure what the problem is, but replace the CJS version with ESM version seems fix it
{
module: require.resolve("tslib"),
path: require.resolve("tslib").replace(/tslib\.js$/, "tslib.es6.js"),
@@ -16,7 +16,7 @@ function esmifyTypescriptEslint(text) {
````
*/
text = text.replaceAll(
// TODO: Use duplicate capture group name when eslint supports
// TODO: Use duplicate capture group name when ESLint supports
/(?<=\n)(?:const|let|var) (?<variable>\w+) = (?:__importStar\(require\(["'](?<moduleName1>.*?)["']\)\)|require\(["'](?<moduleName2>.*?)["']\));/g,
(...args) => {
const groups = args.at(-1);
+1 -1
View File
@@ -15,7 +15,7 @@ Get a package file.
- a package name with path like `"prettier/index.js"`
@param {string} [base] -- Where the package should be solved from
- a package name like `"prettier"`
- a file url like `"file://path/to/prettier"`
- a file URL like `"file://path/to/prettier"`
- an absolute path like `"/path/to/prettier"`
@returns {string}
*/
+1 -1
View File
@@ -159,7 +159,7 @@ function getCommentDescription(content, comment) {
return `template comment on line ${startLine}-${endLine}`;
}
// Forbid html in title
// Forbid HTML in title
// https://github.com/prettier/prettier/issues/17089
function validateTitle(displayPath, title) {
const processor = unified().use(remarkParse);
+1 -1
View File
@@ -20,7 +20,7 @@ function runCommand(command) {
});
}
// Fetch git tags to get the previous version number (i.e. the latest tag)
// Fetch Git tags to get the previous version number (i.e. the latest tag)
await runCommand("git fetch --tags");
// Install script's dependencies before any require
+1 -1
View File
@@ -10,7 +10,7 @@ export default async function updateVersion({ version, next }) {
return;
}
// Update github issue templates
// Update GitHub issue templates
processFile(".github/ISSUE_TEMPLATE/formatting.md", (content) =>
content.replace(/^(\*\*Prettier ).*?(\*\*)$/m, `$1${version}$2`),
);
@@ -1,6 +1,6 @@
const MESSAGE_ID = "jsx-identifier-case";
// To ignore variables, config eslint like this
// To ignore variables, config ESLint like this
// {'prettier-internal-rules/jsx-identifier-case': ['error', 'name1', ... 'nameN']}
export default {
+1 -1
View File
@@ -22,7 +22,7 @@ function parseArgv(rawArguments, detailedOptions, logger, keys) {
...Object.fromEntries(
Object.entries(normalized).map(([key, value]) => {
const option = detailedOptions.find(({ name }) => name === key) || {};
// If the flag is a prettier api option, use the option name
// If the flag is a prettier API option, use the option name
// Otherwise use camel case for readability
// `--ignore-unknown` -> `ignoreUnknown`
return [option.forwardToApi || camelCase(key), value];
+1 -1
View File
@@ -58,7 +58,7 @@ async function getParser(file, options) {
// We should wrap this function with `withPlugins` and use `options.plugins` directly instead of loading plugins here
// See #18375 #18081
// But somehow it breaks VSCode extension, see #18353
// But somehow it breaks VS Code extension, see #18353
plugins = (
await Promise.all([loadBuiltinPlugins(), loadPlugins(plugins)])
).flat();
+1 -1
View File
@@ -127,7 +127,7 @@ function mergeOverrides(configResult, filePath) {
return options;
}
// Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js
// Based on ESLint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js
function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
const patternList = Array.isArray(patterns) ? patterns : [patterns];
// micromatch always matches against basename when the option is enabled
+1 -1
View File
@@ -91,7 +91,7 @@ const inferParser = withPlugins((file, options) =>
inferParserWithoutPlugins(options, { physicalFile: file }),
);
// Internal shared with cli
// Internal shared with CLI
const sharedWithCli = {
errors,
optionCategories,
+1 -1
View File
@@ -175,7 +175,7 @@ function parseNestedValue(node, options) {
}
function parseValue(value, options) {
// Inline javascript in Less
// Inline JavaScript in Less
if (options.parser === "less" && value.startsWith("~`")) {
return { type: "value-unknown", value };
}
+1 -1
View File
@@ -230,7 +230,7 @@ function parseNestedCSS(node, options) {
}
}
// only css support custom-selector
// only CSS support custom-selector
if (options.parser === "css" && node.name === "custom-selector") {
const customSelector = node.params.match(/:--\S+\s+/)[0].trim();
node.customSelector = customSelector;
@@ -280,7 +280,7 @@ function printCommaSeparatedValueGroup(path, options, print) {
continue;
}
// Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
// Ignore CSS variables and interpolation in SCSS (i.e. `--#{$var}`)
if (iNode.value === "--" && isHashNode(iNextNode)) {
continue;
}
@@ -533,7 +533,7 @@ function printCommaSeparatedValueGroup(path, options, print) {
return group(indent(parts));
}
// Indent is not needed for import url when url is very long
// Indent is not needed for import URL when URL is very long
// and node has two groups
// when type is value-comma_group
// example @import url("verylongurl") projection,tv
+2 -2
View File
@@ -38,7 +38,7 @@ const getCssStyleTags = (property) =>
const CSS_DISPLAY_TAGS = {
...getCssStyleTags("display"),
// special cases for some css display=none elements
// special cases for some CSS display=none elements
template: "inline",
source: "block",
track: "block",
@@ -48,7 +48,7 @@ const CSS_DISPLAY_TAGS = {
// `noscript` is inline
// noscript: "inline",
// there's no css display for these elements but they behave these ways
// there's no CSS display for these elements but they behave these ways
meter: "inline-block",
progress: "inline-block",
object: "inline-block",
+1 -1
View File
@@ -46,7 +46,7 @@ async function formatAttributeValue(
shouldHugJsExpression,
) {
options = {
// strictly prefer single quote to avoid unnecessary html entity escape
// strictly prefer single quote to avoid unnecessary HTML entity escape
__isInHtmlAttribute: true,
__embeddedInHtml: true,
...options,
+1 -1
View File
@@ -42,7 +42,7 @@ function massageAstNode(original, cloned, parent) {
(parent.fullName === "img" || parent.fullName === "source")) ||
(name === "allow" && parent.fullName === "iframe") ||
name.startsWith("on") ||
// Vue attributes
// Vue.js attributes
name.startsWith("@") ||
name.startsWith(":") ||
name.startsWith(".") ||
+1 -1
View File
@@ -56,7 +56,7 @@ function parseVue(input, parseOptions) {
(node.kind === "element" && node.name.toLowerCase() === "html"),
);
// If not Vue SFC, treat as html
// If not Vue.js SFC, treat as HTML
if (isHtml) {
return parseHtml(input, HTML_PARSE_OPTIONS);
}
+1 -1
View File
@@ -41,7 +41,7 @@ const angularParser = createParser({
tokenizeAngularLetDeclaration: true,
});
// Vue
// Vue.js
const vueParser = createParser({
name: "vue",
isTagNameCaseSensitive: true,
+3 -3
View File
@@ -53,7 +53,7 @@ function shouldPreserveContent(node, options) {
return true;
}
// incomplete html in ie conditional comment
// incomplete HTML in ie conditional comment
// e.g. <!--[if lt IE 9]></div><![endif]-->
if (node.kind === "ieConditionalComment" && !node.complete) {
return true;
@@ -475,7 +475,7 @@ function hasParent(node, fn) {
}
function getNodeCssStyleDisplay(node, options) {
// Every root block in Vue SFC is a block
// Every root block in Vue.js SFC is a block
if (isVueSfcBlock(node, options)) {
return "block";
}
@@ -535,7 +535,7 @@ function getUnescapedAttributeValue(node) {
return unescapeQuoteEntities(node.value);
}
// top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
// top-level elements (excluding <template>, <style> and <script>) in Vue.js SFC are considered custom block
// See https://vue-loader.vuejs.org/spec.html for detail
const vueRootElementsSet = new Set(["template", "style", "script"]);
function isVueCustomBlock(node, options) {
+1 -1
View File
@@ -356,7 +356,7 @@ function handleMethodNameComments({
followingNode,
text,
}) {
// This is only needed for estree parsers (flow, typescript) to attach
// This is only needed for estree parsers (Flow, TypeScript) to attach
// after a method name:
// obj = { fn /*comment*/() {} };
if (
+2 -2
View File
@@ -103,7 +103,7 @@ function massageAstNode(original, cloned, parent) {
}
}
// CSS template literals in css prop
// CSS template literals in CSS prop
if (
original.type === "JSXAttribute" &&
original.name.name === "css" &&
@@ -155,7 +155,7 @@ function massageAstNode(original, cloned, parent) {
}
}
// styled-components, graphql, markdown
// styled-components, GraphQL, markdown
if (
original.type === "TaggedTemplateExpression" &&
(original.tag.type === "MemberExpression" ||
+4 -4
View File
@@ -263,13 +263,13 @@ export {
/** @internal */
babelExpression as __js_expression,
babelTSExpression as __ts_expression,
/** for vue filter */
/** for Vue.js filter */
babelExpression as __vue_expression,
/** for vue filter written in TS */
/** for Vue.js filter written in TS */
babelTSExpression as __vue_ts_expression,
/** for vue event binding to handle semicolon */
/** for Vue.js event binding to handle semicolon */
babel as __vue_event_binding,
/** for vue event binding written in TS to handle semicolon */
/** for Vue.js event binding written in TS to handle semicolon */
babelTs as __vue_ts_event_binding,
/** verify that we can print this AST */
babelEstree as __babel_estree,
+1 -1
View File
@@ -150,7 +150,7 @@ function chooseLayout(path, options, print, leftDoc, rightPropertyName) {
node.type === "ImportAttribute" ||
(rightNode.type === "CallExpression" &&
rightNode.callee.name === "require") ||
// do not put values on a separate line from the key in json
// do not put values on a separate line from the key in JSON
path.root.type === "JsonRoot"
) {
return "never-break-after-operator";
+1 -1
View File
@@ -5,7 +5,7 @@ import { printTypeAnnotationProperty } from "./type-annotation.js";
function printIndexSignature(path, options, print) {
const { node } = path;
// The typescript parser accepts multiple parameters here. If you're
// The TypeScript parser accepts multiple parameters here. If you're
// using them, it makes sense to have a trailing comma. But if you
// aren't, this is more like a computed property name than an array.
// So we leave off the trailing comma when there's just one parameter.
+1 -1
View File
@@ -75,7 +75,7 @@ function isKeySafeToQuote(node, options) {
// Angular does not support unquoted numbers in expressions.
//
// So we play it safe and only unquote numbers for the JavaScript parsers.
// (Vue supports unquoted numbers in expressions, but let’s keep it simple.)
// (Vue.js supports unquoted numbers in expressions, but let’s keep it simple.)
//
// Identifiers can be unquoted in more circumstances, though.
function isKeySafeToUnquote(node, options) {
@@ -21,7 +21,7 @@ function printVariableDeclaration(path, options, print) {
if (printed.length === 1 && !hasComment(node.declarations[0])) {
firstVariable = printed[0];
} else {
// Indent first var to comply with eslint one-var rule
// Indent first var to comply with ESLint one-var rule
firstVariable = indent(printed[0]);
}
+1 -1
View File
@@ -31,7 +31,7 @@ function iterateClassMembersPath(path, iteratee) {
}
if (node.type === "ObjectTypeAnnotation") {
// Unfortunately, things grouped together in the ast can be
// Unfortunately, things grouped together in the AST can be
// interleaved in the source code. So we need to reorder them before
// printing them.
const children = flowObjectTypeAnnotationChildrenProperties
@@ -1,4 +1,4 @@
/* The argument is a duck type of AstPath, so we can use it in comment attach and ast massage */
/* The argument is a duck type of AstPath, so we can use it in comment attach and AST massage */
function isMeaningfulEmptyStatement({ node, parent }) {
if (node?.type !== "EmptyStatement") {
return false;
@@ -1,6 +1,6 @@
import { hasSameLocStart } from "../location/index.js";
// Hack to differentiate between the following two which have the same ast
// Hack to differentiate between the following two which have the same AST
// declare function f(a): void;
// var f: (a) => void;
function isTypeAnnotationAFunction(node) {
+1 -1
View File
@@ -28,7 +28,7 @@ const languages = [
name: "JSON.stringify",
parsers: ["json-stringify"],
vscodeLanguageIds: ["json"],
extensions: [".importmap"], // .json file defaults to json instead of json-stringify
extensions: [".importmap"], // .json file defaults to `json` instead of `json-stringify`
filenames: ["package.json", "package-lock.json", "composer.json"],
})),
createLanguage(linguistLanguages.JSON, (data) => ({
+3 -3
View File
@@ -193,7 +193,7 @@ function attachComments(ast, options) {
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
// There are no nodes, let's attach it to the root of the ast
// There are no nodes, let's attach it to the root of the AST
/* c8 ignore next */
addDanglingComment(ast, comment);
}
@@ -209,7 +209,7 @@ function attachComments(ast, options) {
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
// There are no nodes, let's attach it to the root of the ast
// There are no nodes, let's attach it to the root of the AST
/* c8 ignore next */
addDanglingComment(ast, comment);
}
@@ -239,7 +239,7 @@ function attachComments(ast, options) {
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
// There are no nodes, let's attach it to the root of the ast
// There are no nodes, let's attach it to the root of the AST
/* c8 ignore next */
addDanglingComment(ast, comment);
}
+1 -1
View File
@@ -6,6 +6,6 @@ to remove the `__parsePrettierYamlConfig` export.
*/
export * from "../language-yaml/index.js";
// Exposed to parser prettier yaml config
// Exposed to parser prettier YAML config
import YAML from "yaml";
export const __parsePrettierYamlConfig = YAML.parse;
+1 -1
View File
@@ -38,7 +38,7 @@ const umdFiles = {
"prettier/plugins/yaml.js",
"prettier/plugins/flow.js",
"prettier/plugins/meriyah.js",
// These two plugins don't have umd version
// These two plugins don't have UMD version
"plugin-hermes/index.mjs",
"plugin-oxc/index.browser.mjs",
],
+1 -1
View File
@@ -29,7 +29,7 @@ function* getFiles(context) {
!file.isFile() ||
filename[0] === "." ||
filename === FORMAT_TEST_SCRIPT_FILENAME ||
// VSCode creates this file sometime https://github.com/microsoft/vscode/issues/105191
// VS Code creates this file sometime https://github.com/microsoft/vscode/issues/105191
filename === "debug.log" ||
path.extname(filename) === ".snap"
) {
@@ -1,7 +1,7 @@
import { parsing, transform } from "json-test-suite";
const SKIP = new Set([
// Prettier doesn't support other encodings than utf8
// Prettier doesn't support other encodings than UTF-8
"i_string_utf16BE_no_BOM.json",
"i_string_utf16LE_no_BOM.json",
"i_string_UTF-16LE_with_BOM.json",
@@ -1,7 +1,7 @@
import { parsing, transform } from "json-test-suite";
const SKIP = new Set([
// Prettier doesn't support other encodings than utf8
// Prettier doesn't support other encodings than UTF-8
"i_string_utf16LE_no_BOM.json",
// Maximum call stack size exceeded
@@ -479,7 +479,7 @@ test("Search from directory, not treat file as directory", async () => {
"directory/.prettierrc",
);
// Api
// API
const directory = new URL("../cli/config/config-position/", import.meta.url);
const getConfigFileByApi = async (file) => {
const configFile = await prettier.resolveConfigFile(
@@ -5,7 +5,7 @@ describe("format correctly if stdin content compatible with stdin-filepath", ()
runCli(
"cli",
["--stdin-filepath", "abc.css"],
{ input: ".name { display: none; }" }, // css
{ input: ".name { display: none; }" }, // CSS
).test({
status: 0,
});
@@ -15,7 +15,7 @@ describe("throw error if stdin content incompatible with stdin-filepath", () =>
runCli(
"cli",
["--stdin-filepath", "abc.js"],
{ input: ".name { display: none; }" }, // css
{ input: ".name { display: none; }" }, // CSS
).test({
status: "non-zero",
});
@@ -25,7 +25,7 @@ describe("gracefully handle stdin-filepath with nonexistent directory", () => {
runCli(
"cli",
["--stdin-filepath", "definitely/nonexistent/path.css"],
{ input: ".name { display: none; }" }, // css
{ input: ".name { display: none; }" }, // CSS
).test({
status: 0,
});
@@ -138,7 +138,7 @@ describe("CLI --stdin-filepath works with --config-precedence prefer-file", () =
runCli(
"cli/config-precedence/overrides",
["--stdin-filepath=abc.ts", "--no-semi", "--config-precedence=prefer-file"],
{ input: "let x: keyof Y = foo<typeof X>()" }, // typescript
{ input: "let x: keyof Y = foo<typeof X>()" }, // TypeScript
).test({
stderr: "",
status: 0,
@@ -153,7 +153,7 @@ describe("CLI --stdin-filepath works with --config-precedence file-override", ()
"--no-semi",
"--config-precedence=file-override",
],
{ input: "let x: keyof Y = foo<typeof X>()" }, // typescript
{ input: "let x: keyof Y = foo<typeof X>()" }, // TypeScript
).test({
stderr: "",
status: 0,
@@ -168,7 +168,7 @@ describe("CLI --stdin-filepath works with --config-precedence cli-override", ()
"--no-semi",
"--config-precedence=cli-override",
],
{ input: "let x: keyof Y = foo<typeof X>()" }, // typescript
{ input: "let x: keyof Y = foo<typeof X>()" }, // TypeScript
).test({
stderr: "",
status: 0,
+2 -2
View File
@@ -31,7 +31,7 @@ const config = {
favicon: "icon.png",
titleDelimiter: "·",
// Set the production url of your site here
// Set the production URL of your site here
url: packageJson.homepage,
// Set the /<baseUrl>/ pathname under which your site is served
// For GitHub pages deployment, it is often '/<projectName>/'
@@ -58,7 +58,7 @@ const config = {
onBrokenLinks: "throw",
// Even if you don't use internationalization, you can use this field to set
// useful metadata like html lang. For example, if your site is Chinese, you
// useful metadata like HTML lang. For example, if your site is Chinese, you
// may want to replace "en" with "zh-Hans".
i18n: {
defaultLocale: "en",
+1 -1
View File
@@ -6,7 +6,7 @@ export function read() {
return {};
}
// backwards support for old json encoded URIComponent
// backwards support for old JSON encoded URIComponent
const decode = hash.includes("%7B%22")
? decodeURIComponent
: LZString.decompressFromEncodedURIComponent;