Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

config: Add TFLint required_version settings #2027

Merged
merged 1 commit into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/user-guide/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ You can change the behavior not only in CLI flags but also in config files. TFLi
The config file is written in [HCL](https://github.com/hashicorp/hcl). An example is shown below:

```hcl
tflint {
required_version = ">= 0.50"
}

config {
format = "compact"
plugin_dir = "~/.tflint.d/plugins"
Expand Down Expand Up @@ -44,6 +48,11 @@ The file path is resolved relative to the module directory when `--chdir` or `--
tflint --recursive --config "$(pwd)/.tflint.hcl"
```

### `required_version`

Restrict the TFLint version used. This is almost the same as [Terraform's `required_version`](https://developer.hashicorp.com/terraform/language/settings#specifying-a-required-terraform-version).
You can write version constraints in the same way.

### `format`

CLI flag: `--format`
Expand Down
89 changes: 89 additions & 0 deletions tflint/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"strings"

"github.com/hashicorp/go-version"
hcl "github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclparse"
Expand All @@ -22,6 +23,9 @@ var fallbackConfigFile = "~/.tflint.hcl"

var configSchema = &hcl.BodySchema{
Blocks: []hcl.BlockHeaderSchema{
{
Type: "tflint",
},
{
Type: "config",
},
Expand Down Expand Up @@ -210,6 +214,10 @@ func loadConfig(file afero.File) (*Config, error) {
return nil, diags
}

if diags := checkVersionRequirement(f.Body); diags.HasErrors() {
return nil, diags
}

content, diags := f.Body.Content(configSchema)
if diags.HasErrors() {
return nil, diags
Expand All @@ -219,6 +227,9 @@ func loadConfig(file afero.File) (*Config, error) {
config.sources = parser.Sources()
for _, block := range content.Blocks {
switch block.Type {
case "tflint":
// The "tflint" block is already handled by checkVersionRequirement and is therefore ignored

case "config":
inner, diags := block.Body.Content(innerConfigSchema)
if diags.HasErrors() {
Expand Down Expand Up @@ -362,6 +373,84 @@ func loadConfig(file afero.File) (*Config, error) {
return config, nil
}

// checkVersionRequirement checks whether the TFLint version satisfy the "required_version".
// At the time of this check, we do not know if other schema meet our requirements,
// so we only extract the minimal schema. Note that it therefore needs to be independent of loadConfig.
func checkVersionRequirement(body hcl.Body) hcl.Diagnostics {
content, _, diags := body.PartialContent(&hcl.BodySchema{
Blocks: []hcl.BlockHeaderSchema{
{Type: "tflint"},
},
})
if diags.HasErrors() {
return diags
}

if len(content.Blocks) == 0 {
return nil
}
if len(content.Blocks) > 1 {
return hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: `Multiple "tflint" blocks are not allowed`,
Detail: fmt.Sprintf(`The "tflint" block is already found in %s, but found the second one.`, content.Blocks[0].DefRange),
Subject: content.Blocks[1].DefRange.Ptr(),
},
}
}
block := content.Blocks[0]

inner, _, diags := block.Body.PartialContent(&hcl.BodySchema{
Attributes: []hcl.AttributeSchema{
{Name: "required_version"},
},
})
if diags.HasErrors() {
return diags
}

versionAttr, exists := inner.Attributes["required_version"]
if !exists {
return nil
}
var requiredVersion string
if err := gohcl.DecodeExpression(versionAttr.Expr, nil, &requiredVersion); err != nil {
return hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: `Failed to decode "required_version" attribute`,
Detail: err.Error(),
Subject: versionAttr.Expr.Range().Ptr(),
},
}
}
constraints, err := version.NewConstraint(requiredVersion)
if err != nil {
return hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: `Failed to parse "required_version" attribute`,
Detail: err.Error(),
Subject: versionAttr.Expr.Range().Ptr(),
},
}
}

if !constraints.Check(Version) {
return hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Unsupported TFLint version",
Detail: fmt.Sprintf(`This config does not support the currently used TFLint version %s. Please update to another supported version or change the version requirement.`, Version),
Subject: versionAttr.Expr.Range().Ptr(),
},
}
}

return nil
}

// Enable the "recommended" preset if the bundled plugin is automatically enabled.
var bundledPluginConfigFilename = "__bundled_plugin_config.hcl"
var bundledPluginConfigContent = `
Expand Down
47 changes: 47 additions & 0 deletions tflint/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tflint

import (
"errors"
"fmt"
"os"
"testing"

Expand Down Expand Up @@ -32,6 +33,10 @@ func TestLoadConfig(t *testing.T) {
file: "config.hcl",
files: map[string]string{
"config.hcl": `
tflint {
required_version = ">= 0"
}

config {
format = "compact"
plugin_dir = "~/.tflint.d/plugins"
Expand Down Expand Up @@ -440,6 +445,48 @@ config {
},
errCheck: neverHappend,
},
{
name: "valid required_version",
file: "config.hcl",
files: map[string]string{
"config.hcl": `
tflint {
required_version = ">= 0.50"
}`,
},
want: EmptyConfig().enableBundledPlugin(),
errCheck: neverHappend,
},
{
name: "invalid required_version",
file: "config.hcl",
files: map[string]string{
"config.hcl": `
tflint {
required_version = "< 0.50"
}`,
},
errCheck: func(err error) bool {
return err == nil || err.Error() != fmt.Sprintf(`config.hcl:3,22-30: Unsupported TFLint version; This config does not support the currently used TFLint version %s. Please update to another supported version or change the version requirement.`, Version)
},
},
{
name: "multiple required_versions",
file: "config.hcl",
files: map[string]string{
"config.hcl": `
tflint {
required_version = ">= 0.50"
}

tflint {
required_version = "< 0.50"
}`,
},
errCheck: func(err error) bool {
return err == nil || err.Error() != `config.hcl:6,1-7: Multiple "tflint" blocks are not allowed; The "tflint" block is already found in config.hcl:2,1-7, but found the second one.`
},
},
}

for _, test := range tests {
Expand Down
Loading