Coder Social home page Coder Social logo

bmish / eslint-doc-generator Goto Github PK

View Code? Open in Web Editor NEW
89.0 4.0 4.0 2.83 MB

Automatic documentation generator for ESLint plugins and rules.

JavaScript 1.04% TypeScript 98.96%
documentation eslint eslint-plugin generator javascript lint linter linting typescript

eslint-doc-generator's Introduction

eslint-doc-generator

npm version test coverage

Automatic documentation generator for ESLint plugins and rules. Inspired by documentation conventions from ESLint and top ESLint plugins.

Generates the following documentation covering a wide variety of rule metadata:

  • README.md rules table
  • README.md configs table
  • Rule doc titles and notices
  • Rule doc options lists

Also performs configurable section consistency checks on rule docs:

  • Contains an ## Options or ## Config section and mentions each named option (for rules with options)

Table of contents

Motivation

  • Standardize documentation across thousands of ESLint plugins and rules
  • Improve the discoverability of key rule information and thus rule usability
  • Streamline the process of adding/updating rules while ensuring documentation is kept up-to-date
  • Eliminate the custom documentation scripts and tests previously built and maintained by many ESLint plugins

Setup

Install it:

npm i --save-dev eslint-doc-generator

Scripts

Add scripts to package.json:

{
  "scripts": {
    "lint": "npm-run-all \"lint:*\"",
    "lint:docs": "markdownlint \"**/*.md\"",
    "lint:eslint-docs": "npm run update:eslint-docs -- --check",
    "lint:js": "eslint .",
    "update:eslint-docs": "eslint-doc-generator"
  }
}

Update README.md

Delete any old rules list from your README.md. A new one will be automatically added to your ## Rules section (along with the following marker comments if they don't already exist):

<!-- begin auto-generated rules list -->
<!-- end auto-generated rules list -->

Optionally, add these marker comments to your README.md in a ## Configs section or similar location (uses the meta.docs.description property exported by each config if available):

<!-- begin auto-generated configs list -->
<!-- end auto-generated configs list -->

Update rule docs

Delete any old recommended/fixable/etc. notices from your rule docs. A new title and notices will be automatically added to the top of each rule doc (along with a marker comment if it doesn't already exist).

<!-- end auto-generated rule header -->

Optionally, add these marker comments to your rule docs in an ## Options section or similar location:

<!-- begin auto-generated rule options list -->
<!-- end auto-generated rule options list -->

Note that rule option lists are subject-to-change as we add support for more kinds and properties of schemas. To fully take advantage of them, you'll want to ensure your rules have the meta.schema property fleshed out with properties like description, type, enum, default, required, deprecated.

Configure linting

And be sure to enable the recommended rules from eslint-plugin-eslint-plugin as well as:

Usage

Run the script from package.json to start out or any time you add a rule or update rule metadata in your plugin:

npm run update:eslint-docs

Examples

For examples, see our users or the in-house examples below. Note that the in-house examples intentionally show all possible columns and notices.

Rules list table

See the generated rules table and legend in our example README.md.

Configs list table

See the generated configs table in our example README.md.

Rule doc notices

See the generated rule doc title and notices in our example rule docs no-foo.md, prefer-bar.md, require-baz.md.

Rule doc options lists

See the generated rule doc options lists in our example rule doc no-foo.md.

Users

This tool is used by popular ESLint plugins like:

Configuration options

These can be provided as CLI options or as config file options. All options are optional.

The CLI has an optional path argument if you need to point the CLI to an ESLint plugin directory that isn't just the current directory:

eslint-doc-generator path/to/eslint-plugin

There's also a postprocess option that's only available via a config file.

Name Description  Default
--check Whether to check for and fail if there is a diff. Any diff will be displayed but no output will be written to files. Typically used during CI. false
--config-emoji Custom emoji to use for a config. Format is config-name,emoji. Option can be repeated. Default emojis are provided for common configs. See Badges for an alternative to emojis.
--config-format The format to use for config names. See choices in below table. name
--ignore-config Config to ignore from being displayed. Often used for an all config. Option can be repeated.
--ignore-deprecated-rules Whether to ignore deprecated rules from being checked, displayed, or updated. false
--init-rule-docs Whether to create rule doc files if they don't yet exist. false
--path-rule-doc Path to markdown file for each rule doc. Use {name} placeholder for the rule name. A function can also be provided for this option via a config file. docs/rules/{name}.md
--path-rule-list Path to markdown file where the rules table list should live. Option can be repeated. README.md
--rule-doc-notices Ordered, comma-separated list of notices to display in rule doc. Non-applicable notices will be hidden. See choices in below table. deprecated, configs, fixableAndHasSuggestions, requiresTypeChecking
--rule-doc-section-exclude Disallowed section in each rule doc. Exit with failure if present. Option can be repeated.
--rule-doc-section-include Required section in each rule doc. Exit with failure if missing. Option can be repeated.
--rule-doc-section-options Whether to require an "Options" or "Config" rule doc section and mention of any named options for rules with options. true
--rule-doc-title-format The format to use for rule doc titles. See choices in below table. desc-parens-prefix-name
--rule-list-columns Ordered, comma-separated list of columns to display in rule list. Empty columns will be hidden. See choices in below table. name, description, configsError, configsWarn, configsOff, fixable, hasSuggestions, requiresTypeChecking, deprecated
--rule-list-split Rule property(s) to split the rules list by. A separate list and header will be created for each value. Example: meta.type. A function can also be provided for this option via a config file.
--url-configs Link to documentation about the ESLint configurations exported by the plugin.
--url-rule-doc Link to documentation for each rule. Useful when it differs from the rule doc path on disk (e.g. custom documentation site in use). Use {name} placeholder for the rule name. A function can also be provided for this option via a config file.

Column and notice types

These are the types of rule metadata that are available for display in rule list columns (--rule-list-columns) and/or rule doc notices (--rule-doc-notices).

Emoji Type Column? Notice? Description
💼 configsError Yes No Whether a rule is set to error in a config.
🚫 configsOff Yes No Whether a rule is set to off in a config.
⚠️ configsWarn Yes No Whether a rule is set to warn in a config.
💼 configs No Yes What configs set a rule to what severities.
deprecated Yes Yes Whether a rule is deprecated (i.e. likely to be removed/renamed in a future major version).
description Yes Yes The rule description.
🔧💡 fixableAndHasSuggestions Yes Yes Whether a rule is fixable and/or has suggestions.
🔧 fixable Yes Yes Whether a rule is fixable.
💡 hasSuggestions Yes Yes Whether a rule has suggestions.
name Yes No The rule name.
⚙️ options Yes Yes Whether a rule has options.
💭 requiresTypeChecking Yes Yes Whether a rule requires type checking.
🗂️ type Yes Yes The rule type (problem, suggestion, or layout).

--config-format

Where recommended is the config name and eslint-plugin-test is the plugin name.

Value Example
name (default) recommended
plugin-colon-prefix-name plugin:test/recommended
prefix-name test/recommended

--rule-doc-title-format

Where no-foo is the rule name, Disallow use of foo is the rule description, and eslint-plugin-test is the plugin name.

Value Example
desc # Disallow use of foo
desc-parens-name # Disallow use of foo (no-foo)
desc-parens-prefix-name (default) # Disallow use of foo (test/no-foo)
name # no-foo
prefix-name # test/no-foo

Configuration file

There are a few ways to create a config file (as an alternative to passing the options via CLI):

  • An object exported by .eslint-doc-generatorrc.js, .eslint-doc-generatorrc.json, or any other config file format/name supported by cosmiconfig
  • An object under the eslint-doc-generator key in package.json

Config files support all the CLI options but in camelCase.

Some options are exclusive to a JavaScript-based config file:

  • postprocess - A function-only option useful for applying custom transformations such as formatting with tools like prettier. See prettier example.
  • ruleListSplit with a function - This is useful for customizing the grouping of rules into lists.

Example .eslint-doc-generatorrc.js:

/** @type {import('eslint-doc-generator').GenerateOptions} */
const config = {
  ignoreConfig: ['all'],
};

module.exports = config;

Example .eslint-doc-generatorrc.js with pathRuleDoc function:

/** @type {import('eslint-doc-generator').GenerateOptions} */
const config = {
  pathRuleDoc(name) {
    // e.g. rule name format is `some-plugin/some-rule`, and rule is in a monorepo under different package.
    const [plugin, rule] = name.split("/");
    return `packages/eslint-plugin-${plugin}/src/rules/${rule}.md`;
  },
};

module.exports = config;

Example .eslint-doc-generatorrc.js with ruleListSplit function:

/** @type {import('eslint-doc-generator').GenerateOptions} */
const config = {
  ruleListSplit(rules) {
    return [
      {
        // No header for this list.
        rules: rules.filter(([name, rule]) => !rule.meta.someProp),
      },
      {
        title: 'Foo',
        rules: rules.filter(([name, rule]) => rule.meta.someProp === 'foo'),
      },
      {
        title: 'Bar',
        rules: rules.filter(([name, rule]) => rule.meta.someProp === 'bar'),
      },
    ];
  },
};

module.exports = config;

Example .eslint-doc-generatorrc.js with urlRuleDoc function:

/** @type {import('eslint-doc-generator').GenerateOptions} */
const config = {
  urlRuleDoc(name, page) {
    if (page === 'README.md') {
      // Use URLs only in the readme.
      return `https://example.com/rules/${name}.html`;
    }
  },
};

module.exports = config;

Badges

While emojis are the recommended representations of configs that a rule belongs to, you can alternatively use a text/image/icon badge for configs by supplying the following markdown for the emoji using the --config-emoji option.

For example, here's the markdown for a text badge representing a custom fun config that displays in blue (note that the markdown includes alt text followed by the image URL):

![fun config badge](https://img.shields.io/badge/-fun-blue.svg)

Here's how you'd configure it:

/** @type {import('eslint-doc-generator').GenerateOptions} */
const config = {
  configEmoji: [
    ['fun', '![fun config badge](https://img.shields.io/badge/-fun-blue.svg)'],
  ],
};

module.exports = config;

And how it looks:

fun config badge

Compatibility

Build tools

If you have a build step for your code like Babel or TypeScript, you may need to adjust your scripts to run your build before this tool to ensure the documentation is generated from the latest plugin information:

{
  "build": "tsc",
  "update:eslint-docs": "npm run build && eslint-doc-generator"
}

markdownlint

The output of this tool should be compatible with the default configuration of markdownlint, which you might use to lint your markdown. If it's not, you can follow the prettier example to tweak your scripts or use the postprocess option. See here for an example of markdownlint's Node API for applying fixes to use in your postprocess function.

prettier

If you use prettier to format your markdown, you can provide a postprocess function to ensure the documentation generated by this tool is formatted correctly:

const prettier = require('prettier');
const { prettier: prettierRC } = require('./package.json'); // or wherever your prettier config lies

/** @type {import('eslint-doc-generator').GenerateOptions} */
const config = {
  postprocess: (content, path) =>
    prettier.format(content, { ...prettierRC, parser: 'markdown' }),
};

module.exports = config;

Alternatively, you can configure your scripts to run prettier after this tool:

{
  "format": "prettier --write .",
  "lint:eslint-docs": "npm run update:eslint-docs && git diff --exit-code",
  "update:eslint-docs": "eslint-doc-generator && npm run format"
}

Semantic versioning policy

This tool follows semantic versioning.

New features will be released as a minor version, while bug fixes will be released as a patch version.

Breaking changes will be released as a major version and include:

  • Changing an option default
  • Renaming or removing an option
  • Other backwards-incompatible changes to the CLI / API
  • Raising Node or ESLint version requirements

Tweaks to the generated documentation output can take place in any type of release including minor and patch versions. This can break your build, as even a small formatting change will cause a diff, but you can simply re-run the tool to fix.

Related

eslint-doc-generator's People

Contributors

bmish avatar ddzz avatar dependabot[bot] avatar g-rath avatar hyoban avatar joshuakgoldberg avatar michaeldeboey avatar simenb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

eslint-doc-generator's Issues

More robust detection of README rules section

Right now, we only detect a ## Rules section when looking for where to insert the rules list into the README when the marker comments are missing. While this is the most common section name, we should detect additional variations:

  • ## 🍟 Rules (eslint-plugin-ember)
  • ## Custom rules (eslint-plugin-square)
  • ## List of supported rules (eslint-plugin-react)

Auto-generate a badge for each config

So the user doesn't have to do it themselves unless they want to.

If an emoji isn't specified for a config, and we don't see a badge for it in the README, automatically add one to the bottom of the README.

Add options for non-standard paths for README.md or rule doc files

Might need a config option to specify the path to these if non-standard:

Standard paths:

  • README.md
  • docs/rules/[rule-name].md

Override options:

  • --path-readme
  • --path-rule-doc

Also considered:

  • --rule-doc-path for grouping with existing rule doc options
  • --rule-list-path for grouping with existing rule list options

Include rule name prefix in rule doc title

Before

# Do not use `foo` (`no-foo`)

After

# Do not use `foo` (`test/no-foo`)

Where the plugin is called eslint-plugin-test.

This avoids a potential hiccup since users will need to use the prefix to refer to the rule in their own codebases.

[BUG] Prettier not found

Apparently the library expects that i installed prettier in my project.

node:internal/errors:465
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'prettier' imported from ...\node_modules\.pnpm\[email protected]_ypn2ylkkyfa5i233caldtndbqa\node_modules\eslint-doc-generator\dist\lib\markdown.js
    at new NodeError (node:internal/errors:372:5)
    at packageResolve (node:internal/modules/esm/resolve:954:9)
    at moduleResolve (node:internal/modules/esm/resolve:1003:20)
    at defaultResolve (node:internal/modules/esm/resolve:1218:11)
    at ESMLoader.resolve (node:internal/modules/esm/loader:580:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:294:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40)
    at link (node:internal/modules/esm/module_job:78:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
 ELIFECYCLE  Command failed with exit code 1.

EXPECTED RESULT:
shouldn't crash if prettier isn't my project.

ACTUAL RESULT:
crash if prettier isn't my project.

ENVIROMENT:
Windows 10
Node 16

Custom config emojis

Allow specifying the emoji to represent each config.

Examples of config option:

--config-emoji "recommended,✅" (default)
--config-emoji "stylistic,🎨"

Potential issue with importing Windows paths

Node 16 Windows CI is failing attempting to add this tool to an eslint plugin in square/eslint-plugin-square#764.

node:internal/errors:477
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only URLs with a scheme in: file, data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'd:'
    at new NodeError (node:internal/errors:387:5)
    at throwIfUnsupportedURLScheme (node:internal/modules/esm/resolve:1116:11)
    at defaultResolve (node:internal/modules/esm/resolve:1196:3)
    at nextResolve (node:internal/modules/esm/loader:165:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:844:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:431:18)
    at ESMLoader.import (node:internal/modules/esm/loader:528:22)
    at importModuleDynamically (node:internal/modules/esm/translators:110:35)
    at importModuleDynamicallyCallback (node:internal/process/esm_loader:35:[14](https://github.com/square/eslint-plugin-square/actions/runs/3170797584/jobs/5163651883#step:5:15))
    at loadPlugin (file:///D:/a/eslint-plugin-square/eslint-plugin-square/node_modules/eslint-doc-generator/dist/lib/package-json.js:[20](https://github.com/square/eslint-plugin-square/actions/runs/3170797584/jobs/5163651883#step:5:21):33) {
  code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME'
}
error Command failed with exit code 1.

https://github.com/square/eslint-plugin-square/actions/runs/3170797584/jobs/5163651883

Only use prettier to format affected doc content

Not everyone wants to format their docs with prettier. It also creates a big diff when running this tool. By default, we should only use prettier to format the doc sections this tool manages. We could have an option (default off) to use it to format the entire affected docs.

Split tests file

All our tests our in the massive generate-test.ts test file. Sticking to acceptance tests and avoiding most unit tests has been helpful as it has allowed quicker refactoring of functions without having to update a ton of unit tests. But we should split this giant acceptance test file into multiple files based on category of test.

Add option to create missing rule docs

--init-rule-docs to create any missing rule docs.

Fail if there are no rule docs to create so this option isn't left in place indefinitely.

This would only be useful for someone who hasn't created any docs for their rules yet. In that scenario, this would help save time in getting started with documentation.

The reason we need an explicit option for this (and we don't want to automatically create missing rule docs by default) is because the rule docs might live at a non-standard path and we just didn't detect them. If the plugin has a non-standard rule doc path, the user just needs to specify --path-rule-doc.

Follow-up to #78.

Leaky unit test is modifying the README

Each of our tests sets up a mock filesystem using mock-fs in beforeEach() and then tears it down with mockFs.restore(); in afterEach(). This way, the tests can see the desired files, modify, and test them without affecting the actual filesystem.

For some reason, there seems to be a leak from the tests to the actual filesystem. The doc generator is inserting a rules list into README.md in between the marker comments.

<!-- begin rules list -->
<!-- end rules list -->

It's easy to accidentally check this change in. We need to figure out how to avoid this leak.

Automatically generate configs list in README

Automatically generate a table/list of configs in the README ## Configs section.

Not sure about this yet. We have the list of configs but we don't know the config descriptions. We do know the config emojis/badges if the user has specified them.

Optional columns:

  • Number of rules enabled, warn, or disabled in each config

Related: #20.

Configurable rule doc title format

We currently use the following rule doc title format:

# Do not use foo (`test/no-foo`)

We should also support another format with just the rule name without description which is also a common format in plugins:

# no-foo

Not sure which should be the default yet.

  • --rule-doc-title-format desc-parens-prefix-name (default): # Do not use foo (test/no-foo)
  • --rule-doc-title-format desc-parens-name: # Do not use foo (no-foo)
  • --rule-doc-title-format prefix-name: # test/no-foo
  • --rule-doc-title-format name: # no-foo

Configurable allowed or disallowed sections enforcement

We currently only check for an ## Options section. Some users may also want to check for other sections like:

  • ## Examples
  • ## Rule details

Or even disallow certain sections.

This helps enforce documentation consistency.

We could have an option like:

  • --rule-doc-section-include
  • --rule-doc-section-exclude

Link to config section of README in rule notices

[MESSAGE_TYPE.CONFIGS]: `${EMOJI_CONFIGS} This rule is enabled in the following configs:`, // TODO: include link to configs in the plugin's README.

Might need an option to specify this URL.

Example current:

💼 This rule is enabled in the following configs: all, recommended.

Example desired:

💼 This rule is enabled in the following configs: all, recommended.

Option:

  • --url-configs https://github.com/ember-cli/eslint-plugin-ember#-configurations

Handle configs that extend other configs

module.exports = {
  extends: [require.resolve('./other-config')],
};

This causes a crash right now:

$ eslint-doc-generator
eslint-doc-generator/dist/lib/configs.js:15
        const value = config.rules[`${pluginPrefix}/${ruleName}`];
                                  ^

TypeError: Cannot read properties of undefined (reading 'test/no-foo')
    at getConfigsForRule (eslint-doc-generator/dist/lib/configs.js:15:35)
    at getRuleNoticeLines (eslint-doc-generator/dist/lib/rule-notices.js:47:28)
    at generateRuleHeaderLines (eslint-doc-generator/dist/lib/rule-notices.js:93:12)
    at generate (eslint-doc-generator/dist/lib/generator.js:62:32)
    at async Command.<anonymous> (eslint-doc-generator/dist/lib/cli.js:21:9)
error Command failed with exit code 1.

And the extended config needs to be resolved. Maybe ESLint has an API to do this for us.

Option to disable options section check

By default, we check for a ## Options or ## Config section that mentions all the named options of a rule.

We could make this configurable through an option like:

Option Desc
--rule-doc-section-options (default true) Whether to check for a rule doc ## Options or ## Config section and any named options when a rule has options.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.