Debian Codegraph @

parser/lowercase_camel_json.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package parser
15
16 import (
17 "bytes"
18 "encoding/json"
19 "regexp"
20 "unicode"
21 "unicode/utf8"
22
23 "github.com/gohugoio/hugo/common/hreflect"
24 )
25
26 // Regexp definitions
27 var (
28 keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`)
29 nullEnableBoolRegex = regexp.MustCompile(`\"(enable\w+)\":null`)
30 nullLineNosRegex = regexp.MustCompile(`\"(lineNos)\":null`)
31 )
32
33 type NullBoolJSONMarshaller struct {
34 Wrapped json.Marshaler
35 }
36
37 func (c NullBoolJSONMarshaller) MarshalJSON() ([]byte, error) {
38 b, err := c.Wrapped.MarshalJSON()
39 if err != nil {
40 return nil, err
41 }
42 b = nullEnableBoolRegex.ReplaceAll(b, []byte(`"$1": false`))
43 b = nullLineNosRegex.ReplaceAll(b, []byte(`"$1": false`))
44 return b, nil
45 }
46
47 // Code adapted from https://gist.github.com/piersy/b9934790a8892db1a603820c0c23e4a7
48 type LowerCaseCamelJSONMarshaller struct {
49 Value any
50 }
51
52 var preserveUpperCaseKeyRe = regexp.MustCompile(`^"HTTP`)
53
54 func preserveUpperCaseKey(match []byte) bool {
55 return preserveUpperCaseKeyRe.Match(match)
56 }
57
58 func (c LowerCaseCamelJSONMarshaller) MarshalJSON() ([]byte, error) {
59 marshalled, err := json.Marshal(c.Value)
60
61 converted := keyMatchRegex.ReplaceAllFunc(
62 marshalled,
63 func(match []byte) []byte {
64 // Attributes on the form XML, JSON etc.
65 if bytes.Equal(match, bytes.ToUpper(match)) {
66 return bytes.ToLower(match)
67 }
68
69 // Empty keys are valid JSON, only lowercase if we do not have an
70 // empty key.
71 if len(match) > 2 && !preserveUpperCaseKey(match) {
72 // Decode first rune after the double quotes
73 r, width := utf8.DecodeRune(match[1:])
74 r = unicode.ToLower(r)
75 utf8.EncodeRune(match[1:width+1], r)
76 }
77 return match
78 },
79 )
80
81 return converted, err
82 }
83
84 type ReplacingJSONMarshaller struct {
85 Value any
86
87 KeysToLower bool
88 OmitEmpty bool
89 }
90
91 func (c ReplacingJSONMarshaller) MarshalJSON() ([]byte, error) {
92 converted, err := json.Marshal(c.Value)
93
94 if c.KeysToLower {
95 converted = keyMatchRegex.ReplaceAllFunc(
96 converted,
97 func(match []byte) []byte {
98 return bytes.ToLower(match)
99 },
100 )
101 }
102
103 if c.OmitEmpty {
104 // It's tricky to do this with a regexp, so convert it to a map, remove zero values and convert back.
105 var m map[string]any
106 err = json.Unmarshal(converted, &m)
107 if err != nil {
108 return nil, err
109 }
110 var removeZeroValues func(m map[string]any)
111 removeZeroValues = func(m map[string]any) {
112 for k, v := range m {
113 if !hreflect.IsMap(v) && !hreflect.IsTruthful(v) {
114 delete(m, k)
115 } else {
116 switch vv := v.(type) {
117 case map[string]any:
118 if len(vv) == 0 {
119 // Keep intentionally empty map.
120 continue
121 }
122 removeZeroValues(vv)
123 if len(vv) == 0 {
124 delete(m, k)
125 }
126 case []any:
127 for _, vvv := range vv {
128 if m, ok := vvv.(map[string]any); ok {
129 removeZeroValues(m)
130 }
131 }
132 }
133 }
134 }
135 }
136 removeZeroValues(m)
137 converted, err = json.Marshal(m)
138
139 }
140
141 return converted, err
142 }