internal/mcp: unify json tag parsing

Do a thorough job of parsing json struct tags.

Move the code to a place where both mcp and jsonschema can use it.

Change-Id: I6c86308834706b12a1e22cd96ae120590f49d3f4
Reviewed-on: https://go-review.googlesource.com/c/tools/+/678757
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Robert Findley <rfindley@google.com>
This commit is contained in:
Jonathan Amsterdam 2025-06-04 09:36:17 -04:00
commit 12761ffcb6

View file

@ -7,7 +7,9 @@ package util
import (
"cmp"
"iter"
"reflect"
"slices"
"strings"
)
// Helpers below are copied from gopls' moremaps package.
@ -34,3 +36,40 @@ func KeySlice[M ~map[K]V, K comparable, V any](m M) []K {
}
return r
}
type JSONInfo struct {
Omit bool // unexported or first tag element is "-"
Name string // Go field name or first tag element. Empty if Omit is true.
Settings map[string]bool // "omitempty", "omitzero", etc.
}
// FieldJSONInfo reports information about how encoding/json
// handles the given struct field.
// If the field is unexported, JSONInfo.Omit is true and no other JSONInfo field
// is populated.
// If the field is exported and has no tag, then Name is the field's name and all
// other fields are false.
// Otherwise, the information is obtained from the tag.
func FieldJSONInfo(f reflect.StructField) JSONInfo {
if !f.IsExported() {
return JSONInfo{Omit: true}
}
info := JSONInfo{Name: f.Name}
if tag, ok := f.Tag.Lookup("json"); ok {
name, rest, found := strings.Cut(tag, ",")
// "-" means omit, but "-," means the name is "-"
if name == "-" && !found {
return JSONInfo{Omit: true}
}
if name != "" {
info.Name = name
}
if len(rest) > 0 {
info.Settings = map[string]bool{}
for _, s := range strings.Split(rest, ",") {
info.Settings[s] = true
}
}
}
return info
}