https://github.com/daveshanley/vacuum
vacuum is the worlds fastest and most versatile OpenAPI & JSON Schema linter, docs generator and toolkit. It tears through API specs at light speed. 100% compatible with Spectral rulesets, and OpenAPI 3.0, 3.1 and 3.2
https://github.com/daveshanley/vacuum
go golang json-schema json-schema-validator lint linter linters linting oas openapi openapi-spec openapi-specification openapi3 openapi3-1 openapi3-validation openapi31 owasp spectral stoplight swagger-spec
Last synced: 19 days ago
JSON representation
vacuum is the worlds fastest and most versatile OpenAPI & JSON Schema linter, docs generator and toolkit. It tears through API specs at light speed. 100% compatible with Spectral rulesets, and OpenAPI 3.0, 3.1 and 3.2
- Host: GitHub
- URL: https://github.com/daveshanley/vacuum
- Owner: daveshanley
- License: mit
- Created: 2021-10-10T18:24:19.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2026-06-02T21:39:28.000Z (19 days ago)
- Last Synced: 2026-06-02T23:20:50.077Z (19 days ago)
- Topics: go, golang, json-schema, json-schema-validator, lint, linter, linters, linting, oas, openapi, openapi-spec, openapi-specification, openapi3, openapi3-1, openapi3-validation, openapi31, owasp, spectral, stoplight, swagger-spec
- Language: Go
- Homepage: https://quobix.com/vacuum
- Size: 39.1 MB
- Stars: 1,070
- Watchers: 5
- Forks: 84
- Open Issues: 16
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yaml
- License: LICENSE
- Agents: AGENTS.md
Awesome Lists containing this project
- awesome-go - vacuum - An ultra-super-fast, lightweight OpenAPI linter and quality checking tool. (Code Analysis / Routers)
- awesome-platform-engineering - Vacuum - vacuum is the worlds fastest OpenAPI 3, OpenAPI 2 / Swagger linter and quality analysis tool. Built in go, it tears through API specs faster than you can think. vacuum is compatible with Spectral rulesets and generates compatible reports (API tools / Threat modelling)
- awesome-go - daveshanley/vacuum
- awesome-go - vacuum - An ultra-super-fast, lightweight OpenAPI linter and quality checking tool. (Code Analysis / Routers)
- awesome-go-cn - vacuum - super-fast, lightweight OpenAPI linter and quality checking tool. [![godoc][D]](https://godoc.org/github.com/daveshanley/vacuum) (代码分析 / 路由器)
- awesome-go-plus - vacuum - An ultra-super-fast, lightweight OpenAPI linter and quality checking tool.  (Code Analysis / Routers)
- awesome-go-cn - vacuum - super-fast, lightweight OpenAPI linter and quality checking tool. [![godoc][D]](https://godoc.org/github.com/daveshanley/vacuum) (代码分析 / 路由器)
- awesome-integration - vacuum (⭐1k) - An ultra-fast OpenAPI linter and quality analysis tool, compatible with Spectral rulesets. (Projects / API Design)
- fucking-awesome-go - vacuum - An ultra-super-fast, lightweight OpenAPI linter and quality checking tool. (Code Analysis / Routers)
- awesome-go - vacuum - An ultra-super-fast, lightweight OpenAPI linter and quality checking tool. (Code Analysis / Routers)
- awesome-go-with-stars - vacuum - super-fast, lightweight OpenAPI linter and quality checking tool. | 2026-03-16 | (Code Analysis / Routers)
README

# vacuum - The world's fastest OpenAPI, AsyncAPI and JSON Schema linter.

[](https://goreportcard.com/report/github.com/daveshanley/vacuum)
[](https://discord.gg/UAcUF78MQN)
[](https://pkg.go.dev/github.com/daveshanley/vacuum)
[](https://www.npmjs.com/package/@quobix/vacuum)
[](https://hub.docker.com/r/dshanley/vacuum)
[](https://github.com/avelino/awesome-go)
An **ultra-super-fast**, lightweight OpenAPI, AsyncAPI and JSON Schema linter and quality checking tool, written in golang and inspired by [Spectral](https://github.com/stoplightio/spectral).
It's **fully compatible** with existing [Spectral](https://github.com/stoplightio/spectral) rulesets.
## Install using [homebrew](https://brew.sh) tap
```
brew install daveshanley/vacuum/vacuum
```
## Install using [npm](https://npmjs.com)
```
npm i -g @quobix/vacuum
```
## Install using [yarn](https://yarnpkg.com/)
```
yarn global add @quobix/vacuum
```
## Install using curl
```bash
curl -fsSL https://quobix.com/scripts/install_vacuum.sh | sh
```
### For CI/CD environments
To avoid GitHub API rate limiting in automated environments, set a GitHub token:
```bash
# Using repository token (GitHub Actions)
GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} curl -fsSL https://quobix.com/scripts/install_vacuum.sh | sh
# Using personal access token
GITHUB_TOKEN=your_github_token curl -fsSL https://quobix.com/scripts/install_vacuum.sh | sh
```
#### GitHub Actions example
```yaml
- name: Install vacuum
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Increases rate limit from 60 to 5000 requests/hour
run: |
curl -fsSL https://quobix.com/scripts/install_vacuum.sh | sh
```
> **Note**: The GitHub token prevents intermittent installation failures in CI/CD environments caused by API rate limiting.
> No additional permissions are required, the token only accesses public repository information.
## Install using [Docker](https://hub.docker.com/r/dshanley/vacuum)
The image is available at: https://hub.docker.com/r/dshanley/vacuum
```
docker pull dshanley/vacuum
```
> **Multi-platform support**: Docker images are available for both `linux/amd64` and `linux/arm64` architectures, including native ARM64 support for Apple Silicon Macs.
To run, mount the current working dir to the container and use a relative path to your spec, like so
```
docker run --rm -v $PWD:/work:ro dshanley/vacuum lint
```
Alternatively, you can pull it from
[GitHub packages](https://github.com/daveshanley/vacuum/pkgs/container/vacuum).
To do that, replace `dshanley/vacuum` with `ghcr.io/daveshanley/vacuum` in the above commands.
## Run with Go
If you have Go 1.25 or newer installed, you can use `go run` to build and run it:
```
go run github.com/daveshanley/vacuum@latest lint
```
## Upgrade vacuum
If vacuum was installed with Homebrew, npm, or the shell installer, run:
```bash
vacuum upgrade
```
vacuum will detect the install path and use the matching upgrade mechanism when it can. Normal commands may also show an
update notice when a newer stable release is available. The passive check keeps only a small temporary cache in the OS temp
directory, refreshed at most every 12 hours. Use `--no-update-check` or `VACUUM_NO_UPDATE_CHECK=true` to skip that check.
---
## Sponsors
If your company is using `vacuum`, please consider [supporting this project](https://github.com/sponsors/daveshanley),
like our _very kind_ sponsors, past and present:

[scalar](https://scalar.com)

[apideck](https://apideck.com)
---
## Come chat with us
Need help? Have a question? Want to share your work? [Join our discord](https://discord.gg/UAcUF78MQN) and
come say hi!
## Documentation
🔥 **New in** `v0.29` 🔥: **Lint AsyncAPI 3 documents in vacuum**
[AsyncAPI](https://www.asyncapi.com) is now a first-class document type in vacuum, alongside OpenAPI and JSON Schema.
Use the normal `lint` command and vacuum will detect AsyncAPI 3 documents automatically.
- [Read more about AsyncAPI linting in vacuum](https://quobix.com/vacuum/asyncapi/)
- [See the default AsyncAPI ruleset](https://quobix.com/vacuum/rulesets/asyncapi-recommended/)
- [See every built-in AsyncAPI rule](https://quobix.com/vacuum/rulesets/asyncapi/)
- [Generate an AsyncAPI ruleset](https://quobix.com/vacuum/commands/generate-ruleset/)
- [See the AsyncAPI functions](https://quobix.com/vacuum/functions/asyncapi/)
---
🔥 **New in** `v0.28` 🔥: **Lint JSON Schema documents in vacuum**
A new `schema` command has been added that opens up vacuum to JSON Schema specific linting rules and checks!
With a whole new set of functions and rules, specifically for JSON Schema documents.
Try it out on your own JSON Schema docs! with `vacuum schema`
- [Read more about JSON Schema linting in vacuum](https://quobix.com/vacuum/json-schema/)
- [Read the available `schema` command options](https://quobix.com/vacuum/commands/schema/)
- [See the new recommended JSON Schema ruleset](https://quobix.com/vacuum/rulesets/json-schema-recommended/)
---
`v0.27`: **Generate OpenAPI Documentation in vacuum**
A new `docs` command will generate the **best OpenAPI Documentation you ever saw**! Now vacuum has
integrated with [the printing press](https://github.com/pb33f/printing-press), it means
generating documentation with built-in linting results is available _right inside vacuum_.
Try it out! instead of the `lint` command try the `docs` command instead.
- [Read more about API Docs in vacuum](https://quobix.com/vacuum/api-docs/)
- [Read the `docs` command reference](https://quobix.com/vacuum/commands/docs/)
- [Read more about the printing press](https://pb33f.io/printing-press/)
- [Learn about rendering modes](https://pb33f.io/printing-press/rendering-modes/)
- [Learn about diagnostics mode](https://pb33f.io/printing-press/diagnostics-mode/)
- [Learn about API catalogs](https://pb33f.io/printing-press/api-catalog/)
- [Learn about agentic AI output](https://pb33f.io/printing-press/agentic-ai/)
- [Learn about generated outputs](https://pb33f.io/printing-press/outputs/)
---
`v0.25`: **Generate Open Collections from OpenAPI files**
A new `open-collection` command will generate an [Open Collection](https://www.opencollection.com/) Workflow folder
(or bundled file)
Open Collection is a new standard for defining and sharing API collections. vacuum supports it natively.
[Read More](https://quobix.com/vacuum/commands/open-collection/)
---
`v0.24`: **TURBO MODE**
A huge tune up of hundreds of systems across the stack has resulted in significant speed boosts and improved memory performance.
| Spec | Size | v0.23 | Turbo | Speedup |
|------|------|-------|-------|-----|
| petstore.yaml | 21KB | 0.03s | 0.02s | 33% |
| mistral.yaml | 292KB | 0.17s | 0.10s | 41% |
| neon.yaml | 370KB | 0.21s | 0.08s | 62% |
| ld.yaml | 1.9MB | 0.93s | 0.31s | 67% |
| plaid.yml | 2.9MB | 1.39s | 0.53s | 62% |
| stripe.yaml | 6.1MB | 3.11s | 0.85s | 73% |
The bigger the spec, the faster vacuum runs!
New `-T` flag will enable **turbo mode**. Go ultra-fast!
---
`v0.23`: **OpenAPI Overlay Support**
Ever needed to tweak an OpenAPI spec for different environments without maintaining multiple copies?
Maybe swap out server URLs between dev, staging, and production? Or perhaps strip out internal endpoints before publishing the API docs?
OpenAPI Overlays are the answer. They let us make non-destructive modifications to specs using JSONPath expressions to
target exactly what we want to change. vacuum now supports a new `apply-overlay` command.
- [Learn more about the apply-overlay command](https://quobix.com/vacuum/commands/apply-overlay)
---
`v0.22`: **Async Functions / Promises, Fetch & Batch mode in Custom JS Functions**
Do you want to call remote APIs in your vacuum javascript functions? What about async processing or the ability to use Promises?
vacuum now has its own event loop and will happily support `async` and `await`. Combined with a full implementation of [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
Also added **Batch Mode**. This allows custom functions to receive the entire list of nodes, instead of firing the function
for each result, so you can send all your data off to an API or an LLM, and have the ability parse and process everything at once
vs individually.
- [Read all about async JS functions in vacuum](https://quobix.com/vacuum/api/custom-javascript-functions/#async-functions--promises)
- [Learn about using fetch in vacuum](https://quobix.com/vacuum/api/custom-javascript-functions/#fetch-api)
- [find out how batch mode works](https://quobix.com/vacuum/api/custom-javascript-functions/#batch-mode-processing)
---
### [Quick Start Guide 🚀](https://quobix.com/vacuum/start)
See all the documentation at https://quobix.com/vacuum
- [Installing vacuum](https://quobix.com/vacuum/installing/)
- [About vacuum](https://quobix.com/vacuum/about/)
- [Why should you care?](https://quobix.com/vacuum/why/)
- [Concepts](https://quobix.com/vacuum/concepts/)
- [FAQ](https://quobix.com/vacuum/faq/)
- [Linting AsyncAPI](https://quobix.com/vacuum/asyncapi/)
- [Ignoring lint results](https://quobix.com/vacuum/ignoring/)
- [Generate API Docs](https://quobix.com/vacuum/api-docs/)
- [Linting JSON Schema](https://quobix.com/vacuum/json-schema/)
- [CLI Commands](https://quobix.com/vacuum/commands/)
- [lint](https://quobix.com/vacuum/commands/lint/)
- [vacuum report](https://quobix.com/vacuum/commands/report/)
- [docs](https://quobix.com/vacuum/commands/docs/)
- [dashboard](https://quobix.com/vacuum/commands/dashboard/)
- [html-report](https://quobix.com/vacuum/commands/html-report/)
- [bundle](https://quobix.com/vacuum/commands/bundle/)
- [spectral-report](https://quobix.com/vacuum/commands/spectral-report/)
- [language-server](https://quobix.com/vacuum/commands/language-server/)
- [upgrade](https://quobix.com/vacuum/commands/upgrade/)
- [apply-overlay](https://quobix.com/vacuum/commands/apply-overlay/)
- [schema](https://quobix.com/vacuum/commands/schema/)
- [Change Detection](https://quobix.com/vacuum/commands/change-detection/)
- [open-collection](https://quobix.com/vacuum/commands/open-collection/)
- [generate-ruleset](https://quobix.com/vacuum/commands/generate-ruleset/)
- [version](https://quobix.com/vacuum/commands/version/)
- [External References](https://quobix.com/vacuum/commands/external-references/)
- [Exit Codes](https://quobix.com/vacuum/commands/exit-codes/)
- [Developer API](https://quobix.com/vacuum/api/getting-started/)
- [Using The Index](https://quobix.com/vacuum/api/spec-index/)
- [RuleResultSet](https://quobix.com/vacuum/api/rule-resultset/)
- [Loading a RuleSet](https://quobix.com/vacuum/api/loading-ruleset/)
- [Linting Non-OpenAPI Files](https://quobix.com/vacuum/api/non-openapi/)
- [Custom Golang Functions](https://quobix.com/vacuum/api/custom-functions/)
- [Custom JavaScript Functions](https://quobix.com/vacuum/api/custom-javascript-functions/)
- [Rules](https://quobix.com/vacuum/rules/)
- [Examples](https://quobix.com/vacuum/rules/examples/)
- [Tags](https://quobix.com/vacuum/rules/tags/)
- [Descriptions](https://quobix.com/vacuum/rules/descriptions/)
- [Schemas](https://quobix.com/vacuum/rules/schemas/)
- [Spec Information](https://quobix.com/vacuum/rules/information/)
- [Operations & Paths](https://quobix.com/vacuum/rules/operations/)
- [Channels](https://quobix.com/vacuum/rules/channels/)
- [Messages](https://quobix.com/vacuum/rules/messages/)
- [Servers](https://quobix.com/vacuum/rules/servers/)
- [Validation](https://quobix.com/vacuum/rules/validation/)
- [Security](https://quobix.com/vacuum/rules/security/)
- [OWASP](https://quobix.com/vacuum/rules/owasp/)
- [Functions](https://quobix.com/vacuum/functions/)
- [Core Functions](https://quobix.com/vacuum/functions/core/)
- [OpenAPI Functions](https://quobix.com/vacuum/functions/openapi/)
- [OWASP Functions](https://quobix.com/vacuum/functions/owasp/)
- [AsyncAPI Functions](https://quobix.com/vacuum/functions/asyncapi/)
- [Understanding RuleSets](https://quobix.com/vacuum/rulesets/understanding/)
- [Sharing RuleSets](https://quobix.com/vacuum/rulesets/sharing/)
- [All Rules](https://quobix.com/vacuum/rulesets/all/)
- [No Rules](https://quobix.com/vacuum/rulesets/no-rules/)
- [Recommended Rules](https://quobix.com/vacuum/rulesets/recommended/)
- [AsyncAPI Default Rules](https://quobix.com/vacuum/rulesets/asyncapi-recommended/)
- [AsyncAPI All Rules](https://quobix.com/vacuum/rulesets/asyncapi/)
- [Custom Rules](https://quobix.com/vacuum/rulesets/custom-rulesets/)
---
> **vacuum can suck all the lint of a 5mb API description in milliseconds.**
Designed to reliably lint API descriptions, **very, very quickly**. Including _very large_ ones. Spectral can be quite slow
when used as an API and does not scale for enterprise applications.
vacuum will tell you what is wrong with your spec, why, where, and how to fix it.
vacuum will work at scale and is designed as a CLI (with a web or console UI) and a library to be consumed in other applications.
### Dashboard
vacuum comes with an interactive dashboard (`vacuum dashboard `) allowing you to explore
rules and violations in a console, without having to scroll through thousands of results.

To read about the dashboard, see the [dashboard command docs](https://quobix.com/vacuum/commands/dashboard/).
### HTML Report
vacuum can generate an easy to navigate and understand HTML report. Like the dashboard
you can explore broken rules and violations, but in your browser.
No external dependencies, the HTML report will run completely offline.

---
> **_Supports OpenAPI Version 2, OpenAPI Version 3+, AsyncAPI 3, and JSON Schema documents_**
You can use either **YAML** or **JSON**, vacuum supports both formats.
## Using vacuum with pre-commit
Vacuum can be used with [pre-commit](https://pre-commit.com).
To do that, add to your `.pre-commit-config.yaml`:
```yaml
repos:
- repo: https://github.com/daveshanley/vacuum
rev: # a tag or a commit hash from this repo, see https://github.com/daveshanley/vacuum/releases
hooks:
- id: vacuum
```
See the [hook definition](./.pre-commit-hooks.yaml) here for details on what options the hook uses and what files it checks by default.
If no filenames or more than one filename in your repository matches the default `files` pattern in the hook definition,
the pattern needs to be overridden in your config so that it matches exactly one filename to lint at a time.
To lint multiple files, specify the hook multiple times with the appropriate overrides.
## Build an interactive HTML report
`vacuum html-report` is included in official release binaries. If you install via `go install github.com/daveshanley/vacuum@`, the command is compiled without the HTML report UI bundles. To enable it from source, run `./scripts/build-ui-assets.sh` and build with `-tags html_report_ui`.
```
./vacuum html-report
```
You can replace `report-name.html` with your own choice of filename. Open the report
in your favorite browser and explore the results.
## See full linting report
```
./vacuum lint -d
```
## Lint multiple files at once
```
./vacuum lint -d
```
## Lint multiple files using a glob pattern
```
./vacuum lint -d some/path/**/*.yaml
```
## See full linting report with inline code snippets
```
./vacuum lint -d -s
```
## See just the linting errors
```
./vacuum lint -d -e
```
## See just a specific category of report
```
./vacuum lint -d -c schemas
```
The options here are:
- `examples`
- `operations`
- `information`
- `descriptions`
- `schemas`
- `security`
- `tags`
- `validation`
- `owasp`
## Generate a Spectral compatible report
If you're already using Spectral JSON reports, and you want to use vacuum instead, use the `spectral-report` command
```
./vacuum spectral-report
```
The report file name is _optional_. The default report output name is `vacuum-spectral-report.json`
## Generate a `vacuum report`
Vacuum reports are complete snapshots in time of a linting report for a specification. These reports can be 'replayed'
back through vacuum. Use the `dashboard` or the `html-report` commands to 'replay' the report and explore the results
as they were when the report was generated.
```
./vacuum report -c
```
The default name of the report will be `vacuum-report-MM-DD-YY-HH_MM_SS.json`. You can change the prefix by supplying
it as the second argument to the `report` command.
Ideally, **you should compress the report using `-c`**. This shrinks down the size significantly. vacuum automatically
recognizes a compressed report file and will deal with it automatically when reading.
> When using compression, the file name will be `vacuum-report-MM-DD-YY-HH_MM_SS.json.gz`. vacuum uses gzip internally.
## Ignoring specific linting errors
You can ignore specific linting errors by providing an `--ignore-file` argument to commands that run or replay lint results, including `lint`, `report`, `spectral-report`, `html-report`, `dashboard`, and `docs`.
```
./vacuum lint --ignore-file -d
```
```
./vacuum report --ignore-file -c
```
The ignore-file should point to a `.yaml` file that contains exact result paths or JSONPath expressions to be ignored by vacuum. The structure of the YAML file is as follows:
```
:
-
-
:
-
-
...
```
Ignoring errors is useful for when you want to implement new rules to existing production APIs. In some cases,
correcting the lint errors would result in a breaking change. Having a way to ignore these errors allows you to implement
the new rules for new APIs while maintaining backwards compatibility for existing ones.
---
## Try out the dashboard
This is an early, but working console UI for vacuum. The code isn't great, it needs a lot of clean up, but
if you're interested in seeing how things are progressing, it's available.
```
./vacuum dashboard
```
---
## Supply your own Spectral compatible ruleset
If you're already using Spectral and you have your own [custom ruleset](https://meta.stoplight.io/docs/spectral/e5b9616d6d50c-custom-rulesets#custom-rulesets),
then you can use it with vacuum!
The `lint`, `dashboard`, `docs`, `html-report`, `report`, and `spectral-report` commands all accept a `-r` or `--ruleset` flag, defining the path to your ruleset file.
### Here are some examples you can try
**_All rules turned off_**
```
./vacuum lint -r rulesets/examples/norules-ruleset.yaml
```
**_Only recommended rules_**
```
./vacuum lint -r rulesets/examples/recommended-ruleset.yaml
```
**_Enable specific rules only_**
```
./vacuum lint -r rulesets/examples/specific-ruleset.yaml
```
**_Custom rules_**
```
./vacuum lint -r rulesets/examples/custom-ruleset.yaml
```
**_All rules, all of them!_**
```
./vacuum lint -r rulesets/examples/all-ruleset.yaml
```
---
## Reference resolution in rules
vacuum has two resolved-execution controls:
- Per rule: `resolved`
- Per run: `--resolve-all-refs` or `motor.ExecutionOptions{ResolveAllRefs: true}`
In YAML/JSON rulesets, `resolved` defaults to `true`. In that mode, `given`, matched nodes, `Index`, and `SpecInfo` come from the dereferenced document, but `context.Document` stays unresolved for compatibility.
Set `resolved: false` when a rule needs the raw document, for example to inspect `$ref` directly. If you build `model.Rule` values in Go, set `Resolved` explicitly.
```yaml
rules:
response-has-content:
given: "$.paths[*][*].responses['404']"
resolved: false
then:
field: content
function: defined
```
`--resolve-all-refs` forces every rule into resolved execution, overrides `resolved: false`, and also supplies resolved `context.Document` to rule functions.
Use `--nested-refs-doc-context` or `motor.ExecutionOptions{NestedRefsDocContext: true}` for split specs where an external file contains another relative `$ref`. That makes nested relative refs resolve from the referenced document instead of the root document. It only affects resolved execution, including runs forced by `--resolve-all-refs`.
---
## Configuration
### File
You can configure vacuum using a configuration file named `vacuum.conf.yaml`
By default, vacuum searches for this file in the following locations:
1. Working directory
2. `$XDG_CONFIG_HOME`, when set
3. `${HOME}/.config`, when `$XDG_CONFIG_HOME` is not set
You can also specify a path to a file using the `--config` flag
Global flags are configured as top level nodes
```yaml
time: true
base: 'http://example.com'
...
```
Command specific flags are configured under a node with the commands name
```yaml
...
lint:
silent: true
...
```
### Environment variables
You can configure global vacuum flags using environment variables in the form of: `VACUUM_`
If a flag, has a `-` in it, replace with `_`
## Auto-fixing rule violations
If you have a rule that doesn't need a human to look at it, and the change can be reliably automated you can configure an `AutoFixFunction` on the rule. When you then run the `lint` command you can pass the `--fix` flag and the violation will be automatically fixed.
### Set up
1. Define a rule that has an `autoFixFunction`, e.g.:
```yaml
rules:
use-compatible-extensions:
autoFixFunction: useExtensibleEnum
description: Prefer compatible extensions
id: use-compatible-extensions
given: "$.components.schemas[?@.enum]"
severity: warn
message: Use x-extensible-enum instead of enum for better compatibility
then:
field: enum
function: falsy
```
This rule flags any usage of `enum` and recommends they are updated to `x-extensible-enum`.
A simple change which can be easily auto fixed!
2. Create a function which performs the auto-fix.
```go
func useExtensibleEnum(
node *yaml.Node,
document *yaml.Node,
context *model.RuleFunctionContext,
) (*yaml.Node, error) {
if node.Kind != yaml.MappingNode {
return node, nil
}
for i := 0; i < len(node.Content); i += 2 {
if i+1 >= len(node.Content) {
break
}
keyNode := node.Content[i]
if keyNode.Value == "enum" {
keyNode.Value = "x-extensible-enum"
return node, nil
}
}
return node, nil
}
```
> [!NOTE]
> The auto fix function must satisfy the `AutoFixFunction` type.
> It should take in the `*yaml.Node` of the violation, the root `*yaml.Node` of the document and the `RuleFunctionContext`.
> It should return the fixed `*yaml.Node` and an error.
3. Configure your `RuleSetExecution` to use the auto fix function.
```go
func Lint(rulesFile string, specFile string) error {
rules, err := rulesets.LoadLocalRuleSet(ctx, rulesFile)
if err != nil {
return fmt.Errorf("error loading ruleset: %w", err)
}
rs := rulesets.BuildDefaultRuleSetsWithLogger(slog.Logger).
GenerateRuleSetFromSuppliedRuleSet(rules)
// NOTE: only showing the fields on the RuleSetExecution relevant to auto-fixing.
results := motor.ApplyRulesToRuleSet(&motor.RuleSetExecution{
AutoFixFunctions: map[string]model.AutoFixFunction{
"useExtensibleEnum": useExtensibleEnum,
},
ApplyAutoFixes: true,
RuleSet: rs,
})
// Write back to file if fixes were applied
if len(lintResults.FixedResults) > 0 && autoFix {
fileInfo, _ := os.Stat(specFile)
err = os.WriteFile(specFile, result.ModifiedSpec, fileInfo.Mode())
if err != nil {
return fmt.Errorf("failed to write file %s: %w", c.file, err)
}
}
return nil
}
```
When the auto fix function runs, if it returns an error the fix will not be applied, the error will be logged, and the violation will be reported in the standard results.
If the auto fix function succeeds the yaml node flagged by the violation will be replaced with the transformed version returned by the auto fix function.
> [!TIP]
> When using `vacuum` as a library You can access the fixed yaml content in the `RuleSetExecutionResult.ModifiedSpec`, and choose where to write the file.
>
> When using `vacuum` as a cli, the `--fix` flag will overwrite the spec file in place, and `--fix-file` flag lets you specify an alternative file to write the content to, if you want to compare the outputs.
### Usage
> Logo gopher is modified, originally from [egonelbre](https://github.com/egonelbre/gophers)