diff --git a/.README/README.md b/.README/README.md index d97029ee2..0889807ea 100644 --- a/.README/README.md +++ b/.README/README.md @@ -557,6 +557,7 @@ selector). {"gitdown": "include", "file": "./rules/empty-tags.md"} {"gitdown": "include", "file": "./rules/implements-on-classes.md"} {"gitdown": "include", "file": "./rules/match-description.md"} +{"gitdown": "include", "file": "./rules/match-name.md"} {"gitdown": "include", "file": "./rules/multiline-blocks.md"} {"gitdown": "include", "file": "./rules/newline-after-description.md"} {"gitdown": "include", "file": "./rules/no-bad-blocks.md"} diff --git a/.README/rules/match-name.md b/.README/rules/match-name.md new file mode 100644 index 000000000..be1a6a13c --- /dev/null +++ b/.README/rules/match-name.md @@ -0,0 +1,61 @@ +### `match-name` + +Reports the name portion of a JSDoc tag if matching or not matching +a given regular expression. + +Note that some tags do not possess names and anything appearing to be a +name will actually be part of the description (e.g., for +`@returns {type} notAName`). If you are defining your own tags, see the +`structuredTags` setting (if `name: false`, this rule will not apply to +that tag). + +#### Options + +A single options object with the following properties: + +##### `match` + +`match` is a required option containing an array of objects which determine +the conditions whereby a name is reported as being problematic. + +These objects can have any combination of the following groups of optional +properties, all of which act to confine one another: + +- `tags` - This array should include tag names or `*` to indicate the + match will apply for all tags (except as confined by any context + properties). If `*` is not used, then these rules will only apply to + the specified tags. If `tags` is omitted, then `*` is assumed. + +- `allowName` - Indicates which names are allowed for the given tag (or `*`). + Accepts a string regular expression (optionally wrapped between two + `/` delimiters followed by optional flags) used to match the name. +- `disallowName` - As with `allowName` but indicates names that are not + allowed. +- `replacement` - If `disallowName` is supplied and this value is present, it + will replace the matched `disallowName` text. + +- `context` - AST to confine the allowing or disallowing to jsdoc blocks + associated with a particular context. See the + ["AST and Selectors"](#eslint-plugin-jsdoc-advanced-ast-and-selectors) + section of our README for more on the expected format. +- `comment` - As with `context` but AST for the JSDoc block comment and types + +- `message` - An optional custom message to use when there is a match. + +Note that `comment`, even if targeting a specific tag, is used to match the +whole block. So if a `comment` finds its specific tag, it may still apply +fixes found by the likes of `disallowName` even when a different tag has the +disallowed name. An alternative is to ensure that `comment` finds the specific +tag of the desired tag and/or name and no `disallowName` (or `allowName`) is +supplied. In such a case, only one error will be reported, but no fixer will +be applied, however. + +||| +|---|---| +|Context|everywhere| +|Tags|(The tags specifie by `tags`, including any tag if `*` is set)| +|Recommended|false| +|Settings|`structuredTags`| +|Options|`match`| + + diff --git a/README.md b/README.md index 7dd69b2c6..c1bda6c71 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ JSDoc linting rules for ESLint. * [`empty-tags`](#eslint-plugin-jsdoc-rules-empty-tags) * [`implements-on-classes`](#eslint-plugin-jsdoc-rules-implements-on-classes) * [`match-description`](#eslint-plugin-jsdoc-rules-match-description) + * [`match-name`](#eslint-plugin-jsdoc-rules-match-name) * [`multiline-blocks`](#eslint-plugin-jsdoc-rules-multiline-blocks) * [`newline-after-description`](#eslint-plugin-jsdoc-rules-newline-after-description) * [`no-bad-blocks`](#eslint-plugin-jsdoc-rules-no-bad-blocks) @@ -7149,6 +7150,217 @@ function quux (foo) { ```` + +### match-name + +Reports the name portion of a JSDoc tag if matching or not matching +a given regular expression. + +Note that some tags do not possess names and anything appearing to be a +name will actually be part of the description (e.g., for +`@returns {type} notAName`). If you are defining your own tags, see the +`structuredTags` setting (if `name: false`, this rule will not apply to +that tag). + + +#### Options + +A single options object with the following properties: + + +##### match + +`match` is a required option containing an array of objects which determine +the conditions whereby a name is reported as being problematic. + +These objects can have any combination of the following groups of optional +properties, all of which act to confine one another: + +- `tags` - This array should include tag names or `*` to indicate the + match will apply for all tags (except as confined by any context + properties). If `*` is not used, then these rules will only apply to + the specified tags. If `tags` is omitted, then `*` is assumed. + +- `allowName` - Indicates which names are allowed for the given tag (or `*`). + Accepts a string regular expression (optionally wrapped between two + `/` delimiters followed by optional flags) used to match the name. +- `disallowName` - As with `allowName` but indicates names that are not + allowed. +- `replacement` - If `disallowName` is supplied and this value is present, it + will replace the matched `disallowName` text. + +- `context` - AST to confine the allowing or disallowing to jsdoc blocks + associated with a particular context. See the + ["AST and Selectors"](#eslint-plugin-jsdoc-advanced-ast-and-selectors) + section of our README for more on the expected format. +- `comment` - As with `context` but AST for the JSDoc block comment and types + +- `message` - An optional custom message to use when there is a match. + +Note that `comment`, even if targeting a specific tag, is used to match the +whole block. So if a `comment` finds its specific tag, it may still apply +fixes found by the likes of `disallowName` even when a different tag has the +disallowed name. An alternative is to ensure that `comment` finds the specific +tag of the desired tag and/or name and no `disallowName` (or `allowName`) is +supplied. In such a case, only one error will be reported, but no fixer will +be applied, however. + +||| +|---|---| +|Context|everywhere| +|Tags|(The tags specifie by `tags`, including any tag if `*` is set)| +|Recommended|false| +|Settings|`structuredTags`| +|Options|`match`| + +The following patterns are considered problems: + +````js +/** + * @param opt_a + * @param opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i"}]}] +// Message: Only allowing names not matching `/^opt_/i` but found "opt_a". + +/** + * @param opt_a + * @param opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","replacement":""}]}] +// Message: Only allowing names not matching `/^opt_/i` but found "opt_a". + +/** + * @param a + * @param opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"allowName":"/^[a-z]+$/i"}]}] +// Message: Only allowing names matching `/^[a-z]+$/i` but found "opt_b". + +/** + * @param arg + * @param opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"allowName":"/^[a-z]+$/i","disallowName":"/^arg/i"}]}] +// Message: Only allowing names not matching `/^arg/i` but found "arg". + +/** + * @param opt_a + * @param arg + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^arg$/i"},{"disallowName":"/^opt_/i"}]}] +// Message: Only allowing names not matching `/^opt_/i` but found "opt_a". + +/** + * @property opt_a + * @param opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","tags":["param"]}]}] +// Message: Only allowing names not matching `/^opt_/i` but found "opt_b". + +/** + * @someTag opt_a + * @param opt_b + */ +// Settings: {"jsdoc":{"structuredTags":{"someTag":{"name":"namepath-defining"}}}} +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","tags":["param"]}]}] +// Message: Only allowing names not matching `/^opt_/i` but found "opt_b". + +/** + * @property opt_a + * @param opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","tags":["*"]}]}] +// Message: Only allowing names not matching `/^opt_/i` but found "opt_a". + +/** + * @param opt_a + * @param opt_b + */ +function quux () { +} +// "jsdoc/match-name": ["error"|"warn", {"match":[{"context":"FunctionDeclaration","disallowName":"/^opt_/i"}]}] +// Message: Only allowing names not matching `/^opt_/i` but found "opt_a". + +/** + * @property opt_a + * @param {Bar|Foo} opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"comment":"JSDocBlock:has(JSDocTag[tag=\"param\"][name=/opt_/] > JSDocTypeUnion:has(JsdocTypeName[value=\"Bar\"]:nth-child(1)))"}]}] +// Message: Prohibited context for "opt_a". + +/** + * @property opt_a + * @param {Bar|Foo} opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"comment":"JSDocBlock:has(JSDocTag[tag=\"param\"][name=/opt_/] > JSDocTypeUnion:has(JsdocTypeName[value=\"Bar\"]:nth-child(1)))","message":"Don't use `opt_` prefixes with Bar|..."}]}] +// Message: Don't use `opt_` prefixes with Bar|... + +/** + * @param opt_a + * @param opt_b + */ +function quux () {} +// "jsdoc/match-name": ["error"|"warn", ] +// Message: Rule `no-restricted-syntax` is missing a `match` option. +```` + +The following patterns are not considered problems: + +````js +/** + * @param opt_a + * @param opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^arg/i"}]}] + +/** + * @param a + * @param opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"allowName":"/^[a-z_]+$/i"}]}] + +/** + * @param someArg + * @param anotherArg + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"allowName":"/^[a-z]+$/i","disallowName":"/^arg/i"}]}] + +/** + * @param elem1 + * @param elem2 + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^arg$/i"},{"disallowName":"/^opt_/i"}]}] + +/** + * @someTag opt_a + * @param opt_b + */ +// Settings: {"jsdoc":{"structuredTags":{"someTag":{"name":"namepath-defining"}}}} +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","tags":["property"]}]}] + +/** + * @property opt_a + * @param opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^arg/i","tags":["*"]}]}] + +/** + * @param opt_a + * @param opt_b + */ +class A { +} +// "jsdoc/match-name": ["error"|"warn", {"match":[{"context":"FunctionDeclaration","disallowName":"/^opt_/i"}]}] + +/** + * @property opt_a + * @param {Foo|Bar} opt_b + */ +// "jsdoc/match-name": ["error"|"warn", {"match":[{"comment":"JSDocBlock > JSDocTag[tag=\"param\"] > JSDocTypeUnion[left.name=\"Bar\"]","disallowName":"/^opt_/i"}]}] +```` + + ### multiline-blocks @@ -7161,12 +7373,12 @@ all jsdoc blocks! Also allows for preventing text at the very beginning or very end of blocks. - + #### Options A single options object with the following properties. - + ##### noZeroLineText (defaults to true) For multiline blocks, any non-whitespace text immediately after the `/**` and @@ -7174,7 +7386,7 @@ space will be reported. (Text after a newline is not reported.) `noMultilineBlocks` will have priority over this rule if it applies. - + ##### noFinalLineText (defaults to true) For multiline blocks, any non-whitespace text preceding the `*/` on the final @@ -7182,13 +7394,13 @@ line will be reported. (Text preceding a newline is not reported.) `noMultilineBlocks` will have priority over this rule if it applies. - + ##### noSingleLineBlocks (defaults to false) If this is `true`, any single line blocks will be reported, except those which are whitelisted in `singleLineTags`. - + ##### singleLineTags (defaults to ['lends', 'type']) An array of tags which can nevertheless be allowed as single line blocks when @@ -7197,14 +7409,14 @@ cause all single line blocks to be reported. If `'*'` is present, then the presence of a tag will allow single line blocks (but not if a tag is missing). - + ##### noMultilineBlocks (defaults to false) Requires that jsdoc blocks are restricted to single lines only unless impacted by the options `minimumLengthForMultiline`, `multilineTags`, or `allowMultipleTags`. - + ##### minimumLengthForMultiline (defaults to not being in effect) If `noMultilineBlocks` is set with this numeric option, multiline blocks will @@ -7213,7 +7425,7 @@ be permitted if containing at least the given amount of text. If not set, multiline blocks will not be permitted regardless of length unless a relevant tag is present and `multilineTags` is set. - + ##### multilineTags (defaults to ['*']) If `noMultilineBlocks` is set with this option, multiline blocks may be allowed @@ -7229,7 +7441,7 @@ such a tag will cause multiline blocks to be allowed. You may set this to an empty array to prevent any tag from permitting multiple lines. - + ##### allowMultipleTags (defaults to true) If `noMultilineBlocks` is set to `true` with this option and multiple tags are @@ -7521,7 +7733,7 @@ The following patterns are not considered problems: Enforces a consistent padding of the block description. - + #### Options This rule allows one optional string argument. If it is `"always"` then a @@ -7764,12 +7976,12 @@ asterisks, but which appear to be intended as jsdoc blocks due to the presence of whitespace followed by whitespace or asterisks, and an at-sign (`@`) and some non-whitespace (as with a jsdoc block tag). - + #### Options Takes an optional options object with the following. - + ##### ignore An array of directives that will not be reported if present at the beginning of @@ -7778,7 +7990,7 @@ a multi-comment block and at-sign `/* @`. Defaults to `['ts-check', 'ts-expect-error', 'ts-ignore', 'ts-nocheck']` (some directives [used by TypeScript](https://www.typescriptlang.org/docs/handbook/intro-to-js-ts.html#ts-check)). - + ##### preventAllMultiAsteriskBlocks A boolean (defaulting to `false`) which if `true` will prevent all @@ -7914,10 +8126,10 @@ tag is attached). Unless your `@default` is on a function, you will need to set `contexts` to an appropriate context, including, if you wish, "any". - + #### Options - + ##### noOptionalParamNames Set this to `true` to report the presence of optional parameters. May be @@ -7926,7 +8138,7 @@ the presence of ES6 default parameters (bearing in mind that such "defaults" are only applied when the supplied value is missing or `undefined` but not for `null` or other "falsey" values). - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -8108,10 +8320,10 @@ which are not adequate to satisfy a condition, e.g., not report if there were only a function declaration of the name "ignoreMe" (though it would report by function declarations of other names). - + #### Options - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -8273,10 +8485,10 @@ Note that if you wish to prevent multiple asterisks at the very beginning of the jsdoc block, you should use `no-bad-blocks` (as that is not proper jsdoc and that rule is for catching blocks which only seem like jsdoc). - + #### Options - + ##### preventAtMiddleLines (defaults to true) Prevent the likes of this: @@ -8288,7 +8500,7 @@ Prevent the likes of this: */ ``` - + ##### preventAtEnd (defaults to true) Prevent the likes of this: @@ -8474,10 +8686,10 @@ structures, (whether or not you add a specific `comment` condition). Note that if your parser supports comment AST (as [jsdoc-eslint-parser/](https://github.com/brettz9/jsdoc-eslint-parser/) is designed to do), you can just use ESLint's rule. - + #### Options - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -8636,10 +8848,10 @@ This rule reports types being used on `@param` or `@returns`. The rule is intended to prevent the indication of types on tags where the type information would be redundant with TypeScript. - + #### Options - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -8809,7 +9021,7 @@ reporting on use of that namepath elsewhere) and/or that a tag's `type` is `false` (and should not be checked for types). If the `type` is an array, that array's items will be considered as defined for the purposes of that tag. - + #### Options An option object may have the following key: @@ -9372,7 +9584,7 @@ function quux(foo) { Requires that each JSDoc line starts with an `*`. - + #### Options This rule allows an optional string argument. If it is `"always"` then a @@ -9383,7 +9595,7 @@ and use the `tags` option to apply to specific tags only. After the string option, one may add an object with the following. - + ##### tags If you want different values to apply to specific tags, you may use @@ -9657,10 +9869,10 @@ Requires that block description, explicit `@description`, and * Periods after items within the `abbreviations` option array are not treated as sentence endings. - + #### Options - + ##### tags If you want additional tags to be checked for their descriptions, you may @@ -9684,14 +9896,14 @@ its "description" (e.g., for `@returns {someType} some description`, the description is `some description` while for `@some-tag xyz`, the description is `xyz`). - + ##### abbreviations You can provide an `abbreviations` options array to avoid such strings of text being treated as sentence endings when followed by dots. The `.` is not necessary at the end of the array items. - + ##### newlineBeforeCapsAssumesBadSentenceEnd When `false` (the new default), we will not assume capital letters after @@ -10362,7 +10574,7 @@ Requires that all functions have a description. is `"tag"`) must have a non-empty description that explains the purpose of the method. - + #### Options An options object may have any of the following properties: @@ -10912,12 +11124,12 @@ Requires that all functions have examples. * Every example tag must have a non-empty description that explains the method's usage. - + #### Options This rule has an object option. - + ##### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document @@ -10926,13 +11138,13 @@ block avoids the need for an `@example`. Defaults to an array with so be sure to add back `inheritdoc` if you wish its presence to cause exemption of the rule. - + ##### exemptNoArguments Boolean to indicate that no-argument functions should not be reported for missing `@example` declarations. - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -10944,18 +11156,18 @@ want the rule to apply to any jsdoc block throughout your files. See the ["AST and Selectors"](#eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our README for more on the expected format. - + ##### checkConstructors A value indicating whether `constructor`s should be checked. Defaults to `true`. - + ##### checkGetters A value indicating whether getters should be checked. Defaults to `false`. - + ##### checkSetters A value indicating whether setters should be checked. Defaults to `false`. @@ -11247,10 +11459,10 @@ Checks that: as being when the overview tag is not preceded by anything other than a comment. - + #### Options - + ##### tags The keys of this object are tag names, and the values are configuration @@ -11533,7 +11745,7 @@ function quux () { Requires (or disallows) a hyphen before the `@param` description. - + #### Options This rule takes one optional string argument and an optional options object. @@ -11764,12 +11976,12 @@ function main(argv) { Checks for presence of jsdoc comments, on class declarations as well as functions. - + #### Options Accepts one optional options object with the following optional keys. - + ##### publicOnly This option will insist that missing jsdoc blocks are only reported for @@ -11785,7 +11997,7 @@ otherwise noted): - `cjs` - CommonJS exports are checked for JSDoc comments (Defaults to `true`) - `window` - Window global exports are checked for JSDoc comments - + ##### require An object with the following optional boolean keys which all default to @@ -11798,7 +12010,7 @@ An object with the following optional boolean keys which all default to - `FunctionExpression` - `MethodDefinition` - + ##### contexts Set this to an array of strings or objects representing the additional AST @@ -11814,7 +12026,7 @@ if you are specifying a more precise form in `contexts` (e.g., `MethodDefinition See the ["AST and Selectors"](#eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our README for more on the expected format. - + ##### exemptEmptyConstructors Default: true @@ -11823,7 +12035,7 @@ When `true`, the rule will not report missing jsdoc blocks above constructors with no parameters or return values (this is enabled by default as the class name or description should be seen as sufficient to convey intent). - + ##### exemptEmptyFunctions Default: false. @@ -11832,14 +12044,14 @@ When `true`, the rule will not report missing jsdoc blocks above functions/methods with no parameters or return values (intended where function/method names are sufficient for themselves as documentation). - + ##### checkConstructors A value indicating whether `constructor`s should be checked. Defaults to `true`. When `true`, `exemptEmptyConstructors` may still avoid reporting when no parameters or return values are found. - + ##### checkGetters A value indicating whether getters should be checked. Besides setting as a @@ -11848,7 +12060,7 @@ getters should be checked but only when there is no setter. This may be useful if one only wishes documentation on one of the two accessors. Defaults to `false`. - + ##### checkSetters A value indicating whether setters should be checked. Besides setting as a @@ -11857,7 +12069,7 @@ setters should be checked but only when there is no getter. This may be useful if one only wishes documentation on one of the two accessors. Defaults to `false`. - + ##### enableFixer A boolean on whether to enable the fixer (which adds an empty jsdoc block). @@ -13386,10 +13598,10 @@ export class User { Requires that each `@param` tag has a `description` value. - + #### Options - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -13510,10 +13722,10 @@ Requires that all function parameters have names. > > [JSDoc](https://jsdoc.app/tags-param.html#overview) - + #### Options - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -13646,10 +13858,10 @@ function example(cb) { Requires that each `@param` tag has a `type` value. - + #### Options - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -13947,30 +14159,30 @@ other properties, so in looking at the docs alone without looking at the function signature, it may appear that there is an actual property named `extra`. - + #### Options An options object accepts the following optional properties: - + ##### enableFixer Whether to enable the fixer. Defaults to `true`. - + ##### enableRootFixer Whether to enable the auto-adding of incrementing roots (see the "Fixer" section). Defaults to `true`. Has no effect if `enableFixer` is set to `false`. - + ##### enableRestElementFixer Whether to enable the rest element fixer (see "Rest Element (`RestElement`) insertions"). Defaults to `true`. - + ##### checkRestProperty If set to `true`, will report (and add fixer insertions) for missing rest @@ -14024,13 +14236,13 @@ function quux ({num, ...extra}) { } ``` - + ##### autoIncrementBase Numeric to indicate the number at which to begin auto-incrementing roots. Defaults to `0`. - + ##### unnamedRootBase An array of root names to use in the fixer when roots are missing. Defaults @@ -14056,7 +14268,7 @@ function quux ({foo}, [bar], {baz}) { */ ``` - + ##### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document block @@ -14065,7 +14277,7 @@ avoids the need for a `@param`. Defaults to an array with so be sure to add back `inheritdoc` if you wish its presence to cause exemption of the rule. - + ##### checkTypesPattern When one specifies a type, unless it is of a generic type, like `object` @@ -14100,7 +14312,7 @@ You could set this regular expression to a more expansive list, or you could restrict it such that even types matching those strings would not need destructuring. - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -14112,28 +14324,28 @@ which are checked. See the ["AST and Selectors"](#eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our README for more on the expected format. - + ##### checkConstructors A value indicating whether `constructor`s should be checked. Defaults to `true`. - + ##### checkGetters A value indicating whether getters should be checked. Defaults to `false`. - + ##### checkSetters A value indicating whether setters should be checked. Defaults to `false`. - + ##### checkDestructured Whether to require destructured properties. Defaults to `true`. - + ##### checkDestructuredRoots Whether to check the existence of a corresponding `@param` for root objects @@ -14146,7 +14358,7 @@ implied to be `false` (i.e., the inside of the roots will not be checked either, e.g., it will also not complain if `a` or `b` do not have their own documentation). Defaults to `true`. - + ##### useDefaultObjectProperties Set to `true` if you wish to expect documentation of properties on objects @@ -15749,7 +15961,7 @@ is set to `false` no non-`undefined` returned or resolved value is found. Will also report if multiple `@returns` tags are present. - + #### Options - `exemptAsync` - By default, functions which return a `Promise` that are not @@ -16276,10 +16488,10 @@ Requires that the `@returns` tag has a `description` value. The error will not be reported if the return value is `void` or `undefined` or if it is `Promise` or `Promise`. - + #### Options - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -16432,10 +16644,10 @@ function quux () { Requires that `@returns` tag has `type` value. - + #### Options - + ##### contexts Set this to an array of strings representing the AST context (or an object with @@ -16555,7 +16767,7 @@ Requires that returns are documented. Will also report if multiple `@returns` tags are present. - + #### Options - `checkConstructors` - A value indicating whether `constructor`s should @@ -17576,7 +17788,7 @@ async function foo() { Requires that throw statements are documented. - + #### Options - `exemptedBy` - Array of tags (e.g., `['type']`) whose presence on the @@ -17852,7 +18064,7 @@ Will also report if multiple `@yields` tags are present. See the `next`, `forceRequireNext`, and `nextWithGeneratorTag` options for an option to expect a non-standard `@next` tag. - + #### Options - `exemptedBy` - Array of tags (e.g., `['type']`) whose presence on the @@ -18662,7 +18874,7 @@ function bodies. Will also report if multiple `@yields` tags are present. - + #### Options - `checkGeneratorsOnly` - Avoids checking the function body and merely insists @@ -19140,7 +19352,7 @@ function * quux (foo) { Enforces lines (or no lines) between tags. - + #### Options The first option is a single string set to "always", "never", or "any" @@ -19151,18 +19363,18 @@ for particular tags). The second option is an object with the following optional properties. - + ##### count (defaults to 1) Use with "always" to indicate the number of lines to require be present. - + ##### noEndLines (defaults to false) Use with "always" to indicate the normal lines to be added after tags should not be added after the final tag. - + ##### tags (default to empty object) Overrides the default behavior depending on specific tags. @@ -19543,7 +19755,7 @@ for valid types (based on the tag's `type` value), and either portion checked for presence (based on `false` `name` or `type` values or their `required` value). See the setting for more details. - + #### Options - `allowEmptyNamepaths` (default: true) - Set to `false` to bulk disallow diff --git a/src/index.js b/src/index.js index e842135ad..d5ab39a82 100644 --- a/src/index.js +++ b/src/index.js @@ -12,6 +12,7 @@ import checkValues from './rules/checkValues'; import emptyTags from './rules/emptyTags'; import implementsOnClasses from './rules/implementsOnClasses'; import matchDescription from './rules/matchDescription'; +import matchName from './rules/matchName'; import multilineBlocks from './rules/multilineBlocks'; import newlineAfterDescription from './rules/newlineAfterDescription'; import noBadBlocks from './rules/noBadBlocks'; @@ -65,6 +66,7 @@ export default { 'jsdoc/empty-tags': 'warn', 'jsdoc/implements-on-classes': 'warn', 'jsdoc/match-description': 'off', + 'jsdoc/match-name': 'off', 'jsdoc/multiline-blocks': 'warn', 'jsdoc/newline-after-description': 'warn', 'jsdoc/no-bad-blocks': 'off', @@ -116,6 +118,7 @@ export default { 'empty-tags': emptyTags, 'implements-on-classes': implementsOnClasses, 'match-description': matchDescription, + 'match-name': matchName, 'multiline-blocks': multilineBlocks, 'newline-after-description': newlineAfterDescription, 'no-bad-blocks': noBadBlocks, diff --git a/src/iterateJsdoc.js b/src/iterateJsdoc.js index a5c6445d3..8500b3168 100644 --- a/src/iterateJsdoc.js +++ b/src/iterateJsdoc.js @@ -100,13 +100,13 @@ const getUtils = ( return commentStringify(specRewire ? rewireSpecs(tagBlock) : tagBlock); }; - utils.reportJSDoc = (msg, tag, handler, specRewire) => { + utils.reportJSDoc = (msg, tag, handler, specRewire, data) => { report(msg, handler ? (fixer) => { handler(); const replacement = utils.stringify(jsdoc, specRewire); return fixer.replaceText(jsdocNode, replacement); - } : null, tag); + } : null, tag, data); }; utils.getRegexFromString = (str, requiredFlags) => { @@ -681,7 +681,7 @@ const iterate = ( info, indent, jsdoc, ruleConfig, context, lines, jsdocNode, node, settings, - sourceCode, iterator, state, lastComment, iteratingAll, + sourceCode, iterator, state, iteratingAll, ) => { const report = makeReport(context, jsdocNode); @@ -746,8 +746,9 @@ const getIndentAndJSDoc = function (lines, jsdocNode) { * @param {JsdocVisitor} iterator * @param {{meta: any}} ruleConfig * @param contexts + * @param {boolean} additiveContexts */ -const iterateAllJsdocs = (iterator, ruleConfig, contexts) => { +const iterateAllJsdocs = (iterator, ruleConfig, contexts, additiveContexts) => { const trackedJsdocs = []; let handler; @@ -766,21 +767,51 @@ const iterateAllJsdocs = (iterator, ruleConfig, contexts) => { lines, jsdocNode, ); + if (additiveContexts) { + contexts.forEach(({comment}, idx) => { + if (comment && handler(comment, jsdoc) === false) { + return; + } + iterate( + { + comment, + lastIndex: idx, + selector: node?.type, + }, + indent, jsdoc, + ruleConfig, context, lines, jsdocNode, node, + settings, sourceCode, iterator, + state, true, + ); + }); + + return; + } + let lastComment; - if (contexts && contexts.every(({comment}) => { + let lastIndex; + if (contexts && contexts.every(({comment}, idx) => { lastComment = comment; + lastIndex = idx; - return handler(comment, jsdoc) === false; + return comment && handler(comment, jsdoc) === false; })) { return; } iterate( - lastComment ? {comment: lastComment, selector: node?.type} : null, + lastComment ? { + comment: lastComment, + lastIndex, + selector: node?.type, + } : { + lastIndex, + selector: node?.type, + }, indent, jsdoc, ruleConfig, context, lines, jsdocNode, node, settings, sourceCode, iterator, - state, lastComment, true, + state, true, ); }); if (lastCall && ruleConfig.exit) { @@ -931,8 +962,10 @@ export default function iterateJsdoc (iterator, ruleConfig) { } let contexts; - if (ruleConfig.contextDefaults || ruleConfig.contextSelected) { - contexts = jsdocUtils.enforcedContexts(context, ruleConfig.contextDefaults); + if (ruleConfig.contextDefaults || ruleConfig.contextSelected || ruleConfig.matchContext) { + contexts = ruleConfig.matchContext && context.options[0]?.match ? + context.options[0].match : + jsdocUtils.enforcedContexts(context, ruleConfig.contextDefaults); if (contexts) { contexts = contexts.map((obj) => { @@ -950,7 +983,7 @@ export default function iterateJsdoc (iterator, ruleConfig) { }); if (hasPlainAny || hasObjectAny) { return iterateAllJsdocs( - iterator, ruleConfig, hasObjectAny ? contexts : null, + iterator, ruleConfig, hasObjectAny ? contexts : null, ruleConfig.matchContext, ).create(context); } } @@ -988,7 +1021,9 @@ export default function iterateJsdoc (iterator, ruleConfig) { let contextObject = {}; - if (contexts && (ruleConfig.contextDefaults || ruleConfig.contextSelected)) { + if (contexts && ( + ruleConfig.contextDefaults || ruleConfig.contextSelected || ruleConfig.matchContext + )) { contextObject = jsdocUtils.getContextObject( contexts, checkJsdoc, diff --git a/src/jsdocUtils.js b/src/jsdocUtils.js index 0acde7c70..8ddb714d1 100644 --- a/src/jsdocUtils.js +++ b/src/jsdocUtils.js @@ -1093,9 +1093,10 @@ const enforcedContexts = (context, defaultContexts) => { const getContextObject = (contexts, checkJsdoc, handler) => { const properties = {}; - contexts.forEach((prop) => { + contexts.forEach((prop, idx) => { if (typeof prop === 'object') { const selInfo = { + lastIndex: idx, selector: prop.context, }; if (prop.comment) { @@ -1110,6 +1111,7 @@ const getContextObject = (contexts, checkJsdoc, handler) => { } } else { const selInfo = { + lastIndex: idx, selector: prop, }; properties[prop] = checkJsdoc.bind(null, selInfo, null); diff --git a/src/rules/matchName.js b/src/rules/matchName.js new file mode 100644 index 000000000..07e232955 --- /dev/null +++ b/src/rules/matchName.js @@ -0,0 +1,130 @@ +import iterateJsdoc from '../iterateJsdoc'; + +export default iterateJsdoc(({ + context, + jsdoc, + report, + info: {lastIndex}, + utils, +}) => { + const {match} = context.options[0] || {}; + if (!match) { + report('Rule `no-restricted-syntax` is missing a `match` option.'); + + return; + } + + const { + allowName, + disallowName, + replacement, + tags = ['*'], + } = match[lastIndex]; + + const allowNameRegex = allowName && utils.getRegexFromString(allowName); + const disallowNameRegex = disallowName && utils.getRegexFromString(disallowName); + + let applicableTags = jsdoc.tags; + if (!tags.includes('*')) { + applicableTags = utils.getPresentTags(tags); + } + + let reported = false; + applicableTags.forEach((tag) => { + const allowed = !allowNameRegex || allowNameRegex.test(tag.name); + const disallowed = disallowNameRegex && disallowNameRegex.test(tag.name); + const hasRegex = allowNameRegex || disallowNameRegex; + if (hasRegex && allowed && !disallowed) { + return; + } + if (!hasRegex && reported) { + return; + } + + const fixer = () => { + tag.source[0].tokens.name = tag.source[0].tokens.name.replace( + disallowNameRegex, replacement, + ); + }; + + let {message} = match[lastIndex]; + if (!message) { + if (hasRegex) { + message = disallowed ? + `Only allowing names not matching \`${disallowNameRegex}\` but found "${tag.name}".` : + `Only allowing names matching \`${allowNameRegex}\` but found "${tag.name}".`; + } else { + message = `Prohibited context for "${tag.name}".`; + } + } + + utils.reportJSDoc( + message, + hasRegex ? tag : null, + + // We could match up + disallowNameRegex && replacement !== undefined ? + fixer : + null, + false, + { + // Could also supply `context`, `comment`, `tags` + allowName, + disallowName, + name: tag.name, + }, + ); + if (!hasRegex) { + reported = true; + } + }); +}, { + matchContext: true, + meta: { + docs: { + description: 'Reports the name portion of a JSDoc tag if matching or not matching a given regular expression.', + url: 'https://github.com/gajus/eslint-plugin-jsdoc#eslint-plugin-jsdoc-rules-match-name', + }, + fixable: 'code', + schema: [ + { + additionalProperies: false, + properties: { + match: { + additionalProperies: false, + items: { + properties: { + allowName: { + type: 'string', + }, + comment: { + type: 'string', + }, + context: { + type: 'string', + }, + disallowName: { + type: 'string', + }, + message: { + type: 'string', + }, + tags: { + items: { + type: 'string', + }, + type: 'array', + }, + }, + type: 'object', + }, + type: 'array', + }, + }, + required: ['match'], + type: 'object', + }, + ], + type: 'suggestion', + }, +}); diff --git a/test/rules/assertions/matchName.js b/test/rules/assertions/matchName.js new file mode 100644 index 000000000..2e241343e --- /dev/null +++ b/test/rules/assertions/matchName.js @@ -0,0 +1,418 @@ +export default { + invalid: [ + { + code: ` + /** + * @param opt_a + * @param opt_b + */ + `, + errors: [{ + line: 3, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_a".', + }, { + line: 4, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_b".', + }], + options: [{ + match: [ + { + disallowName: '/^opt_/i', + }, + ], + }], + }, + { + code: ` + /** + * @param opt_a + * @param opt_b + */ + `, + errors: [{ + line: 3, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_a".', + }, { + line: 4, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_b".', + }], + options: [{ + match: [ + { + disallowName: '/^opt_/i', + replacement: '', + }, + ], + }], + output: ` + /** + * @param a + * @param opt_b + */ + `, + }, + { + code: ` + /** + * @param a + * @param opt_b + */ + `, + errors: [{ + line: 4, + message: 'Only allowing names matching `/^[a-z]+$/i` but ' + + 'found "opt_b".', + }], + options: [{ + match: [ + { + allowName: '/^[a-z]+$/i', + }, + ], + }], + }, + { + code: ` + /** + * @param arg + * @param opt_b + */ + `, + errors: [{ + line: 3, + message: 'Only allowing names not matching `/^arg/i` but ' + + 'found "arg".', + }, { + line: 4, + message: 'Only allowing names matching `/^[a-z]+$/i` but ' + + 'found "opt_b".', + }], + options: [{ + match: [ + { + allowName: '/^[a-z]+$/i', + disallowName: '/^arg/i', + }, + ], + }], + }, + { + code: ` + /** + * @param opt_a + * @param arg + */ + `, + errors: [{ + line: 3, + message: 'Only allowing names not matching `/^opt_/i` but ' + + 'found "opt_a".', + }, { + line: 4, + message: 'Only allowing names not matching `/^arg$/i` but ' + + 'found "arg".', + }], + options: [{ + match: [ + { + disallowName: '/^arg$/i', + }, + { + disallowName: '/^opt_/i', + }, + ], + }], + }, + { + code: ` + /** + * @property opt_a + * @param opt_b + */ + `, + errors: [{ + line: 4, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_b".', + }], + options: [{ + match: [ + { + disallowName: '/^opt_/i', + tags: ['param'], + }, + ], + }], + }, + { + code: ` + /** + * @someTag opt_a + * @param opt_b + */ + `, + errors: [{ + line: 4, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_b".', + }], + options: [{ + match: [ + { + disallowName: '/^opt_/i', + tags: ['param'], + }, + ], + }], + settings: { + jsdoc: { + structuredTags: { + someTag: { + name: 'namepath-defining', + }, + }, + }, + }, + }, + { + code: ` + /** + * @property opt_a + * @param opt_b + */ + `, + errors: [{ + line: 3, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_a".', + }, { + line: 4, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_b".', + }], + options: [{ + match: [ + { + disallowName: '/^opt_/i', + tags: ['*'], + }, + ], + }], + }, + { + code: ` + /** + * @param opt_a + * @param opt_b + */ + function quux () { + } + `, + errors: [{ + line: 3, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_a".', + }, { + line: 4, + message: 'Only allowing names not matching `/^opt_/i` but found "opt_b".', + }], + options: [{ + match: [ + { + context: 'FunctionDeclaration', + disallowName: '/^opt_/i', + }, + ], + }], + }, + { + code: ` + /** + * @property opt_a + * @param {Bar|Foo} opt_b + */ + `, + errors: [{ + line: 2, + message: 'Prohibited context for "opt_a".', + }], + options: [{ + match: [ + { + comment: 'JSDocBlock:has(JSDocTag[tag="param"][name=/opt_/] > JSDocTypeUnion:has(JsdocTypeName[value="Bar"]:nth-child(1)))', + }, + ], + }], + }, + { + code: ` + /** + * @property opt_a + * @param {Bar|Foo} opt_b + */ + `, + errors: [{ + line: 2, + message: 'Don\'t use `opt_` prefixes with Bar|...', + }], + options: [{ + match: [ + { + comment: 'JSDocBlock:has(JSDocTag[tag="param"][name=/opt_/] > JSDocTypeUnion:has(JsdocTypeName[value="Bar"]:nth-child(1)))', + message: 'Don\'t use `opt_` prefixes with Bar|...', + }, + ], + }], + }, + { + code: ` + /** + * @param opt_a + * @param opt_b + */ + function quux () {} + `, + errors: [{ + line: 2, + message: 'Rule `no-restricted-syntax` is missing a `match` option.', + }], + options: [], + }, + ], + valid: [ + { + code: ` + /** + * @param opt_a + * @param opt_b + */ + `, + options: [{ + match: [ + { + disallowName: '/^arg/i', + }, + ], + }], + }, + { + code: ` + /** + * @param a + * @param opt_b + */ + `, + options: [{ + match: [ + { + allowName: '/^[a-z_]+$/i', + }, + ], + }], + }, + { + code: ` + /** + * @param someArg + * @param anotherArg + */ + `, + options: [{ + match: [ + { + allowName: '/^[a-z]+$/i', + disallowName: '/^arg/i', + }, + ], + }], + }, + { + code: ` + /** + * @param elem1 + * @param elem2 + */ + `, + options: [{ + match: [ + { + disallowName: '/^arg$/i', + }, + { + disallowName: '/^opt_/i', + }, + ], + }], + }, + { + code: ` + /** + * @someTag opt_a + * @param opt_b + */ + `, + options: [{ + match: [ + { + disallowName: '/^opt_/i', + tags: ['property'], + }, + ], + }], + settings: { + jsdoc: { + structuredTags: { + someTag: { + name: 'namepath-defining', + }, + }, + }, + }, + }, + { + code: ` + /** + * @property opt_a + * @param opt_b + */ + `, + options: [{ + match: [ + { + disallowName: '/^arg/i', + tags: ['*'], + }, + ], + }], + }, + { + code: ` + /** + * @param opt_a + * @param opt_b + */ + class A { + } + `, + options: [{ + match: [ + { + context: 'FunctionDeclaration', + disallowName: '/^opt_/i', + }, + ], + }], + }, + { + code: ` + /** + * @property opt_a + * @param {Foo|Bar} opt_b + */ + `, + options: [{ + match: [ + { + comment: 'JSDocBlock > JSDocTag[tag="param"] > JSDocTypeUnion[left.name="Bar"]', + disallowName: '/^opt_/i', + }, + ], + }], + }, + ], +}; diff --git a/test/rules/ruleNames.json b/test/rules/ruleNames.json index fedd59333..d38553595 100644 --- a/test/rules/ruleNames.json +++ b/test/rules/ruleNames.json @@ -13,6 +13,7 @@ "empty-tags", "implements-on-classes", "match-description", + "match-name", "multiline-blocks", "newline-after-description", "no-bad-blocks",