Debian Codegraph @

internal/libyaml/options.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Options configuration for loading and dumping YAML.
5 // Provides centralized control for indentation, line width, strictness, and
6 // more.
7
8 package libyaml
9
10 import (
11 "errors"
12 "fmt"
13 )
14
15 // Options holds configuration for both loading and dumping YAML.
16 type Options struct {
17 // Loading options
18 KnownFields bool // Enforce known fields in structs
19 SingleDocument bool // Only load first document
20 UniqueKeys bool // Enforce unique keys in mappings
21 StreamNodes bool // Enable stream node emission
22 AllDocuments bool // Load/Dump all documents in multi-document streams
23
24 // Dumping options
25 Indent int // Indentation spaces (2-9)
26 CompactSeqIndent bool // Whether '- ' counts as indentation
27 LineWidth int // Preferred line width (-1 for unlimited)
28 Unicode bool // Allow non-ASCII characters
29 Canonical bool // Canonical YAML output
30 LineBreak LineBreak // Line ending style
31 ExplicitStart bool // Always emit ---
32 ExplicitEnd bool // Always emit ...
33 FlowSimpleCollections bool // Use flow style for simple collections
34 QuotePreference QuoteStyle // Preferred quote style when quoting is required
35
36 // Safety limit checks (set by ApplyOptions or WithPlugin(limit.New(...)))
37 DepthCheck func(depth int, ctx *DepthContext) error
38 AliasCheck func(aliasCount, constructCount int) error
39
40 // Private options (not exported, used internally)
41 FromLegacy bool // Indicates legacy Unmarshal()/Decoder path (check Unmarshaler, allow trailing content)
42 }
43
44 // Option allows configuring YAML loading and dumping operations.
45 type Option func(*Options) error
46
47 // DepthKind represents the type of nesting (flow or block).
48 type DepthKind string
49
50 // DepthKindFlow and DepthKindBlock are the possible values of DepthContext.Kind.
51 const (
52 DepthKindFlow DepthKind = "flow"
53 DepthKindBlock DepthKind = "block"
54 )
55
56 // DepthContext holds context about a nesting depth check.
57 type DepthContext struct {
58 Kind DepthKind
59 }
60
61 // DefaultDepthCheck is the default depth check function.
62 // It returns an error when depth exceeds 10000.
63 func DefaultDepthCheck(depth int, ctx *DepthContext) error {
64 const maxDepth = 10000
65 if depth > maxDepth {
66 return fmt.Errorf("exceeded max depth of %d", maxDepth)
67 }
68 return nil
69 }
70
71 // DefaultAliasCheck is the default alias check function.
72 // It uses a ratio-based heuristic to prevent DoS attacks via excessive aliasing.
73 func DefaultAliasCheck(aliasCount, constructCount int) error {
74 const (
75 aliasRatioRangeLow = 400000
76 aliasRatioRangeHigh = 4000000
77 aliasRatioRange = float64(aliasRatioRangeHigh - aliasRatioRangeLow)
78 )
79 if aliasCount <= 100 || constructCount <= 1000 {
80 return nil
81 }
82 var allowed float64
83 switch {
84 case constructCount <= aliasRatioRangeLow:
85 allowed = 0.99
86 case constructCount >= aliasRatioRangeHigh:
87 allowed = 0.10
88 default:
89 allowed = 0.99 - 0.89*(float64(constructCount-aliasRatioRangeLow)/aliasRatioRange)
90 }
91 if float64(aliasCount)/float64(constructCount) > allowed {
92 return errors.New("document contains excessive aliasing")
93 }
94 return nil
95 }
96
97 // WithIndent sets the number of spaces to use for indentation when
98 // dumping YAML content.
99 //
100 // Valid values are 2-9. Common choices: 2 (compact), 4 (readable).
101 func WithIndent(indent int) Option {
102 return func(o *Options) error {
103 if indent < 2 || indent > 9 {
104 return errors.New("yaml: indent must be between 2 and 9 spaces")
105 }
106 o.Indent = indent
107 return nil
108 }
109 }
110
111 // WithCompactSeqIndent configures whether the sequence indicator '- ' is
112 // considered part of the indentation when dumping YAML content.
113 //
114 // If compact is true, '- ' is treated as part of the indentation.
115 // If compact is false, '- ' is not treated as part of the indentation.
116 // When called without arguments, defaults to true.
117 func WithCompactSeqIndent(compact ...bool) Option {
118 if len(compact) > 1 {
119 return func(o *Options) error {
120 return errors.New("yaml: WithCompactSeqIndent accepts at most one argument")
121 }
122 }
123 val := len(compact) == 0 || compact[0]
124 return func(o *Options) error {
125 o.CompactSeqIndent = val
126 return nil
127 }
128 }
129
130 // WithKnownFields enables or disables strict field checking during YAML loading.
131 //
132 // When enabled, loading will return an error if the YAML input contains fields
133 // that do not correspond to any fields in the target struct.
134 // When called without arguments, defaults to true.
135 func WithKnownFields(knownFields ...bool) Option {
136 if len(knownFields) > 1 {
137 return func(o *Options) error {
138 return errors.New("yaml: WithKnownFields accepts at most one argument")
139 }
140 }
141 val := len(knownFields) == 0 || knownFields[0]
142 return func(o *Options) error {
143 o.KnownFields = val
144 return nil
145 }
146 }
147
148 // WithSingleDocument configures the Loader to only process the first document
149 // in a YAML stream. After the first document is loaded, subsequent calls to
150 // Load will return [io.EOF].
151 //
152 // When called without arguments, defaults to true.
153 //
154 // This is useful when you expect exactly one document and want behavior
155 // similar to [Unmarshal].
156 func WithSingleDocument(singleDocument ...bool) Option {
157 if len(singleDocument) > 1 {
158 return func(o *Options) error {
159 return errors.New("yaml: WithSingleDocument accepts at most one argument")
160 }
161 }
162 val := len(singleDocument) == 0 || singleDocument[0]
163 return func(o *Options) error {
164 o.SingleDocument = val
165 return nil
166 }
167 }
168
169 // WithStreamNodes enables returning stream boundary nodes when loading YAML.
170 //
171 // When enabled, Loader.Load returns an interleaved sequence of StreamNode and
172 // DocumentNode values:
173 //
174 // [StreamNode, DocNode, StreamNode, DocNode, ..., StreamNode]
175 //
176 // StreamNodes contain metadata about the stream including:
177 // - Encoding (UTF-8, UTF-16LE, UTF-16BE)
178 // - YAML version directive (%YAML)
179 // - Tag directives (%TAG)
180 // - Position information (Line, Column)
181 //
182 // An empty YAML stream returns a single StreamNode.
183 // When called without arguments, defaults to true.
184 //
185 // The default is false.
186 func WithStreamNodes(enable ...bool) Option {
187 if len(enable) > 1 {
188 return func(o *Options) error {
189 return errors.New("yaml: WithStreamNodes accepts at most one argument")
190 }
191 }
192 val := len(enable) == 0 || enable[0]
193 return func(o *Options) error {
194 o.StreamNodes = val
195 return nil
196 }
197 }
198
199 // WithAllDocuments enables multi-document mode for Load and Dump operations.
200 //
201 // When used with Load, the target must be a pointer to a slice.
202 // All documents in the YAML stream will be decoded into the slice.
203 // Zero documents results in an empty slice (no error).
204 //
205 // When used with Dump, the input must be a slice.
206 // Each element will be encoded as a separate YAML document
207 // with "---" separators.
208 //
209 // When called without arguments, defaults to true.
210 //
211 // The default is false (single-document mode).
212 func WithAllDocuments(all ...bool) Option {
213 if len(all) > 1 {
214 return func(o *Options) error {
215 return errors.New("yaml: WithAllDocuments accepts at most one argument")
216 }
217 }
218 val := len(all) == 0 || all[0]
219 return func(o *Options) error {
220 o.AllDocuments = val
221 return nil
222 }
223 }
224
225 // WithLineWidth sets the preferred line width for YAML output.
226 //
227 // When encoding long strings, the encoder will attempt to wrap them at this
228 // width using literal block style (|). Set to -1 or 0 for unlimited width.
229 //
230 // The default is 80 characters.
231 func WithLineWidth(width int) Option {
232 return func(o *Options) error {
233 if width < 0 {
234 width = -1
235 }
236 o.LineWidth = width
237 return nil
238 }
239 }
240
241 // WithUnicode controls whether non-ASCII characters are allowed in YAML output.
242 //
243 // When true, non-ASCII characters appear as-is (e.g., "café").
244 // When false, non-ASCII characters are escaped (e.g., "caf\u00e9").
245 // When called without arguments, defaults to true.
246 //
247 // The default is true.
248 func WithUnicode(unicode ...bool) Option {
249 if len(unicode) > 1 {
250 return func(o *Options) error {
251 return errors.New("yaml: WithUnicode accepts at most one argument")
252 }
253 }
254 val := len(unicode) == 0 || unicode[0]
255 return func(o *Options) error {
256 o.Unicode = val
257 return nil
258 }
259 }
260
261 // WithUniqueKeys enables or disables duplicate key detection during YAML loading.
262 //
263 // When enabled, loading will return an error if the YAML input contains
264 // duplicate keys in any mapping. This is a security feature that prevents
265 // key override attacks.
266 // When called without arguments, defaults to true.
267 //
268 // The default is true.
269 func WithUniqueKeys(uniqueKeys ...bool) Option {
270 if len(uniqueKeys) > 1 {
271 return func(o *Options) error {
272 return errors.New("yaml: WithUniqueKeys accepts at most one argument")
273 }
274 }
275 val := len(uniqueKeys) == 0 || uniqueKeys[0]
276 return func(o *Options) error {
277 o.UniqueKeys = val
278 return nil
279 }
280 }
281
282 // WithCanonical forces canonical YAML output format.
283 //
284 // When enabled, the encoder outputs strictly canonical YAML with explicit
285 // tags for all values. This produces verbose output primarily useful for
286 // debugging and YAML spec compliance testing.
287 // When called without arguments, defaults to true.
288 //
289 // The default is false.
290 func WithCanonical(canonical ...bool) Option {
291 if len(canonical) > 1 {
292 return func(o *Options) error {
293 return errors.New("yaml: WithCanonical accepts at most one argument")
294 }
295 }
296 val := len(canonical) == 0 || canonical[0]
297 return func(o *Options) error {
298 o.Canonical = val
299 return nil
300 }
301 }
302
303 // WithLineBreak sets the line ending style for YAML output.
304 //
305 // Available options:
306 // - LineBreakLN: Unix-style \n (default)
307 // - LineBreakCR: Old Mac-style \r
308 // - LineBreakCRLN: Windows-style \r\n
309 //
310 // The default is LineBreakLN.
311 func WithLineBreak(lineBreak LineBreak) Option {
312 return func(o *Options) error {
313 o.LineBreak = lineBreak
314 return nil
315 }
316 }
317
318 // WithExplicitStart controls whether document start markers (---) are always emitted.
319 //
320 // When true, every document begins with an explicit "---" marker.
321 // When false (default), the marker is omitted for the first document.
322 // When called without arguments, defaults to true.
323 func WithExplicitStart(explicit ...bool) Option {
324 if len(explicit) > 1 {
325 return func(o *Options) error {
326 return errors.New("yaml: WithExplicitStart accepts at most one argument")
327 }
328 }
329 val := len(explicit) == 0 || explicit[0]
330 return func(o *Options) error {
331 o.ExplicitStart = val
332 return nil
333 }
334 }
335
336 // WithExplicitEnd controls whether document end markers (...) are always emitted.
337 //
338 // When true, every document ends with an explicit "..." marker.
339 // When false (default), the marker is omitted.
340 // When called without arguments, defaults to true.
341 func WithExplicitEnd(explicit ...bool) Option {
342 if len(explicit) > 1 {
343 return func(o *Options) error {
344 return errors.New("yaml: WithExplicitEnd accepts at most one argument")
345 }
346 }
347 val := len(explicit) == 0 || explicit[0]
348 return func(o *Options) error {
349 o.ExplicitEnd = val
350 return nil
351 }
352 }
353
354 // WithFlowSimpleCollections controls whether simple collections use flow style.
355 //
356 // When true, sequences and mappings containing only scalar values (no nested
357 // collections) are rendered in flow style if they fit within the line width.
358 // Example: {name: test, count: 42} or [a, b, c]
359 // When called without arguments, defaults to true.
360 //
361 // When false (default), all collections use block style.
362 func WithFlowSimpleCollections(flow ...bool) Option {
363 if len(flow) > 1 {
364 return func(o *Options) error {
365 return errors.New("yaml: WithFlowSimpleCollections accepts at most one argument")
366 }
367 }
368 val := len(flow) == 0 || flow[0]
369 return func(o *Options) error {
370 o.FlowSimpleCollections = val
371 return nil
372 }
373 }
374
375 // WithQuotePreference sets the preferred quote style for strings that require
376 // quoting.
377 //
378 // This option only affects strings that require quoting per the YAML spec.
379 // Plain strings that don't need quoting remain unquoted regardless of this
380 // setting. Quoting is required for:
381 // - Strings that look like other YAML types (true, false, null, 123, etc.)
382 // - Strings with leading/trailing whitespace
383 // - Strings containing special YAML syntax characters
384 // - Empty strings in certain contexts
385 //
386 // Quote styles:
387 // - QuoteSingle: Use single quotes (v4 default)
388 // - QuoteDouble: Use double quotes
389 // - QuoteLegacy: Legacy v2/v3 behavior (mixed quoting)
390 func WithQuotePreference(style QuoteStyle) Option {
391 return func(o *Options) error {
392 switch style {
393 case QuoteSingle, QuoteDouble, QuoteLegacy:
394 o.QuotePreference = style
395 return nil
396 default:
397 return fmt.Errorf("invalid QuoteStyle value: %d", style)
398 }
399 }
400 }
401
402 // CombineOptions combines multiple options into a single Option.
403 // This is useful for creating option presets or combining version defaults
404 // with custom options.
405 func CombineOptions(opts ...Option) Option {
406 return func(o *Options) error {
407 for _, opt := range opts {
408 if err := opt(o); err != nil {
409 return err
410 }
411 }
412 return nil
413 }
414 }
415
416 // ApplyOptions applies the given options to a new options struct.
417 // Starts with v4 defaults.
418 func ApplyOptions(opts ...Option) (*Options, error) {
419 o := &Options{
420 Canonical: false,
421 LineBreak: LN_BREAK,
422
423 // v4 defaults
424 Indent: 2,
425 CompactSeqIndent: true,
426 LineWidth: 80,
427 Unicode: true,
428 UniqueKeys: true,
429
430 // Default safety limits
431 DepthCheck: DefaultDepthCheck,
432 AliasCheck: DefaultAliasCheck,
433 }
434 for _, opt := range opts {
435 if err := opt(o); err != nil {
436 return nil, err
437 }
438 }
439 return o, nil
440 }
441
442 // DefaultOptions holds the default options for APIs that don't accept options.
443 var DefaultOptions = &Options{
444 Indent: 4,
445 LineWidth: -1,
446 Unicode: true,
447 UniqueKeys: true,
448 QuotePreference: QuoteLegacy,
449 }