Skip to content

Commit c62ea8f

Browse files
authored
Add a toggle to disable "omitempty" (#282)
Disable omitempty
1 parent b88cab5 commit c62ea8f

File tree

6 files changed

+37
-1
lines changed

6 files changed

+37
-1
lines changed

pkg/generator/config.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ type Config struct {
1616
OnlyModels bool
1717
MinSizedInts bool
1818
Loader schemas.Loader
19+
// When DisableOmitempty is set to true,
20+
// an "omitempty" tag will never be present in generated struct fields.
21+
// When DisableOmitempty is set to false,
22+
// an "omitempty" tag will be present for all fields that are not required.
23+
DisableOmitempty bool
1924
}
2025

2126
type SchemaMapping struct {

pkg/generator/generate.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,3 +224,7 @@ func (g *Generator) makeEnumConstantName(typeName, value string) string {
224224

225225
return typeName + idv
226226
}
227+
228+
func (g *Generator) DisableOmitempty() bool {
229+
return g.config.DisableOmitempty
230+
}

pkg/generator/schema_generator.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -776,7 +776,7 @@ func (g *schemaGenerator) addStructField(
776776

777777
tags := ""
778778

779-
if isRequired {
779+
if isRequired || g.DisableOmitempty() {
780780
for _, tag := range g.config.Tags {
781781
tags += fmt.Sprintf(`%s:"%s" `, tag, name)
782782
}

tests/data/disableOmitempty/omitempty.go

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"$schema": "http://json-schema.org/draft-07/schema#",
3+
"id": "https://example.com/imported",
4+
"type": "object",
5+
"properties": {
6+
"importedString": {
7+
"type": "string"
8+
}
9+
}
10+
}

tests/generation_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@ func TestCore(t *testing.T) {
3838
testExamples(t, basicConfig, "./data/core")
3939
}
4040

41+
func TestOmitempty(t *testing.T) {
42+
t.Parallel()
43+
44+
cfg := basicConfig
45+
cfg.DisableOmitempty = true
46+
47+
testExamples(t, cfg, "./data/disableOmitempty")
48+
}
49+
4150
func TestValidation(t *testing.T) {
4251
t.Parallel()
4352

0 commit comments

Comments
 (0)