### Install yamllint from source Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Install yamllint from source by building the package and then installing it using pip. This is useful for development or if you need the latest unreleased version. ```bash python -m build pip install --user dist/yamllint-*.tar.gz ``` -------------------------------- ### Install yamllint using pip Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Install yamllint using pip, the Python package manager. Use --user to install for the current user. ```bash pip install --user yamllint ``` -------------------------------- ### Install yamllint on FreeBSD Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use pkg to install py-yamllint on FreeBSD. ```bash pkg install py-yamllint ``` -------------------------------- ### Install and Run Tests Source: https://github.com/adrienverge/yamllint/blob/master/CONTRIBUTING.rst Install the project locally and run all tests or specific test files. Use this to ensure your changes do not break existing functionality. ```bash pip install --user . python -m unittest discover # all tests... python -m unittest tests/rules/test_commas.py # or just some tests (faster) ``` -------------------------------- ### Install yamllint on OpenBSD Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use doas pkg_add to install py-yamllint on OpenBSD. ```bash doas pkg_add py-yamllint ``` -------------------------------- ### yamllint Configuration File Example Source: https://context7.com/adrienverge/yamllint/llms.txt A full example of a .yamllint configuration file, demonstrating global options like extends, ignore, yaml-files, locale, and per-rule settings. ```yaml # .yamllint — full example with all top-level options extends: default # inherit from 'default' or 'relaxed' or a file path # Gitignore-style patterns for files/dirs to skip entirely ignore: | build/ *.generated.yaml !/build/important.yaml # Or load ignore patterns from .gitignore (mutually exclusive with 'ignore') # ignore-from-file: [.gitignore, .yamlignore] # Override which file extensions are treated as YAML (gitignore-style globs) yaml-files: - '*.yaml' - '*.yml' - '.yamllint' - '*.j2.yaml' # Locale for key-ordering rule (empty string = system default) locale: en_US.UTF-8 rules: # Adjust line length to 120 characters, downgraded to warning line-length: max: 120 level: warning allow-non-breakable-words: true allow-non-breakable-inline-mappings: true # Require 2-space indentation, allow flexible sequence placement indentation: spaces: 2 indent-sequences: consistent check-multi-line-strings: false # Only allow lowercase true/false for boolean values truthy: allowed-values: ['true', 'false'] check-keys: true level: error # Enforce double-quoted strings everywhere quoted-strings: quote-type: double required: only-when-needed # Disable rules not needed for this project document-start: disable key-ordering: disable # Per-rule path ignoring (gitignore-style) trailing-spaces: ignore: | ascii-art/* legacy/*.yaml ``` -------------------------------- ### yamllint configuration example Source: https://github.com/adrienverge/yamllint/blob/master/README.rst Example of a yamllint configuration file. It extends the default configuration and customizes rules for line length and indentation. ```yaml extends: default rules: # 80 chars should be enough, but don't fail if a line is longer line-length: max: 80 level: warning # don't bother me with this rule indentation: disable ``` -------------------------------- ### Install yamllint on Debian/Ubuntu Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use apt-get to install yamllint on Debian 8+ or Ubuntu 16.04+ systems. ```bash sudo apt-get install yamllint ``` -------------------------------- ### Install yamllint on Alpine Linux Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use pkg add to install yamllint on Alpine Linux. ```bash pkg add yamllint ``` -------------------------------- ### Install yamllint on Fedora/CentOS Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use dnf to install yamllint on Fedora or CentOS systems. EPEL repository is required on CentOS. ```bash sudo dnf install yamllint ``` -------------------------------- ### Install yamllint on Mac OS Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use Homebrew to install yamllint on Mac OS 10.11+. ```bash brew install yamllint ``` -------------------------------- ### Examples of quoted-strings rule in yamllint Source: https://context7.com/adrienverge/yamllint/llms.txt Demonstrates passing and failing cases for the `quoted-strings` rule based on its configuration, including handling of URLs and quote consistency. ```yaml # PASS (required: only-when-needed): unquoted plain string foo: bar # PASS (required: only-when-needed): quotes needed to avoid ambiguity not_number: '123' not_boolean: 'true' not_list: '[1, 2, 3]' # FAIL (required: only-when-needed): quotes unnecessary for plain string foo: 'bar' # PASS (extra-required: ['^http://']): URLs must be quoted - "http://localhost/path" # FAIL (extra-required: ['^http://']): unquoted URL - http://localhost/path # PASS (quote-type: consistent): all strings use same quote style foo: 'bar' baz: 'quux' # FAIL (quote-type: consistent): mixed quote styles foo: 'bar' baz: "quux" ``` -------------------------------- ### Configure yamllint for GitHub Actions Source: https://context7.com/adrienverge/yamllint/llms.txt Sets up yamllint to run as a GitHub Action, providing direct annotations on diffs for linting issues. Assumes `pip` is available for installation. ```yaml # .github/workflows/lint.yaml --- on: push # yamllint disable-line rule:truthy jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install yamllint run: pip install yamllint - name: Lint all YAML files run: yamllint --strict . ``` -------------------------------- ### Examples of empty-values rule in yamllint Source: https://context7.com/adrienverge/yamllint/llms.txt Illustrates passing and failing cases for the `empty-values` rule, showing correct explicit nulls and incorrect implicit nulls in various YAML structures. ```yaml # PASS: explicit null implicitly-null: null {prop: null} # FAIL (forbid-in-block-mappings): no value after key implicitly-null: # FAIL (forbid-in-flow-mappings): empty flow value {a: 1, b:, c: 3} # FAIL (forbid-in-block-sequences): empty sequence entry some-sequence: - ``` -------------------------------- ### Extend Default Configuration - Disable Rule Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Example of a custom configuration file that extends the default configuration and disables the 'comments-indentation' rule. ```yaml # This is my first, very own configuration file for yamllint! # It extends the default conf by adjusting some options. extends: default rules: comments-indentation: disable # don't bother me with this rule ``` -------------------------------- ### Minimal GitHub Actions Workflow for yamllint Source: https://github.com/adrienverge/yamllint/blob/master/docs/integration.md A basic GitHub Actions workflow to automatically lint YAML files on push events. It checks out the code, installs yamllint via pip, and runs the linter on the current directory. ```yaml --- on: push # yamllint disable-line rule:truthy jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install yamllint run: pip install yamllint - name: Lint YAML files run: yamllint . ``` -------------------------------- ### Use parsable output format Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use the -f parsable argument to get machine-readable output, suitable for integration with text editors for syntax highlighting or other tools. ```bash yamllint -f parsable file.yml ``` -------------------------------- ### Set Locale for Key Ordering Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Configure the locale globally to affect sorting in the 'key-ordering' rule. An empty string uses the system default. Example uses 'en_US.UTF-8'. ```yaml extends: default locale: en_US.UTF-8 ``` -------------------------------- ### Format Yaml Comments with Yamllint Source: https://context7.com/adrienverge/yamllint/llms.txt Enforce formatting and positioning of YAML comments. Ensure comments start with a space after '#', have a minimum number of spaces from content, and optionally ignore shebangs. ```yaml extends: default rules: comments: require-starting-space: true # require a space after '#' ignore-shebangs: true # don't apply require-starting-space to #!/... on line 1 min-spaces-from-content: 2 # inline comments must be at least 2 spaces from content level: warning ``` ```yaml # PASS: space after '#', 2 spaces before inline comment x: 127 # Mersenne prime number ``` ```yaml # FAIL (require-starting-space): no space after '#' #This is a bad comment ``` ```yaml # FAIL (min-spaces-from-content: 2): only 1 space before comment x: 127 # needs two spaces ``` -------------------------------- ### Ignore specific rules for certain files Source: https://github.com/adrienverge/yamllint/blob/master/README.rst Configure yamllint to ignore specific rules for certain files or patterns. This example shows ignoring 'key-duplicates' and 'trailing-spaces'. ```yaml rules: key-duplicates: ignore: | generated *.template.yaml trailing-spaces: ignore: | *.ignore-trailing-spaces.yaml /ascii-art/* ``` -------------------------------- ### GitLab CI/CD for Code Quality Report Source: https://github.com/adrienverge/yamllint/blob/master/docs/integration.md This GitLab CI/CD configuration runs yamllint and generates a 'codequality.json' report compatible with GitLab's Code Quality feature. It installs yamllint, processes the output using awk to format it, and saves the report as an artifact. ```yaml --- lint: stage: lint script: - pip install yamllint - mkdir reports - > yamllint -f parsable . | tee >(awk ' BEGIN {FS = ":"; ORS="\n"; first=1} { gsub(/^[ \t]+|[ \t]+$|"/, "", $4); match($4, /^\[(warning|error)\](.*)\((.*)\)$/, a); sev = (a[1] == "error" ? "major" : "minor"); if (first) { first=0; printf("["); } else { printf(","); } printf("{\"location\":{\"path\":\"%s\",\"lines\":{\"begin\":%s,\"end\":%s}},\"severity\":\"%s\",\"check_name\":\"%s\",\"categories\":[\"Style\"],\"type\":\"issue\",\"description\":\"%s\"}", $1, $2, $3, sev, a[3], a[2]); } END { if (!first) printf("]\n"); }' > reports/codequality.json) artifacts: when: always paths: - reports expire_in: 1 week reports: codequality: reports/codequality.json ``` -------------------------------- ### Lint with a custom configuration file Source: https://github.com/adrienverge/yamllint/blob/master/README.rst Specify a custom configuration file using the '-c' flag for detailed linting rules. ```bash yamllint -c /path/to/myconfig file-to-lint.yaml ``` -------------------------------- ### Specify custom configuration file Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use the -c option to specify a custom linting configuration file. This allows for project-specific linting rules. ```bash yamllint -c ~/myconfig file.yaml ``` -------------------------------- ### Run Doc8 Linter Source: https://github.com/adrienverge/yamllint/blob/master/CONTRIBUTING.rst Check documentation files for style compliance using Doc8. Run this if you have added or modified documentation. ```bash doc8 $(git ls-files '*.rst') ``` -------------------------------- ### Python API: `linter.run()` Source: https://context7.com/adrienverge/yamllint/llms.txt `linter.run(input, conf, filepath=None)` lints a YAML source and returns a generator of `LintProblem` objects. Input can be a string, bytes, or file-like stream. ```APIDOC ## Python API: `linter.run()` `linter.run(input, conf, filepath=None)` lints a YAML source and returns a generator of `LintProblem` objects. Input can be a string, bytes, or file-like stream. Returns an empty iterator if the file is ignored by the config. ### Usage Examples ```python from yamllint import linter from yamllint.config import YamlLintConfig conf = YamlLintConfig("extends: default") # Lint from a string yaml_content = """ --- key: value other_key: value other_key: duplicate """ problems = list(linter.run(yaml_content, conf, filepath="example.yaml")) for p in problems: print(f"{p.line}:{p.column} [{p.level}] {p.desc} ({p.rule})") # 2:7 [error] too many spaces after colon (colons) # 2:14 [error] trailing spaces (trailing-spaces) # 4:1 [error] duplication of key "other_key" in mapping (key-duplicates) # Lint from a file stream with open("config.yaml", "rb") as f: for problem in linter.run(f, conf, filepath="config.yaml"): print(repr(problem)) # → 3:1: wrong indentation: expected 2 but found 1 (indentation) ``` ``` -------------------------------- ### List Files to Process Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Command-line option to list all files that yamllint would process without actually linting them. ```bash yamllint --list-files . ``` -------------------------------- ### Custom Configuration via CLI Data Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Pass custom configuration options directly via the -d command-line argument, combining 'extends' and specific rule overrides. ```bash yamllint -d "{extends: relaxed, rules: {line-length: {max: 120}}}" file.yaml ``` -------------------------------- ### Choose Relaxed Configuration via CLI Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Use the -d option with the value 'relaxed' to apply the relaxed configuration for a single linting operation. ```bash yamllint -d relaxed file.yml ``` -------------------------------- ### Lint files and directories with yamllint CLI Source: https://context7.com/adrienverge/yamllint/llms.txt Use the `yamllint` command to lint specific files, recursively lint directories, or lint from standard input. Supports custom configurations and presets. ```bash yamllint file.yaml other.yml ``` ```bash yamllint . ``` ```bash echo "key: value" | yamllint - ``` ```bash yamllint -d relaxed file.yaml ``` ```bash yamllint -c /path/to/.yamllint file.yaml ``` ```bash yamllint -d "{extends: relaxed, rules: {line-length: {max: 120}}}" file.yaml ``` ```bash yamllint -f parsable file.yaml ``` ```bash # → file.yaml:6:2: [warning] missing starting space in comment (comments) # → file.yaml:57:1: [error] trailing spaces (trailing-spaces) ``` ```bash yamllint --format github file.yaml ``` ```bash yamllint --strict file.yaml ``` ```bash yamllint --no-warnings file.yaml ``` ```bash yamllint --list-files . ``` -------------------------------- ### Python API: `YamlLintConfig` Source: https://context7.com/adrienverge/yamllint/llms.txt `YamlLintConfig` loads and validates a yamllint configuration from a YAML string or file. It supports `extends` to inherit from built-in presets or custom config files. ```APIDOC ## Python API: `YamlLintConfig` `YamlLintConfig` loads and validates a yamllint configuration from a YAML string or file. It supports `extends` to inherit from built-in presets (`default`, `relaxed`) or any custom config file. ### Usage Examples ```python from yamllint.config import YamlLintConfig, YamlLintConfigError # Load from inline YAML string, extending the default preset conf = YamlLintConfig("extends: default") # Load from a file conf = YamlLintConfig(file="/path/to/.yamllint") # Build config programmatically with custom rule overrides conf = YamlLintConfig(""" extends: default rules: line-length: max: 100 level: warning indentation: spaces: 4 indent-sequences: consistent truthy: allowed-values: ['true', 'false', 'yes', 'no'] comments-indentation: disable """) # Check whether a file path is ignored by config print(conf.is_file_ignored("generated/output.yaml")) # True if matches ignore pattern # Check whether a filepath is treated as a YAML file print(conf.is_yaml_file("config.yml")) # True # Error handling try: bad_conf = YamlLintConfig("rules:\n unknown-rule: enable") except YamlLintConfigError as e: print(f"Config error: {e}") ``` ``` -------------------------------- ### Load yamllint configuration with YamlLintConfig Source: https://context7.com/adrienverge/yamllint/llms.txt Instantiate `YamlLintConfig` to load and validate configurations from YAML strings or files. Supports extending presets and programmatic rule overrides. ```python from yamllint.config import YamlLintConfig, YamlLintConfigError # Load from inline YAML string, extending the default preset conf = YamlLintConfig("extends: default") ``` ```python conf = YamlLintConfig(file="/path/to/.yamllint") ``` ```python conf = YamlLintConfig(""" extends: default rules: line-length: max: 100 level: warning indentation: spaces: 4 indent-sequences: consistent truthy: allowed-values: ['true', 'false', 'yes', 'no'] comments-indentation: disable """) ``` ```python # Check whether a file path is ignored by config print(conf.is_file_ignored("generated/output.yaml")) # True if matches ignore pattern ``` ```python # Check whether a filepath is treated as a YAML file print(conf.is_yaml_file("config.yml")) # True ``` ```python # Error handling try: bad_conf = YamlLintConfig("rules:\n unknown-rule: enable") except YamlLintConfigError as e: print(f"Config error: {e}") ``` -------------------------------- ### Extend Default Configuration - Adjust Rules Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Custom configuration extending the default, setting 'line-length' to a warning and adjusting 'indentation' for sequences. ```yaml extends: default rules: # 80 chars should be enough, but don't fail if a line is longer line-length: max: 80 level: warning # accept both key: # - item # # and key: # - item indentation: indent-sequences: whatever ``` -------------------------------- ### Configure YAML File Extensions Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Define the file extensions that yamllint should consider as YAML files using the 'yaml-files' option in the configuration. ```yaml yaml-files: - '*.yaml' - '*.yml' - '.yamllint' ``` -------------------------------- ### List Files to be Processed Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Use the --list-files option to see the exact list of files that yamllint would process without actually performing the linting. ```bash yamllint --list-files . ``` -------------------------------- ### Lint with a pre-defined configuration Source: https://github.com/adrienverge/yamllint/blob/master/README.rst Use the 'relaxed' pre-defined lint configuration for a specified file. This is useful for quick checks without custom configuration. ```bash yamllint -d relaxed file.yaml ``` -------------------------------- ### Lint multiple YAML files Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Run yamllint on specified YAML files. Provide file paths as arguments. ```bash yamllint file.yml other-file.yaml ``` -------------------------------- ### Ignore Files from External List (Multiple Files) Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Specify multiple files (e.g., .gitignore, .yamlignore) as a list to read ignore patterns from. This is mutually exclusive with the 'ignore' key. ```yaml ignore-from-file: [.gitignore, .yamlignore] ``` -------------------------------- ### Ignore files and directories for all rules Source: https://github.com/adrienverge/yamllint/blob/master/README.rst Configure yamllint to ignore specific files or directories using '.gitignore'-style patterns in the configuration file. ```yaml ignore: | *.dont-lint-me.yaml /bin/ !/bin/*.lint-me-anyway.yaml ``` -------------------------------- ### CLI: Lint files and directories Source: https://context7.com/adrienverge/yamllint/llms.txt The `yamllint` command lints one or more YAML files, or recursively all YAML files inside a directory. It provides various options for configuration and output formatting. ```APIDOC ## CLI: Lint files and directories The `yamllint` command lints one or more YAML files, or recursively all YAML files inside a directory. Exit codes: `0` = no issues, `1` = errors found, `2` = warnings found (only in strict mode). ### Usage Examples ```bash # Lint one or more specific files yamllint file.yaml other.yml # Recursively lint all YAML files under current directory (auto-discovers .yamllint config) yamllint . # Lint from stdin echo "key: value" | yamllint - # Use built-in relaxed preset yamllint -d relaxed file.yaml # Use a custom config file yamllint -c /path/to/.yamllint file.yaml # Pass inline config (YAML object) without a file yamllint -d "{extends: relaxed, rules: {line-length: {max: 120}}}" file.yaml # Parsable output (useful for editors / CI parsers) yamllint -f parsable file.yaml # → file.yaml:6:2: [warning] missing starting space in comment (comments) # → file.yaml:57:1: [error] trailing spaces (trailing-spaces) # Force GitHub Actions annotation format yamllint --format github file.yaml # Strict mode: exit 2 on warnings, exit 1 on errors yamllint --strict file.yaml # Suppress warning-level output (only show errors) yamllint --no-warnings file.yaml # List files that would be linted without actually linting them yamllint --list-files . ``` ``` -------------------------------- ### Integrate yamllint with pre-commit Source: https://github.com/adrienverge/yamllint/blob/master/docs/integration.md Add this configuration to your .pre-commit-config.yaml to enable yamllint checks. Update the 'rev' to your desired release version and specify a custom .yamllint configuration file using the 'args' attribute if needed. ```yaml --- # Update the rev variable with the release version that you want, from the yamllint repo # You can pass your custom .yamllint with args attribute. repos: - repo: https://github.com/adrienverge/yamllint.git rev: v1.29.0 hooks: - id: yamllint args: [--strict, -c=/path/to/.yamllint] ``` -------------------------------- ### Lint all YAML files in a directory Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Run yamllint on all YAML files within the current directory. The '.' argument specifies the current directory. ```bash yamllint . ``` -------------------------------- ### Complex Path Ignoring with Negation Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Demonstrates complex path exclusion and inclusion using .gitignore-style patterns, including negation. This configuration ignores all .dont-lint-me.yaml files and the /bin/ directory, but re-includes files in /bin/ that match *.lint-me-anyway.yaml. ```yaml # For all rules ignore: | *.dont-lint-me.yaml /bin/ !/bin/*.lint-me-anyway.yaml extends: default rules: key-duplicates: ignore: | generated *.template.yaml trailing-spaces: ignore: | *.ignore-trailing-spaces.yaml ascii-art/* ``` -------------------------------- ### Lint YAML content with linter.run() Source: https://context7.com/adrienverge/yamllint/llms.txt Use `linter.run()` to lint YAML content from strings, bytes, or file streams. It returns a generator of `LintProblem` objects. The file is ignored if the config specifies it. ```python from yamllint import linter from yamllint.config import YamlLintConfig conf = YamlLintConfig("extends: default") # Lint from a string yaml_content = """ --- key: value other_key: value other_key: duplicate """ problems = list(linter.run(yaml_content, conf, filepath="example.yaml")) for p in problems: print(f"{p.line}:{p.column} [{p.level}] {p.desc} ({p.rule})") # 2:7 [error] too many spaces after colon (colons) # 2:14 [error] trailing spaces (trailing-spaces) # 4:1 [error] duplication of key "other_key" in mapping (key-duplicates) ``` ```python # Lint from a file stream with open("config.yaml", "rb") as f: for problem in linter.run(f, conf, filepath="config.yaml"): print(repr(problem)) # → 3:1: wrong indentation: expected 2 but found 1 (indentation) ``` -------------------------------- ### Run Yamllint Linter Source: https://github.com/adrienverge/yamllint/blob/master/CONTRIBUTING.rst Validate YAML files for syntax and style errors using yamllint. Run this if you have modified any YAML files. ```bash yamllint --strict $(git ls-files '*.yaml' '*.yml') ``` -------------------------------- ### Lint YAML from standard input Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Pipe YAML content to yamllint using standard input. The '-' argument tells yamllint to read from stdin. ```bash echo -e 'this: is\nvalid: YAML' | yamllint - ``` -------------------------------- ### Run Flake8 Linter Source: https://github.com/adrienverge/yamllint/blob/master/CONTRIBUTING.rst Execute the Flake8 linter to check for Python code style issues. This should be run on all code changes. ```bash flake8 . ``` -------------------------------- ### Ignore Files from External List (Single File) Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Specify a single file (e.g., .gitignore) to read ignore patterns from. This is mutually exclusive with the 'ignore' key. ```yaml ignore-from-file: .gitignore ``` -------------------------------- ### Configure Indentation in Yaml Source: https://context7.com/adrienverge/yamllint/llms.txt Control indentation levels, sequence placement, and multi-line string indentation. Specify the number of spaces per level, whether to indent sequences, and if multi-line strings should be checked. ```yaml extends: default rules: indentation: spaces: 2 # or 4, or 'consistent' (auto-detect from file) indent-sequences: true # true | false | whatever | consistent check-multi-line-strings: false # validate indentation inside multi-line strings ``` ```yaml # PASS with {spaces: 2, indent-sequences: true} list: - item1 - item2 mapping: key: value ``` ```yaml # FAIL with {spaces: 2}: wrong indentation list: - item1 # 3 spaces, expected 2 ``` ```yaml # PASS with {spaces: 2, indent-sequences: false}: sequences at parent level list: - item1 - item2 ``` ```yaml # PASS with {spaces: 2, indent-sequences: consistent}: all sequences same style - flying: - spaghetti - monster - not flying: - spaghetti - sauce ``` -------------------------------- ### Default Configuration Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md The default configuration used by yamllint when no custom file is specified. It enables most rules and sets specific levels for comments and truthy values. ```yaml --- yaml-files: - '*.yaml' - '*.yml' - '.yamllint' rules: anchors: enable braces: enable brackets: enable colons: enable commas: enable comments: level: warning comments-indentation: level: warning document-end: disable document-start: level: warning empty-lines: enable empty-values: disable float-values: disable hyphens: enable indentation: enable key-duplicates: enable key-ordering: disable line-length: enable new-line-at-end-of-file: enable new-lines: enable octal-values: disable quoted-strings: disable trailing-spaces: enable truthy: level: warning ``` -------------------------------- ### Add yamllint as a pre-commit hook Source: https://context7.com/adrienverge/yamllint/llms.txt Integrates yamllint into the pre-commit framework to automatically lint YAML files before each commit. Requires a `.pre-commit-config.yaml` file. ```yaml # .pre-commit-config.yaml repos: - repo: https://github.com/adrienverge/yamllint.git rev: v1.38.0 hooks: - id: yamllint args: [--strict, -c=.yamllint] ``` -------------------------------- ### Run yamllint Linter from Python Source: https://github.com/adrienverge/yamllint/blob/master/docs/development.md Use this snippet to programmatically lint YAML files within your Python applications. It requires importing the yamllint configuration and linter modules. ```python import yamllint.config import yamllint.linter yaml_config = yamllint.config.YamlLintConfig("extends: default") for p in yamllint.linter.run(open("example.yaml", "r"), yaml_config): print(p.desc, p.line, p.rule) ``` -------------------------------- ### Output lint results in parsable format Source: https://github.com/adrienverge/yamllint/blob/master/README.rst Use the '-f parsable' flag to output linting results in a format suitable for integration with editors like Vim or Emacs. ```bash yamllint -f parsable file.yaml ``` -------------------------------- ### Lint a single YAML file Source: https://github.com/adrienverge/yamllint/blob/master/README.rst Basic command to lint a single YAML file. Replace 'my_file.yml' with the actual file name. ```bash yamllint my_file.yml my_other_file.yaml ... ``` -------------------------------- ### Configure yamllint for Arcanist Source: https://github.com/adrienverge/yamllint/blob/master/docs/integration.md This JSON configuration defines a 'yamllint' linter for Arcanist, specifying it as a script-and-regex type. It sets the script to 'yamllint' and provides a regex to parse its output, including line, offset, severity, message, and name. It also includes a filter to only lint files ending in .yml or .yaml. ```json { "linters": { "yamllint": { "type": "script-and-regex", "script-and-regex.script": "yamllint", "script-and-regex.regex": "/^(?P\\d+):(?P\\d+) +(?Pwarning|error) +(?P.*) +\\((?P.*)\\)$/m", "include": "(\\.(yml|yaml)$)" } } } ``` -------------------------------- ### yamllint `braces` Rule Configuration Source: https://context7.com/adrienverge/yamllint/llms.txt Configure the `braces` rule to control the use of flow mappings (`{…}`) and spacing inside them. Options include forbidding flow mappings, and setting minimum/maximum spaces inside braces. ```yaml extends: default rules: braces: forbid: false # true = forbid all flow mappings; 'non-empty' = forbid non-empty ones min-spaces-inside: 1 # require at least 1 space after { and before } max-spaces-inside: 1 # allow at most 1 space min-spaces-inside-empty: 0 # for empty {}: require 0 spaces max-spaces-inside-empty: 0 # for empty {}: allow 0 spaces ``` -------------------------------- ### Ignore Paths Globally (List) Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Use a list of strings to specify paths to ignore globally. Supports glob patterns. ```yaml extends: default ignore: - /this/specific/file.yaml - all/this/directory/ - '*.template.yaml' ``` -------------------------------- ### Configure Syntastic for Vim Source: https://github.com/adrienverge/yamllint/blob/master/docs/text_editors.md Add this configuration to your .vimrc file to enable yamllint as the checker for Syntastic in Vim. ```vim let g:syntastic_yaml_checkers = ['yamllint'] ``` -------------------------------- ### Configure empty-values rule in yamllint Source: https://context7.com/adrienverge/yamllint/llms.txt Prevents implicitly null values in mappings and sequences. Configure which contexts should forbid empty values. ```yaml extends: default rules: empty-values: forbid-in-block-mappings: true # disallow 'key:' with no value forbid-in-flow-mappings: true # disallow '{key: }' with no value forbid-in-block-sequences: true # disallow bare '- ' entries ``` -------------------------------- ### Configure Line Length Limits in Yaml Source: https://context7.com/adrienverge/yamllint/llms.txt Set a maximum line length for YAML files. Options include allowing long non-breakable words (like URLs) and inline mappings, and setting the severity level. ```yaml extends: default rules: line-length: max: 120 allow-non-breakable-words: true # allow long URLs and single tokens allow-non-breakable-inline-mappings: true # allow long inline mapping values level: warning ``` ```yaml # PASS (allow-non-breakable-words: true): long URL is unbreakable this: is: - a: http://localhost/very/very/very/very/very/very/very/long/url ``` ```yaml # FAIL (allow-non-breakable-words: false): line could be split - this line is waaaaaaaaaaaaaay too long but could be easily split into multiple lines here ``` ```yaml # PASS (allow-non-breakable-inline-mappings: true) - foobar: http://localhost/very/very/very/very/very/very/very/very/long/url ``` -------------------------------- ### Python API for yamllint Source: https://context7.com/adrienverge/yamllint/llms.txt Provides a Python function to programmatically lint YAML content using yamllint. It accepts YAML content as a string and returns a list of detected problems. ```python import sys import yamllint.linter from yamllint.config import YamlLintConfig, YamlLintConfigError def lint_yaml(content: str, filepath: str = "") -> list: """Lint YAML content and return a list of (line, col, level, rule, desc) tuples.""" try: conf = YamlLintConfig(""" extends: default rules: line-length: max: 120 level: warning truthy: allowed-values: ['true', 'false'] level: error document-start: disable ") except YamlLintConfigError as e: raise ValueError(f"Invalid yamllint config: {e}") from e problems = [] for p in yamllint.linter.run(content, conf, filepath=filepath): problems.append({ "line": p.line, "column": p.column, "level": p.level, "rule": p.rule, "message": p.message, }) return problems # Example usage yaml_input = """ name: my-app version: "1.0" debug: yes config: host: localhost port: 8080 """ issues = lint_yaml(yaml_input, filepath="config.yaml") has_errors = any(i["level"] == "error" for i in issues) for issue in issues: print(f"{issue['line']}:{issue['column']} [{issue['level']}] {issue['message']}") sys.exit(1 if has_errors else 0) # Output: # 3:8 [error] truthy value should be one of [false, true] (truthy) ``` -------------------------------- ### Ignore Paths Globally (String) Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Use a multi-line string to specify paths to ignore globally. Supports glob patterns. ```yaml extends: default ignore: | /this/specific/file.yaml all/this/directory/ *.template.yaml ``` -------------------------------- ### Relaxed Configuration Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md A pre-defined configuration that is more tolerant than the default. It sets most rules to a warning level and disables comments and truthy checks. ```yaml --- extends: default rules: braces: level: warning max-spaces-inside: 1 brackets: level: warning max-spaces-inside: 1 colons: level: warning commas: level: warning comments: disable comments-indentation: disable document-start: disable empty-lines: level: warning hyphens: level: warning indentation: level: warning indent-sequences: consistent line-length: level: warning allow-non-breakable-inline-mappings: true truthy: disable ``` -------------------------------- ### yamllint `anchors` Rule Configuration Source: https://context7.com/adrienverge/yamllint/llms.txt Configure the `anchors` rule to control detection of undeclared, duplicated, and unused anchors in YAML documents. Set `forbid-undeclared-aliases`, `forbid-duplicated-anchors`, and `forbid-unused-anchors` to `true` to enable checks. ```yaml # .yamllint extends: default rules: anchors: forbid-undeclared-aliases: true # error on *alias with no matching &anchor forbid-duplicated-anchors: true # error when same anchor name declared twice forbid-unused-anchors: true # error when &anchor is declared but never used ``` ```yaml # PASS: anchor declared before alias, used exactly once --- - &defaults timeout: 30 retries: 3 - service1: <<: *defaults port: 8080 # FAIL (forbid-undeclared-aliases): *unknown not declared --- - <<: *unknown extra: value # FAIL (forbid-duplicated-anchors): &anchor used twice --- - &anchor Foo Bar - &anchor [item 1, item 2] # FAIL (forbid-unused-anchors): &anchor declared but never referenced --- - &anchor foo: bar - items: - item1 ``` -------------------------------- ### Configure Spacing Around Colons in Yaml Source: https://context7.com/adrienverge/yamllint/llms.txt Control the number of spaces before and after colons in YAML mappings. Set `max-spaces-before` to 0 to disallow spaces before the colon and `max-spaces-after` to 1 for at most one space after. ```yaml extends: default rules: colons: max-spaces-before: 0 # no spaces allowed before colon (use -1 to disable) max-spaces-after: 1 # at most 1 space after colon ``` ```yaml # PASS: standard key: value key: value other: data ``` ```yaml # FAIL (max-spaces-before: 0): space before colon key : value ``` ```yaml # PASS (max-spaces-after: 2): aligned values first: 1 second: 2 third: 3 ``` -------------------------------- ### Ignore Paths for Specific Rules (List) Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Use a list of strings within a rule's configuration to ignore paths for that specific rule. Supports glob patterns. ```yaml extends: default rules: trailing-spaces: ignore: - /this-file-has-trailing-spaces-but-it-is-OK.yaml - /generated/*.yaml ``` -------------------------------- ### Force colored output Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use the -f colored argument to force colored output, overriding the default behavior which is to only color output when run from a terminal. ```bash yamllint -f colored file.yml ``` -------------------------------- ### Disable All Rules for a Block of Lines in YAML Source: https://github.com/adrienverge/yamllint/blob/master/docs/disable_with_comments.md Use `# yamllint disable` before a block and `# yamllint enable` after it to disable all linting rules for a section of the file. This is generally not recommended but can be useful in specific scenarios. ```yaml # yamllint disable - Lorem : ipsum: dolor : [ sit,amet] - consectetur : adipiscing elit # yamllint enable ``` -------------------------------- ### Wrap Jinja Template Syntax in YAML Comments Source: https://github.com/adrienverge/yamllint/blob/master/docs/disable_with_comments.md To make a Jinja template file valid YAML, wrap Jinja control flow statements within YAML comments (`#`). This allows yamllint to parse the file correctly while preserving the template logic. ```yaml # This file IS valid YAML because the Jinja is in a YAML comment # {% if extra_info %} key1: value1 # {% endif %} key2: value2 ``` -------------------------------- ### Force non-colored output Source: https://github.com/adrienverge/yamllint/blob/master/docs/quickstart.md Use the -f standard argument to force non-colored output, useful when redirecting output to a file or non-terminal environments. ```bash yamllint -f standard file.yml ``` -------------------------------- ### Access LintProblem Attributes Source: https://context7.com/adrienverge/yamllint/llms.txt Iterate through linting results to access attributes of each problem. Attributes include line number, column, severity level, rule ID, and description. ```python for p in linter.run(yaml_content, conf): print(p.line) # int: line number (1-based) print(p.column) # int: column number (1-based) print(p.level) # str: 'warning' or 'error' print(p.rule) # str: rule ID, e.g. 'trailing-spaces' print(p.desc) # str: human-readable description print(p.message) # str: desc + " (rule)" combined print(repr(p)) # str: "line:col: message" ``` -------------------------------- ### Ignore Paths for Specific Rules (String) Source: https://github.com/adrienverge/yamllint/blob/master/docs/configuration.md Use a multi-line string within a rule's configuration to ignore paths for that specific rule. Supports glob patterns. ```yaml extends: default rules: trailing-spaces: ignore: | /this-file-has-trailing-spaces-but-it-is-OK.yaml /generated/*.yaml ``` -------------------------------- ### Disable All Rules for a Specific Line in YAML Source: https://github.com/adrienverge/yamllint/blob/master/docs/disable_with_comments.md Use `# yamllint disable-line` without specifying a rule to disable all checks for a single line. This should be used sparingly as it bypasses all linting. ```yaml # yamllint disable-line - { all : rules ,are disabled for this line} ``` -------------------------------- ### Disable block-specific linting rules Source: https://github.com/adrienverge/yamllint/blob/master/README.rst Use '# yamllint disable rule:rule-name' and '# yamllint enable' comments to disable linting rules for a block of YAML. ```yaml # yamllint disable rule:colons - Lorem : ipsum dolor : sit amet, consectetur : adipiscing elit # yamllint enable ``` -------------------------------- ### Disable Checks for a Block of Lines in YAML Source: https://github.com/adrienverge/yamllint/blob/master/docs/disable_with_comments.md Use `# yamllint disable rule:rule-name` before a block and `# yamllint enable rule:rule-name` after it to disable a specific rule for a section of the file. This is useful for larger code sections with known deviations. ```yaml # yamllint disable rule:colons - Lorem : ipsum dolor : sit amet, consectetur : adipiscing elit # yamllint enable rule:colons - rest of the document... ``` -------------------------------- ### Disable All Checks for an Entire File in YAML Source: https://github.com/adrienverge/yamllint/blob/master/docs/disable_with_comments.md Add `# yamllint disable-file` as the first line of a YAML file to disable all yamllint checks for that file. This is useful for files that are not strictly YAML or have intentional formatting issues. ```yaml # yamllint disable-file # The following mapping contains the same key twice, but I know what I'm doing: - key: value 1 key: value 2 - This line is waaaaaaaaaay too long but yamllint will not report anything about it. ``` -------------------------------- ### Disable All Checks for an Entire File in Jinja Template Source: https://github.com/adrienverge/yamllint/blob/master/docs/disable_with_comments.md Use `# yamllint disable-file` as the first line in a Jinja template file to prevent yamllint from processing it. This is essential when the file contains Jinja syntax that is not valid YAML. ```jinja # yamllint disable-file # This file is not valid YAML because it is a Jinja template {% if extra_info %} key1: value1 {% endif %} key2: value2 ``` -------------------------------- ### Enforce Truthy Values in Yaml Source: https://context7.com/adrienverge/yamllint/llms.txt Prevent non-explicit truthy values that can cause YAML parser surprises. Configure allowed values (e.g., 'true', 'false'), whether to check keys, and the severity level. ```yaml extends: default rules: truthy: allowed-values: ['true', 'false'] # only lowercase true/false allowed check-keys: true # also check mapping keys (not just values) level: error ``` ```yaml # PASS: explicit lowercase boolean enabled: true disabled: false ``` ```yaml # FAIL: non-standard truthy values enabled: yes # error: truthy value should be one of [false, true] disabled: OFF # ``` ```yaml # PASS: explicit type tag bypasses the rule value: !!bool YES ``` ```yaml # PASS: quoted strings are not booleans - "yes" - 'off' ``` ```yaml # PASS: YAML 1.2 document — 'yes'/'on' are not truthy in 1.2 %YAML 1.2 --- yes: 1 on: 2 true: 3 ```