Debian Codegraph @

tpl/transform/unmarshal.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 transform
15
16 import (
17 "errors"
18 "fmt"
19 "io"
20 "strings"
21
22 "github.com/gohugoio/hugo/resources"
23 "github.com/gohugoio/hugo/resources/resource"
24
25 "github.com/gohugoio/hugo/common/hashing"
26 "github.com/gohugoio/hugo/common/types"
27
28 "github.com/mitchellh/mapstructure"
29
30 "github.com/gohugoio/hugo/parser/metadecoders"
31
32 "github.com/spf13/cast"
33 )
34
35 // Unmarshal unmarshals the data given, which can be either a string, json.RawMessage
36 // or a Resource. Supported formats are JSON, TOML, YAML, and CSV.
37 // You can optionally provide an options map as the first argument.
38 func (ns *Namespace) Unmarshal(args ...any) (any, error) {
39 if len(args) < 1 || len(args) > 2 {
40 return nil, errors.New("unmarshal takes 1 or 2 arguments")
41 }
42
43 var data any
44 decoder := metadecoders.Default
45
46 if len(args) == 1 {
47 data = args[0]
48 } else {
49 m, ok := args[0].(map[string]any)
50 if !ok {
51 return nil, errors.New("first argument must be a map")
52 }
53
54 var err error
55
56 data = args[1]
57 decoder, err = decodeDecoder(m)
58 if err != nil {
59 return nil, fmt.Errorf("failed to decode options: %w", err)
60 }
61 }
62
63 if r, ok := data.(resource.UnmarshableResource); ok {
64 key := r.Key()
65
66 if key == "" {
67 return nil, errors.New("no Key set in Resource")
68 }
69
70 if decoder != metadecoders.Default {
71 key += decoder.OptionsKey()
72 }
73
74 v, err := ns.cacheUnmarshal.GetOrCreate(key, func(string) (*resources.StaleValue[any], error) {
75 var f metadecoders.Format
76 if decoder.Format != "" {
77 f = metadecoders.FormatFromString(decoder.Format)
78 if f == "" {
79 return nil, fmt.Errorf("format %q not supported", decoder.Format)
80 }
81 } else {
82 f = metadecoders.FormatFromStrings(r.MediaType().Suffixes()...)
83 if f == "" {
84 return nil, fmt.Errorf("MIME %q not supported", r.MediaType())
85 }
86 }
87
88 reader, err := r.ReadSeekCloser()
89 if err != nil {
90 return nil, err
91 }
92 defer reader.Close()
93
94 b, err := io.ReadAll(reader)
95 if err != nil {
96 return nil, err
97 }
98
99 v, err := decoder.Unmarshal(b, f)
100 if err != nil {
101 return nil, err
102 }
103
104 return &resources.StaleValue[any]{
105 Value: v,
106 StaleVersionFunc: func() uint32 {
107 return resource.StaleVersion(r)
108 },
109 }, nil
110 })
111 if err != nil {
112 return nil, err
113 }
114
115 return v.Value, nil
116
117 }
118
119 dataStr, err := types.ToStringE(data)
120 if err != nil {
121 return nil, fmt.Errorf("type %T not supported", data)
122 }
123
124 if strings.TrimSpace(dataStr) == "" {
125 return nil, nil
126 }
127
128 key := hashing.XxHashFromStringHexEncoded(dataStr)
129
130 if decoder != metadecoders.Default {
131 key += decoder.OptionsKey()
132 }
133
134 v, err := ns.cacheUnmarshal.GetOrCreate(key, func(string) (*resources.StaleValue[any], error) {
135 var f metadecoders.Format
136 if decoder.Format != "" {
137 f = metadecoders.FormatFromString(decoder.Format)
138 if f == "" {
139 return nil, fmt.Errorf("format %q not supported", decoder.Format)
140 }
141 } else {
142 f = decoder.FormatFromContentString(dataStr)
143 if f == "" {
144 return nil, errors.New("unknown format")
145 }
146 }
147
148 v, err := decoder.Unmarshal([]byte(dataStr), f)
149 if err != nil {
150 return nil, err
151 }
152
153 return &resources.StaleValue[any]{
154 Value: v,
155 StaleVersionFunc: func() uint32 {
156 return 0
157 },
158 }, nil
159 })
160 if err != nil {
161 return nil, err
162 }
163
164 return v.Value, nil
165 }
166
167 func decodeDecoder(m map[string]any) (metadecoders.Decoder, error) {
168 opts := metadecoders.Default
169
170 if m == nil {
171 return opts, nil
172 }
173
174 // mapstructure does not support string to rune conversion, so do that manually.
175 // See https://github.com/mitchellh/mapstructure/issues/151
176 for k, v := range m {
177 if strings.EqualFold(k, "Delimiter") {
178 r, err := stringToRune(v)
179 if err != nil {
180 return opts, err
181 }
182 opts.Delimiter = r
183 delete(m, k)
184
185 } else if strings.EqualFold(k, "Comment") {
186 r, err := stringToRune(v)
187 if err != nil {
188 return opts, err
189 }
190 opts.Comment = r
191 delete(m, k)
192 }
193 }
194
195 err := mapstructure.WeakDecode(m, &opts)
196
197 return opts, err
198 }
199
200 func stringToRune(v any) (rune, error) {
201 s, err := cast.ToStringE(v)
202 if err != nil {
203 return 0, err
204 }
205
206 if len(s) == 0 {
207 return 0, nil
208 }
209
210 var r rune
211
212 for i, rr := range s {
213 if i == 0 {
214 r = rr
215 } else {
216 return 0, fmt.Errorf("invalid character: %q", v)
217 }
218 }
219
220 return r, nil
221 }