1.7.1 • Published 2 years ago

yaml-fm-lint v1.7.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Package size NPM version VS Code extension


Content


What is this

An opinionated CLI NodeJS script which extracts yaml front matter from markdown files, lints the extracted data based on a config file and, if required, fixes most issues regarding the yaml.

There is also a VS Code extension which integrates this script within VS Code and decorates errors/warnings in real time.

Install

You can either install the package as a devDependency with

npm i -D yaml-fm-lint
yarn add -D yaml-fm-lint

or use it directly with

npx yaml-fm-lint <path>

Usage

Include the script in your package.json file:

"scripts": {
  "fmlint": "yaml-fm-lint path/to/your/markdown/files -r"
}

Then run the script:

npm run fmlint
yarn run fmlint

Additional arguments:

ArgumentDefaultDescription
--configprocess.cwd()Path to the config file
--fixfalseAutomatically fix the errors
--globOnlyfalseOverride extra excluded and included directories/files and just use the glob matching to lint files
-r, --recursivefalseRecursively lint accepted files if given a specific directory
-q, --quietfalseWill only show the number of warnings and errors
-o, --onelinefalseCondense error messages to one line, skipping snippets
-bs, --backslashfalseWhen logging, use backslashes instead of forward slashes
-m, --mandatorytrueIf no front matter is found, show an error. Shows a warning when false
-c, --coloredtrueUse control characters to color the output

Example:

npm run fmlint -- docs --config="src/configs/.yaml-fm-lint.json" -r --oneline --colored=false

This command would recursively look for all markdown files in the docs directory and lint them based on the .yaml-fm-lint.json config file located under src/configs/. The output would not be colored and would not show code snippets.

You can also use glob patterns to find files.

npm run fmlint -- "**/[!README]*.{md,mdx}"

node_modules folder is ignored by default.


Configuration

Text passed to yaml-fm-lint is parsed as YAML, analysed, and any issues reported.

Disabling linting

To disable rules for a particular line within the front matter, add one of these markers to the appropriate place (comments don't affect the file's metadata):

  • Disable all rules for the current line: # fmlint-disable-line
  • Disable all rules for the next line: # fmlint-disable-next-line

For example:

sidebar_label: Configuration
description: It's the configuration file # fmlint-disable-line

Or:

sidebar_label: Configuration
# fmlint-disable-next-line
description: It's the configuration file

Config files

When run recursively, the script will look for the most nested config file, overriding properties from previous configurations.
Config path specified in CLI arguments will never be overriden.

.yaml-fm-lint.json

Default config file

Property namedefaultdescription
disabledAttributes[]Array of attributes to exclude from linting
excludeDirsSee default configAn array of directories to exclude from linting (🛑You should not overwrite this in your config unless you know what you are doing)
extraExcludeDirs[]Additional array of directories to exclude from linting
excludeFiles[]Array of file names or file paths to exclude from linting
extensions[".md"]Array of extensions of files to parse
includeDirs[]Array of directories to include in linting
requiredAttributes[]Array of attributes that must be present in the yaml front matter
mandatorytrueIf set to false will show warning instead of error if no front matter is found

.yaml-fm-lint.js

You will have to default export the config object.

Custom linters

In addition to the default config you can also add your own custom linters. These will be executed after the default linters.

The functions receive an object with the following properties:

  • filePath - The path to the currently linted file
  • attributes - The yaml front matter as a JavaScript object
  • fmLines - The yaml front matter lines in a string array. Includes lines with --- dashes
  • lintLog - Function to call error/warning messages. Receives the following arguments:
    • type - "Error" or "Warning"
    • message - The error message
    • affected - This is either a string[] of word values, a number[] of erronious lines or an array of objects with row and col values for precise error locations (should include colStart and colEnd for decorations in the VS Code extension)
/**
 * @param {{filePath: string, attributes: Object, fmLines: string[], lintLog: (type: "Error" | "Warning", message: string, affected: string[] | number[] | { row: number, col: number, colStart?: number, colEnd?: number }[] | undefined) => void}} props
 * @returns {{errors: number, warnings: number}}
 */
function lowercaseTags({ fmLines, lintLog }) {
  const tagsRegExp = /^tags.*:/g;

  const tagsLineIndex = fmLines.findIndex((line) => tagsRegExp.test(line));
  if (tagsLineIndex < 0) return { errors: 0, warnings: 0 };

  const eachTagRegExp = /^(\s*-\s+)(.+)$/;
  const locations = [];
  let errors = 0;

  for (let i = tagsLineIndex + 1; i < fmLines.length; i++) {
    const line = fmLines[i];
    if (!eachTagRegExp.test(line)) break;
    const match = line.match(eachTagRegExp);
    const tag = match[2];
    if (tag.toLowerCase() !== tag) {
      locations.push({
        row: i,
        col: match[1].length + 2,
        colStart: match[1].length,
        colEnd: match[1].length + tag.length,
      });
      errors++;
    }
  }

  lintLog("Error", "tags must be lowercase", locations);

  return { errors, warnings: 0 };
}

module.exports = {
  extraLintFns: [lowercaseTags],
  requiredAttributes: ["tags"],
};
1.7.1

2 years ago

1.7.0

2 years ago

1.6.4

2 years ago

1.6.5

2 years ago

1.6.3

3 years ago

1.6.2

3 years ago

1.6.1

3 years ago

1.6.0

3 years ago

1.5.7

3 years ago

1.5.6

3 years ago

1.5.5

3 years ago

1.5.4

3 years ago

1.5.3

3 years ago

1.5.2

3 years ago

1.5.1

3 years ago

1.5.0

3 years ago

1.4.0

3 years ago

1.3.3

3 years ago

1.3.2

3 years ago

1.3.1

3 years ago

1.3.0

3 years ago

1.2.0

3 years ago

1.1.0-alpha

3 years ago

1.0.6-alpha

3 years ago

1.0.5-alpha

3 years ago

1.0.4-alpha

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago