Skip to content
This repository was archived by the owner on Dec 27, 2024. It is now read-only.

Commit 43c19fa

Browse files
committed
feat: string/int64 validator OneOfWithDescriptionIfAttributeIsOneOf
1 parent ccc6199 commit 43c19fa

19 files changed

+630
-50
lines changed

.golangci.yml

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,33 @@
1-
# Visit https://golangci-lint.run/ for usage documentation
2-
# and information on other useful linters
3-
issues:
4-
max-per-linter: 0
5-
max-same-issues: 0
61

72
linters:
83
enable:
94
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers [fast: true, auto-fix: false]
105
- bidichk # Checks for dangerous unicode character sequences [fast: true, auto-fix: false]
11-
- deadcode # Finds unused code [fast: false, auto-fix: false]
126
- decorder # check declaration order and count of types, constants, variables and functions [fast: true, auto-fix: false]
137
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) [fast: true, auto-fix: false]
148
- durationcheck # check for two durations multiplied together [fast: false, auto-fix: false]
159
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases [fast: false, auto-fix: false]
1610
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. [fast: false, auto-fix: false]
1711
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. [fast: false, auto-fix: false]
18-
- execinquery # execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds [fast: false, auto-fix: false]
19-
- exportloopref # checks for pointers to enclosing loop variables [fast: false, auto-fix: false]
12+
- copyloopvar # Checks for loop variables that are used in a closure [fast: true, auto-fix: false]
2013
- forbidigo # Forbids identifiers [fast: true, auto-fix: false]
2114
- gci # Gci controls golang package import order and makes it always deterministic. [fast: true, auto-fix: false]
22-
- goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false]
2315
- gocritic # Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false]
2416
- gocyclo # Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false]
2517
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true]
2618
- goheader # Checks is file header matches to pattern [fast: true, auto-fix: false]
2719
- gofumpt # Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true]
28-
- goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. [fast: true, auto-fix: true]
2920
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. [fast: true, auto-fix: false]
3021
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. [fast: true, auto-fix: false]
3122
- goprintffuncname # Checks that printf-like functions are named with `f` at the end [fast: true, auto-fix: false]
3223
- gosec #(gas): Inspects source code for security problems [fast: false, auto-fix: false]
3324
- gosimple #(megacheck): Linter for Go source code that specializes in simplifying a code [fast: false, auto-fix: false]
3425
- govet #(vet, vetshadow): Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: false, auto-fix: false]
3526
- grouper # An analyzer to analyze expression groups. [fast: true, auto-fix: false]
36-
- ifshort # Checks that your code uses short syntax for if-statements whenever possible [fast: true, auto-fix: false]
3727
- importas # Enforces consistent import aliases [fast: false, auto-fix: false]
3828
- ineffassign # Detects when assignments to existing variables are not used [fast: true, auto-fix: false]
3929
- makezero # Finds slice declarations with non-zero initial length [fast: false, auto-fix: false]
4030
- misspell # Finds commonly misspelled English words in comments [fast: true, auto-fix: true]
41-
- nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false]
4231
- nilerr # Finds the code that returns nil even if it checks that the error is not nil. [fast: false, auto-fix: false]
4332
- noctx # noctx finds sending http request without context.Context [fast: false, auto-fix: false]
4433
- nolintlint # Reports ill-formed or insufficient nolint directives [fast: true, auto-fix: false]
@@ -48,40 +37,41 @@ linters:
4837
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false]
4938
- rowserrcheck # checks whether Err of rows is checked successfully [fast: false, auto-fix: false]
5039
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. [fast: false, auto-fix: false]
51-
- structcheck # Finds unused struct fields [fast: false, auto-fix: false]
5240
- stylecheck # Stylecheck is a replacement for golint [fast: false, auto-fix: false]
5341
- tagliatelle # Checks the struct tags. [fast: true, auto-fix: false]
5442
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 [fast: false, auto-fix: false]
5543
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes [fast: false, auto-fix: false]
5644
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code [fast: false, auto-fix: false]
5745
- unconvert # Remove unnecessary type conversions [fast: false, auto-fix: false]
58-
- varcheck # Finds unused global variables and constants [fast: false, auto-fix: false]
5946
- wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false]
6047
- whitespace # Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true]
48+
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. [fast: false, auto-fix: false]
49+
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false]
50+
- godot # Check if comments end in a period [fast: true, auto-fix: true]
51+
- unused #(megacheck): Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false]
52+
- unparam # reports unused function parameters
53+
- staticcheck #(megacheck): Staticcheck is a go vet on steroids, applying a ton of static analysis checks [fast: false, auto-fix: false]
54+
- bodyclose # checks whether HTTP response body is closed successfully
55+
- goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false]
6156

6257
disable:
63-
- depguard # Go linter that checks if package imports are in a list of acceptable packages [fast: true, auto-fix: false]
6458
- dupl # Tool for code clone detection [fast: true, auto-fix: false]
59+
- nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false]
60+
- depguard # Go linter that checks if package imports are in a list of acceptable packages [fast: true, auto-fix: false]
61+
- goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. [fast: true, auto-fix: true]
6562
- containedctx # containedctx is a linter that detects struct contained context.Context field [fast: true, auto-fix: false]
6663
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers [fast: false, auto-fix: false]
6764
- cyclop # checks function and package cyclomatic complexity [fast: false, auto-fix: false]
68-
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. [fast: false, auto-fix: false]
6965
- exhaustive # check exhaustiveness of enum switch statements [fast: false, auto-fix: false]
7066
- funlen # Tool for detection of long functions [fast: true, auto-fix: false]
7167
- gochecknoglobals # check that no global variables exist [fast: true, auto-fix: false]
7268
- gochecknoinits # Checks that no init functions are present in Go code [fast: true, auto-fix: false]
7369
- gocognit # Computes and checks the cognitive complexity of functions [fast: true, auto-fix: false]
74-
- godot # Check if comments end in a period [fast: true, auto-fix: true]
7570
- godox # Tool for detection of FIXME, TODO and other comment keywords [fast: true, auto-fix: false]
76-
- goerr113 # Golang linter to check the errors handling expressions [fast: false, auto-fix: false]
77-
- gomnd # An analyzer to detect magic numbers. [fast: true, auto-fix: false]
7871
- lll # Reports long lines [fast: true, auto-fix: false]
7972
- maintidx # maintidx measures the maintainability index of each function. [fast: true, auto-fix: false]
8073
- nestif # Reports deeply nested if statements [fast: true, auto-fix: false]
81-
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false]
8274
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity [fast: true, auto-fix: false]
83-
- staticcheck #(megacheck): Staticcheck is a go vet on steroids, applying a ton of static analysis checks [fast: false, auto-fix: false]
84-
- unused #(megacheck): Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false]
8575
- varnamelen # checks that the length of a variable's name matches its scope [fast: false, auto-fix: false]
8676
- wrapcheck # Checks that errors returned from external packages are wrapped [fast: false, auto-fix: false]
8777
- wsl # Whitespace Linter - Forces you to use empty lines! [fast: true, auto-fix: false]
@@ -140,6 +130,4 @@ linters-settings:
140130
allow:
141131
- $gostd
142132
- github.com/hashicorp
143-
- github.com/FrangipaneTeam
144-
# Packages that are not allowed where the value is a suggestion.
145-
deny:
133+
- github.com/FrangipaneTeam

boolvalidator/require_if_attribute_is_set.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"github.com/FrangipaneTeam/terraform-plugin-framework-validators/internal"
88
)
99

10-
// RequireIfAttributeIsSet checks if the path.Path attribute is set
10+
// RequireIfAttributeIsSet checks if the path.Path attribute is set.
1111
func RequireIfAttributeIsSet(path path.Expression) validator.Bool {
1212
return internal.RequireIfAttributeIsSet{
1313
PathExpression: path,
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# `OneOfWithDescription`
2+
3+
!!! quote inline end "Released in v1.9.0"
4+
5+
This validator is used to check if the string is one of the given values if the attribute is one of and format the description and the markdown description.
6+
7+
## How to use it
8+
9+
```go
10+
// Schema defines the schema for the resource.
11+
func (r *xResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
12+
resp.Schema = schema.Schema{
13+
(...)
14+
"foo": schema.StringAttribute{
15+
Optional: true,
16+
MarkdownDescription: "foo ...",
17+
Validators: []validator.String{
18+
fstringvalidator.OneOf("VM_NAME", "VM_TAGS"),
19+
},
20+
},
21+
"bar": schema.StringAttribute{
22+
Optional: true,
23+
MarkdownDescription: "bar of ...",
24+
Validators: []validator.String{
25+
fstringvalidator.OneOfWithDescriptionIfAttributeIsOneOf(
26+
path.MatchRelative().AtParent().AtName("foo"),
27+
[]attr.Value{types.StringValue("VM_NAME")},
28+
func() []fstringvalidator.OneOfWithDescriptionIfAttributeIsOneOfValues {
29+
return []fstringvalidator.OneOfWithDescriptionIfAttributeIsOneOfValues{
30+
{
31+
Value: "CONTAINS",
32+
Description: "The `value` must be contained in the VM name.",
33+
},
34+
{
35+
Value: "STARTS_WITH",
36+
Description: "The VM name must start with the `value`.",
37+
},
38+
{
39+
Value: "ENDS_WITH",
40+
Description: "The VM name must end with the `value`.",
41+
},
42+
{
43+
Value: "EQUALS",
44+
Description: "The VM name must be equal to the `value`.",
45+
},
46+
}
47+
}()...),
48+
},
49+
},
50+
```
51+
52+
## Description and Markdown description
53+
54+
* **Description:**
55+
If the value of attribute <.type is "VM_NAME" the allowed values are : "CONTAINS" (The `value` must be contained in the VM name.), "STARTS_WITH" (The VM name must start with the `value`.), "ENDS_WITH" (The VM name must end with the `value`.), "EQUALS" (The VM name must be equal to the `value`.)
56+
* **Markdown description:**
57+
58+
![oneofwithdescriptionifattributeisoneof](oneofwithdescriptionifattributeisoneof.png)
34 KB
Loading

docs/int64validator/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
- [`NullIfAttributeIsOneOf`](../common/null_if_attribute_is_one_of.md) - This validator is used to verify the attribute value is null if another attribute is one of the given values.
1919
- [`NullIfAttributeIsSet`](../common/null_if_attribute_is_set.md) - This validator is used to verify the attribute value is null if another attribute is set.
2020
- [`OneOfWithDescription`](oneofwithdescription.md) - This validator is used to check if the string is one of the given values and format the description and the markdown description.
21+
- [`OneOfWithDescriptionIfAttributeIsOneOf`](../common/oneofwithdescriptionifattributeisoneof.md) - This validator is used to check if the string is one of the given values if the attribute is one of and format the description and the markdown description.
2122
- [`AttributeIsDivisibleByAnInteger`](attribute_is_divisible_by_an_integer.md) - This validator is used to validate that the attribute is divisible by an integer.
2223
- [`ZeroRemainder`](zero_remainder.md) - This validator checks if the configured attribute is divisible by a specified integer X, and has zero remainder.
2324

docs/stringvalidator/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
- [`NullIfAttributeIsOneOf`](../common/null_if_attribute_is_one_of.md) - This validator is used to verify the attribute value is null if another attribute is one of the given values.
1919
- [`NullIfAttributeIsSet`](../common/null_if_attribute_is_set.md) - This validator is used to verify the attribute value is null if another attribute is set.
2020
- [`OneOfWithDescription`](oneofwithdescription.md) - This validator is used to check if the string is one of the given values and format the description and the markdown description.
21+
- [`OneOfWithDescriptionIfAttributeIsOneOf`](../common/oneofwithdescriptionifattributeisoneof.md) - This validator is used to check if the string is one of the given values if the attribute is one of and format the description and the markdown description.
2122

2223
### Network
2324

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package int64validator
2+
3+
import (
4+
"github.com/hashicorp/terraform-plugin-framework/attr"
5+
"github.com/hashicorp/terraform-plugin-framework/path"
6+
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
7+
"github.com/hashicorp/terraform-plugin-framework/types"
8+
9+
"github.com/FrangipaneTeam/terraform-plugin-framework-validators/internal"
10+
)
11+
12+
type OneOfWithDescriptionIfAttributeIsOneOfValues struct {
13+
Value int64
14+
Description string
15+
}
16+
17+
// OneOfWithDescriptionIfAttributeIsOneOf checks that the value is one of the expected values if the attribute is one of the exceptedValue.
18+
// The description of the value is used to generate advanced
19+
// Description and MarkdownDescription messages.
20+
func OneOfWithDescriptionIfAttributeIsOneOf(path path.Expression, exceptedValue []attr.Value, values ...OneOfWithDescriptionIfAttributeIsOneOfValues) validator.String {
21+
frameworkValues := make([]internal.OneOfWithDescriptionIfAttributeIsOneOf, 0, len(values))
22+
23+
for _, v := range values {
24+
frameworkValues = append(frameworkValues, internal.OneOfWithDescriptionIfAttributeIsOneOf{
25+
Value: types.Int64Value(v.Value),
26+
Description: v.Description,
27+
})
28+
}
29+
30+
return internal.OneOfWithDescriptionIfAttributeIsOneOfValidator{
31+
Values: frameworkValues,
32+
ExceptedValues: exceptedValue,
33+
PathExpression: path,
34+
}
35+
}

int64validator/require_if_attribute_is_set.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"github.com/FrangipaneTeam/terraform-plugin-framework-validators/internal"
88
)
99

10-
// RequireIfAttributeIsSet checks if the path.Path attribute is set
10+
// RequireIfAttributeIsSet checks if the path.Path attribute is set.
1111
func RequireIfAttributeIsSet(path path.Expression) validator.Int64 {
1212
return internal.RequireIfAttributeIsSet{
1313
PathExpression: path,

internal/one_of_with_description.go

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -75,18 +75,6 @@ func (v OneOfWithDescriptionValidator) MarkdownDescription(_ context.Context) st
7575
return fmt.Sprintf("%s %s", oneOfWithDescriptionValidatorDescription, valuesDescription)
7676
}
7777

78-
func (v OneOfWithDescriptionValidator) valuesDescription(_ context.Context) string {
79-
var valuesDescription string
80-
for i, value := range v.Values {
81-
if i == len(v.Values)-1 {
82-
valuesDescription += fmt.Sprintf("%s (%s)", value.Value.String(), value.Description)
83-
break
84-
}
85-
valuesDescription += fmt.Sprintf("%s (%s), ", value.Value.String(), value.Description)
86-
}
87-
return valuesDescription
88-
}
89-
9078
func (v OneOfWithDescriptionValidator) Validate(ctx context.Context, req OneOfWithDescriptionValidatorRequest, res *OneOfWithDescriptionValidatorResponse) {
9179
// If attribute configuration is not null or unknown, there is nothing else to validate
9280
if req.ConfigValue.IsNull() || req.ConfigValue.IsUnknown() || len(v.Values) == 0 {

0 commit comments

Comments
 (0)