Skip to content

Commit 0c23a88

Browse files
committed
new linter: defaults
Signed-off-by: sivchari <shibuuuu5@gmail.com>
1 parent d3015c9 commit 0c23a88

File tree

25 files changed

+1453
-3
lines changed

25 files changed

+1453
-3
lines changed

docs/linters.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
- [CommentStart](#commentstart) - Ensures comments start with the serialized form of the type
66
- [ConflictingMarkers](#conflictingmarkers) - Detects mutually exclusive markers on the same field
77
- [DefaultOrRequired](#defaultorrequired) - Ensures fields marked as required do not have default values
8+
- [Defaults](#defaults) - Checks that fields with default markers are configured correctly
89
- [DuplicateMarkers](#duplicatemarkers) - Checks for exact duplicates of markers
910
- [DependentTags](#dependenttags) - Enforces dependencies between markers
1011
- [ForbiddenMarkers](#forbiddenmarkers) - Checks that no forbidden markers are present on types/fields.
@@ -212,6 +213,45 @@ The linter also detects conflicts with:
212213

213214
This linter is enabled by default and helps ensure that API designs are consistent and unambiguous about whether fields are truly required or have default values.
214215

216+
## Defaults
217+
218+
The `defaults` linter checks that fields with default markers are configured correctly.
219+
220+
Fields with default markers (`+default`, `+kubebuilder:default`, or `+k8s:default`) should also be marked as optional.
221+
Additionally, fields with default markers should have `omitempty` or `omitzero` in their json tags to ensure that
222+
the default values are applied correctly during serialization and deserialization.
223+
224+
### Example
225+
226+
A well-configured field with a default:
227+
228+
```go
229+
type MyStruct struct {
230+
// +optional
231+
// +default="default-value"
232+
Field string `json:"field,omitempty"`
233+
}
234+
```
235+
236+
The following issues will be flagged by the linter:
237+
238+
```go
239+
type MyStruct struct {
240+
// Missing optional marker
241+
// +default="value"
242+
Field1 string `json:"field1,omitempty"` // Error: has default but not marked as optional
243+
244+
// Missing omitempty tag
245+
// +optional
246+
// +default="value"
247+
Field2 string `json:"field2"` // Error: has default but no omitempty or omitzero
248+
}
249+
```
250+
251+
### Fixes
252+
253+
The `defaults` linter can automatically add `omitempty,omitzero` to the json tag when missing.
254+
215255
## DuplicateMarkers
216256

217257
The duplicatemarkers linter checks for exact duplicates of markers for types and fields.

0 commit comments

Comments
 (0)