Debian Codegraph @

docs/options.md

raw symbols SCIP
1 # YAML Options Guide
2
3 This guide explains how to use the go-yaml options system to control YAML
4 formatting and behavior.
5
6 ## Quick Start
7
8 The simplest way to use go-yaml is with the default settings:
9
10 ```go
11 import "go.yaml.in/yaml/v4"
12
13 // Uses v4 defaults (2-space indent, compact sequences)
14 dumper, _ := yaml.NewDumper(writer)
15 dumper.Dump(&myData)
16 dumper.Close()
17 ```
18
19 But what if you want 4-space indentation like v3? Or strict field checking?
20 That's where options come in.
21
22 ## Individual Options
23
24 **Note:** All options work with both package-level functions (`Load`, `Dump`,
25 `NewLoader`, `NewDumper`) and node-level methods (`node.Load()`, `node.Dump()`).
26
27 You can tweak specific settings with individual option functions:
28
29 ```go
30 dumper, _ := yaml.NewDumper(writer,
31 yaml.WithIndent(4), // 4-space indentation (v3 style)
32 yaml.WithCompactSeqIndent(false), // Non-compact lists (v3 style)
33 )
34 ```
35
36 ### Available Options
37
38 #### Dumper (Encoding) Options
39
40 **Boolean Options:** All boolean options support variadic arguments.
41 Call without arguments to enable (defaults to `true`), or pass `false` to
42 explicitly disable:
43
44 ```go
45 yaml.WithExplicitStart() // Enable (same as WithExplicitStart(true))
46 yaml.WithExplicitStart(false) // Explicitly disable
47 ```
48
49 ##### `yaml.WithIndent(spaces int)`
50
51 Controls how many spaces to use for indentation.
52
53 ```go
54 // 2-space indent (compact)
55 yaml.NewDumper(w, yaml.WithIndent(2))
56
57 // 4-space indent (readable)
58 yaml.NewDumper(w, yaml.WithIndent(4))
59
60 // 8-space indent (very spacious)
61 yaml.NewDumper(w, yaml.WithIndent(8))
62 ```
63
64 **Example output with different indents:**
65
66 ```yaml
67 # WithIndent(2)
68 servers:
69 web:
70 host: localhost
71 port: 8080
72
73 # WithIndent(4)
74 servers:
75 web:
76 host: localhost
77 port: 8080
78
79 # WithIndent(8)
80 servers:
81 web:
82 host: localhost
83 port: 8080
84 ```
85
86 ##### `yaml.WithCompactSeqIndent(...bool)`
87
88 Controls whether the list indicator `- ` counts as part of the indentation.
89
90 ```go
91 // Enable compact sequences (short form)
92 yaml.NewDumper(w,
93 yaml.WithIndent(4),
94 yaml.WithCompactSeqIndent(),
95 )
96 ```
97
98 **Example:**
99
100 ```yaml
101 # compact=true (v4 default)
102 items:
103 - name: first
104 value: 1
105 - name: second
106 value: 2
107
108 # compact=false (v3 style)
109 items:
110 - name: first
111 value: 1
112 - name: second
113 value: 2
114 ```
115
116 ##### `yaml.WithLineWidth(width int)`
117
118 Sets the preferred line width for wrapping long strings.
119 Use -1 or 0 for unlimited width.
120
121 ```go
122 // Wrap at 40 characters
123 yaml.NewDumper(w, yaml.WithLineWidth(40))
124
125 // Unlimited width (no wrapping)
126 yaml.NewDumper(w, yaml.WithLineWidth(-1))
127 ```
128
129 **Example:**
130
131 ```yaml
132 # LineWidth=40
133 description: |
134 This is a long description
135 that wraps to multiple lines.
136
137 # LineWidth=-1
138 description: This is a long description that stays on one line
139 ```
140
141 **Default:** 80 characters
142
143 ##### `yaml.WithUnicode(...bool)`
144
145 Controls whether non-ASCII characters appear as-is or are escaped.
146
147 ```go
148 // Allow unicode (default)
149 yaml.NewDumper(w, yaml.WithUnicode(true))
150
151 // Escape non-ASCII characters
152 yaml.NewDumper(w, yaml.WithUnicode(false))
153 ```
154
155 **Example:**
156
157 ```yaml
158 # WithUnicode(true) - default
159 name: café
160
161 # WithUnicode(false)
162 name: "caf\u00e9"
163 ```
164
165 **Use case:** Set to false for ASCII-only output required by legacy systems.
166
167 **Default:** true
168
169 ##### `yaml.WithCanonical(...bool)`
170
171 Forces strictly canonical YAML output with explicit tags.
172 Primarily for debugging and spec testing.
173
174 ```go
175 yaml.NewDumper(w, yaml.WithCanonical(true))
176 ```
177
178 **Example:**
179
180 ```yaml
181 # Normal output
182 name: John
183 age: 30
184
185 # Canonical output
186 !!map {
187 ? !!str "name"
188 : !!str "John",
189 ? !!str "age"
190 : !!int "30",
191 }
192 ```
193
194 **Default:** false
195
196 ##### `yaml.WithLineBreak(lineBreak yaml.LineBreak)`
197
198 Sets the line ending style.
199 Available options: `yaml.LineBreakLN` (Unix), `yaml.LineBreakCR` (old Mac),
200 `yaml.LineBreakCRLN` (Windows).
201
202 ```go
203 // Unix line endings (default)
204 yaml.NewDumper(w, yaml.WithLineBreak(yaml.LineBreakLN))
205
206 // Windows line endings
207 yaml.NewDumper(w, yaml.WithLineBreak(yaml.LineBreakCRLN))
208 ```
209
210 **Default:** `yaml.LineBreakLN` (Unix `\n`)
211
212 ##### `yaml.WithExplicitStart(...bool)`
213
214 Controls whether document start markers (`---`) are always emitted.
215
216 ```go
217 // Always emit --- at document start (short form)
218 yaml.NewDumper(w, yaml.WithExplicitStart())
219 ```
220
221 **Example:**
222
223 ```yaml
224 # WithExplicitStart(true)
225 ---
226 name: test
227
228 # WithExplicitStart(false) - default
229 name: test
230 ```
231
232 **Use case:** Multi-document streams, explicit document boundaries.
233
234 **Default:** false
235
236 ##### `yaml.WithExplicitEnd(...bool)`
237
238 Controls whether document end markers (`...`) are always emitted.
239
240 ```go
241 // Always emit ... at document end (short form)
242 yaml.NewDumper(w, yaml.WithExplicitEnd())
243 ```
244
245 **Example:**
246
247 ```yaml
248 # WithExplicitEnd(true)
249 name: test
250 ...
251
252 # WithExplicitEnd(false) - default
253 name: test
254 ```
255
256 **Use case:** Streaming scenarios where document end must be explicit.
257
258 **Default:** false
259
260 ##### `yaml.WithFlowSimpleCollections(...bool)`
261
262 Controls whether simple collections use flow style.
263 Simple collections are sequences and mappings that:
264
265 - Contain only scalar values (no nested collections)
266 - Fit within the line width when rendered in flow style
267
268 ```go
269 // Use flow style for simple collections (short form)
270 yaml.NewDumper(w, yaml.WithFlowSimpleCollections())
271 ```
272
273 **Example:**
274
275 ```yaml
276 # WithFlowSimpleCollections(true)
277 config:
278 tags: [web, api, prod]
279 metadata: {version: 1.0, author: admin}
280 nested: # Not simple - has nested collections
281 items:
282 - name: foo
283
284 # WithFlowSimpleCollections(false) - default
285 config:
286 tags:
287 - web
288 - api
289 - prod
290 metadata:
291 version: 1.0
292 author: admin
293 ```
294
295 **Use case:** Compact output for simple data structures, JSON-like formatting.
296
297 **Default:** false
298
299 ##### `yaml.WithQuotePreference(style yaml.QuoteStyle)`
300
301 Controls which type of quotes to use when quoting is required by the YAML spec.
302
303 **Important:** This option only affects strings that *require* quoting. Plain strings that don't need quoting remain unquoted regardless of this setting.
304
305 Quoting is required for:
306 - Strings that look like other YAML types (true, false, null, 123, etc.)
307 - Strings with leading/trailing whitespace
308 - Strings containing special YAML syntax characters
309 - Empty strings in certain contexts
310
311 ```go
312 // Use single quotes when quoting is required (v4 default)
313 yaml.NewDumper(w, yaml.WithQuotePreference(yaml.QuoteSingle))
314
315 // Use double quotes when quoting is required
316 yaml.NewDumper(w, yaml.WithQuotePreference(yaml.QuoteDouble))
317
318 // Use legacy v2/v3 behavior (mixed quoting)
319 yaml.NewDumper(w, yaml.WithQuotePreference(yaml.QuoteLegacy))
320 ```
321
322 **Example:**
323
324 ```yaml
325 # WithQuotePreference(yaml.QuoteSingle) - v4 default
326 plain: hello # Plain string stays plain
327 bool: 'true' # Looks like bool, gets single quotes
328 number: '123' # Looks like number, gets single quotes
329 spaces: ' hello' # Leading space, gets single quotes
330
331 # WithQuotePreference(yaml.QuoteDouble)
332 plain: hello # Plain string stays plain
333 bool: "true" # Looks like bool, gets double quotes
334 number: "123" # Looks like number, gets double quotes
335 spaces: " hello" # Leading space, gets double quotes
336
337 # WithQuotePreference(yaml.QuoteLegacy) - v2/v3 behavior
338 plain: hello # Plain string stays plain
339 bool: "true" # Looks like bool, gets double quotes
340 number: "123" # Looks like number, gets double quotes
341 spaces: ' hello' # Leading space, gets single quotes
342 ```
343
344 **Use case:**
345 - `QuoteSingle`: Modern YAML style with single quotes (cleaner, less escaping)
346 - `QuoteDouble`: When you prefer double quotes or need consistency with JSON-style
347 - `QuoteLegacy`: Backward compatibility with go-yaml v2/v3 output
348
349 **Default:**
350 - v4: `QuoteSingle`
351 - v2/v3: `QuoteLegacy`
352
353 #### Loader (Decoding) Options
354
355 **Boolean Options:** All boolean options support variadic arguments.
356 Call without arguments to enable (defaults to `true`), or pass `false` to
357 explicitly disable:
358
359 ```go
360 yaml.WithKnownFields() // Enable (same as WithKnownFields(true))
361 yaml.WithKnownFields(false) // Explicitly disable
362 ```
363
364 ##### `yaml.WithKnownFields(...bool)`
365
366 When enabled, loading will fail if the YAML contains fields that don't exist in
367 your struct.
368
369 ```go
370 type Config struct {
371 Name string `yaml:"name"`
372 Port int `yaml:"port"`
373 }
374
375 // Enable strict field checking (short form)
376 loader, _ := yaml.NewLoader(reader,
377 yaml.WithKnownFields(),
378 )
379
380 // This will fail if YAML contains "unknown_field"
381 var config Config
382 err := loader.Load(&config)
383 ```
384
385 **Great for:** Catching typos in config files, enforcing strict schemas.
386
387 ##### `yaml.WithSingleDocument(...bool)`
388
389 Only load the first YAML document, then return EOF.
390
391 ```go
392 // Enable single document mode (short form)
393 loader, _ := yaml.NewLoader(reader,
394 yaml.WithSingleDocument(),
395 )
396
397 var doc1 Doc
398 loader.Load(&doc1) // Loads first document
399
400 var doc2 Doc
401 loader.Load(&doc2) // Returns io.EOF
402
403 // Dynamic based on environment/config
404 singleDoc := os.Getenv("SINGLE_DOC") == "true"
405 loader, _ := yaml.NewLoader(reader,
406 yaml.WithSingleDocument(singleDoc),
407 )
408 ```
409
410 **Use case:** When you expect exactly one document and want to catch extras.
411
412 **Default:** false (multi-document mode)
413
414 ##### `yaml.WithUniqueKeys(...bool)`
415
416 Controls duplicate key detection in mappings.
417 When enabled, loading fails if duplicate keys are found.
418
419 ```go
420 // Enforce unique keys (default - short form)
421 loader, _ := yaml.NewLoader(reader,
422 yaml.WithUniqueKeys(),
423 )
424
425 // Allow duplicates (not recommended)
426 loader, _ := yaml.NewLoader(reader,
427 yaml.WithUniqueKeys(false),
428 )
429 ```
430
431 **Example YAML that would fail:**
432
433 ```yaml
434 admin: false
435 admin: true # Error: duplicate key
436 ```
437
438 **Security note:** This prevents key override attacks where an attacker could
439 override security-critical keys.
440
441 **Default:** true (enabled)
442
443 ## Version-Specific Option Presets
444
445 Instead of setting options one by one, you can use version presets that match
446 go-yaml v2, v3, or v4 behavior.
447
448 ### What's the difference?
449
450 | Option | v2 | v3 | v4 |
451 |-----------------------|---------|---------|--------|
452 | Indent | 2 | 4 | 2 |
453 | Compact Sequences | No | No | Yes |
454 | Line Width | 80 | 80 | 80 |
455 | Unicode | Yes | Yes | Yes |
456 | Unique Keys | Yes | Yes | Yes |
457 | Quote Preference | Legacy | Legacy | Single |
458
459 **Note:** v4 uses compact sequences (modern YAML standard) while v2/v3 preserve
460 the historical non-compact behavior for backward compatibility.
461
462 ### Using v2 Options
463
464 ```go
465 dumper, _ := yaml.NewDumper(writer, yaml.WithV2Defaults())
466 ```
467
468 **When to use:** Matching go-yaml v2 output format (2-space indent).
469
470 ### Using v3 Options
471
472 ```go
473 dumper, _ := yaml.NewDumper(writer, yaml.WithV3Defaults())
474 ```
475
476 **When to use:** Explicitly requesting v3 behavior (4-space indent, non-compact
477 sequences).
478 Use this for compatibility with older go-yaml v3 output or when working with
479 code that expects v3 formatting.
480
481 ### Using v4 Options (Default)
482
483 ```go
484 dumper, _ := yaml.NewDumper(writer, yaml.WithV4Defaults())
485 ```
486
487 **When to use:** Modern YAML output with 2-space indent and compact sequences.
488 This is the default, so you usually don't need to specify `yaml.WithV4Defaults()` unless you
489 want to be explicit.
490
491 ## Mixing Presets with Individual Options
492
493 You can start with a preset and override specific options.
494 **Options apply left-to-right**, so later options override earlier ones.
495
496 ```go
497 // Start with v3 defaults (4-space), then override to 2-space
498 dumper, _ := yaml.NewDumper(writer,
499 yaml.WithV3Defaults(),
500 yaml.WithIndent(2), // This wins
501 )
502 ```
503
504 **More examples:**
505
506 ```go
507 // Default (v4) + override to 4-space indent
508 dumper, _ := yaml.NewDumper(writer,
509 yaml.WithIndent(4), // Overrides default 2-space
510 )
511
512 // Start with 2-space, then apply v3 (4-space wins)
513 dumper, _ := yaml.NewDumper(writer,
514 yaml.WithIndent(2),
515 yaml.WithV3Defaults(), // This overrides to 4
516 )
517 ```
518
519 ## Loading Options from YAML Config
520
521 You can load your YAML processing options from a YAML configuration file! This
522 is great for making formatting configurable.
523
524 ```go
525 configYAML := `
526 indent: 3
527 compact-seq-indent: true
528 known-fields: true
529 `
530
531 opts, err := yaml.OptsYAML(configYAML)
532 if err != nil {
533 log.Fatal(err)
534 }
535
536 dumper, _ := yaml.NewDumper(writer, opts)
537 ```
538
539 **The YAML field names are:**
540 - `indent` - Number of spaces
541 - `compact-seq-indent` - Boolean
542 - `line-width` - Integer
543 - `unicode` - Boolean
544 - `canonical` - Boolean
545 - `line-break` - String (ln, cr, crln)
546 - `explicit-start` - Boolean
547 - `explicit-end` - Boolean
548 - `flow-simple-coll` - Boolean
549 - `quote-preference` - String (single, double, legacy)
550 - `known-fields` - Boolean
551 - `single-document` - Boolean
552 - `unique-keys` - Boolean
553
554 **Any field not in your config uses the version's defaults.**
555
556 ## Real-World Examples
557
558 ### Example 1: Strict Config File Loader
559
560 ```go
561 type AppConfig struct {
562 Database DatabaseConfig `yaml:"database"`
563 Server ServerConfig `yaml:"server"`
564 }
565
566 func LoadConfig(filename string) (*AppConfig, error) {
567 f, err := os.Open(filename)
568 if err != nil {
569 return nil, err
570 }
571 defer f.Close()
572
573 loader, err := yaml.NewLoader(f,
574 yaml.WithV4Defaults(),
575 yaml.WithKnownFields(), // Catch typos (defaults to true)
576 yaml.WithSingleDocument(), // Expect exactly one doc
577 )
578 if err != nil {
579 return nil, err
580 }
581
582 var config AppConfig
583 if err := loader.Load(&config); err != nil {
584 return nil, err
585 }
586
587 return &config, nil
588 }
589 ```
590
591 ### Example 2: Matching External Tool Format
592
593 Your CI system expects 2-space indented YAML:
594
595 ```go
596 func GenerateCI(config *CIConfig) ([]byte, error) {
597 var buf bytes.Buffer
598
599 dumper, err := yaml.NewDumper(&buf,
600 yaml.WithV2Defaults(),
601 )
602 if err != nil {
603 return nil, err
604 }
605
606 if err := dumper.Dump(config); err != nil {
607 return nil, err
608 }
609 dumper.Close()
610
611 return buf.Bytes(), nil
612 }
613 ```
614
615 ### Example 3: User-Configurable Formatter
616
617 ```go
618 func FormatYAML(input []byte, userPrefs string) ([]byte, error) {
619 // Load user's formatting preferences
620 opts, err := yaml.OptsYAML(userPrefs)
621 if err != nil {
622 return nil, err
623 }
624
625 // Parse input
626 var node yaml.Node
627 if err := yaml.Load(input, &node); err != nil {
628 return nil, err
629 }
630
631 // Reformat with user preferences
632 var buf bytes.Buffer
633 dumper, _ := yaml.NewDumper(&buf, opts)
634 dumper.Dump(&node)
635 dumper.Close()
636
637 return buf.Bytes(), nil
638 }
639 ```
640
641 ### Example 4: Multi-Document Stream with Options
642
643 ```go
644 func ProcessMultiDocs(reader io.Reader) error {
645 loader, err := yaml.NewLoader(reader,
646 yaml.WithKnownFields(false), // Allow unknown fields (override default)
647 )
648 if err != nil {
649 return err
650 }
651
652 for {
653 var doc Document
654 err := loader.Load(&doc)
655 if err == io.EOF {
656 break
657 }
658 if err != nil {
659 return err
660 }
661
662 // Process document...
663 processDocument(&doc)
664 }
665
666 return nil
667 }
668 ```
669
670 ## Common Patterns
671
672 ### Pattern: Application Config Loader
673
674 ```go
675 loader, _ := yaml.NewLoader(configFile,
676 yaml.WithSingleDocument(), // Only one config file
677 yaml.WithKnownFields(), // Strict validation (defaults to true)
678 )
679 ```
680
681 ### Pattern: Default YAML Output
682
683 ```go
684 dumper, _ := yaml.NewDumper(output) // Uses v4 defaults (2-space, compact)
685 ```
686
687 ### Pattern: Match Legacy Format
688
689 ```go
690 dumper, _ := yaml.NewDumper(output, yaml.WithV3Defaults()) // 4-space like old go-yaml
691 ```
692
693 ## Tips & Tricks
694
695 **Default is v4:** `yaml.NewDumper(w)` uses v4 defaults (2-space indent,
696 compact sequences).
697
698 **Order matters:** Options are applied left-to-right, with later options
699 overriding earlier ones.
700 For example, `yaml.WithIndent(2), yaml.WithV3Defaults()` gives you 4 spaces (V3 wins),
701 while `yaml.WithV3Defaults(), yaml.WithIndent(2)` gives you 2 spaces.
702
703 **Load from files:** Use `yaml.OptsYAML()` to make formatting configurable by
704 users.
705
706 **Validation:** Use `WithKnownFields()` to catch config file typos early.
707
708 **One document:** Use `WithSingleDocument()` when you expect exactly one YAML
709 document.
710
711 **Test your options:** Run examples with different options to see the output
712 format.
713
714 ## See Also
715
716 - [Dumping and Loading API Guide](dump-load-api.md) - Complete guide to Dump/Load APIs
717 - [API Documentation](https://pkg.go.dev/go.yaml.in/yaml/v4) - Full API
718 reference
719 - [Examples](../example/README.md) - Runnable code examples