@@ -33,6 +33,14 @@ const (
33
33
jsString = "string"
34
34
)
35
35
36
+ type FieldVisibility int
37
+
38
+ const (
39
+ FieldVisible FieldVisibility = iota
40
+ FieldHide
41
+ FieldIgnore
42
+ )
43
+
36
44
// Generate generates a JSON schema for the given message descriptor.
37
45
func Generate (input protoreflect.MessageDescriptor ) map [protoreflect.FullName ]map [string ]interface {} {
38
46
generator := & jsonSchemaGenerator {
@@ -75,20 +83,28 @@ func (p *jsonSchemaGenerator) generateDefault(result map[string]interface{}, des
75
83
var patternProperties = make (map [string ]interface {})
76
84
for i := range desc .Fields ().Len () {
77
85
field := desc .Fields ().Get (i )
78
- if p .shouldIgnoreField (field ) {
86
+ visibility := p .shouldIgnoreField (field )
87
+ if visibility == FieldIgnore {
79
88
continue
80
89
}
81
90
82
- // Generate the schema
91
+ // Generate the schema.
83
92
fieldSchema := p .generateField (field )
84
93
85
94
// TODO: Add an option to include custom alias.
86
95
aliases := make ([]string , 0 , 1 )
87
96
88
- // TODO: Optionally make the json name the 'primary' name.
89
- properties [string (field .Name ())] = fieldSchema
90
- if field .JSONName () != string (field .Name ()) {
91
- aliases = append (aliases , field .JSONName ())
97
+ if visibility == FieldHide {
98
+ aliases = append (aliases , string (field .Name ()))
99
+ if field .JSONName () != string (field .Name ()) {
100
+ aliases = append (aliases , field .JSONName ())
101
+ }
102
+ } else {
103
+ // TODO: Optionally make the json name the 'primary' name.
104
+ properties [string (field .Name ())] = fieldSchema
105
+ if field .JSONName () != string (field .Name ()) {
106
+ aliases = append (aliases , field .JSONName ())
107
+ }
92
108
}
93
109
94
110
if len (aliases ) > 0 {
@@ -285,9 +301,18 @@ func (p *jsonSchemaGenerator) makeWktGenerators() map[protoreflect.FullName]func
285
301
return result
286
302
}
287
303
288
- func (p * jsonSchemaGenerator ) shouldIgnoreField (fdesc protoreflect.FieldDescriptor ) bool {
304
+ func (p * jsonSchemaGenerator ) shouldIgnoreField (fdesc protoreflect.FieldDescriptor ) FieldVisibility {
289
305
const ignoreComment = "jsonschema:ignore"
306
+ const hideComment = "jsonschema:hide"
290
307
srcLoc := fdesc .ParentFile ().SourceLocations ().ByDescriptor (fdesc )
291
- return strings .Contains (srcLoc .LeadingComments , ignoreComment ) ||
292
- strings .Contains (srcLoc .TrailingComments , ignoreComment )
308
+ switch {
309
+ case strings .Contains (srcLoc .LeadingComments , ignoreComment ),
310
+ strings .Contains (srcLoc .TrailingComments , ignoreComment ):
311
+ return FieldIgnore
312
+ case strings .Contains (srcLoc .LeadingComments , hideComment ),
313
+ strings .Contains (srcLoc .TrailingComments , hideComment ):
314
+ return FieldHide
315
+ default :
316
+ return FieldVisible
317
+ }
293
318
}
0 commit comments