Debian Codegraph @

docs/v3-to-v4-migration.md

raw symbols SCIP
1 # Migrating from v3 to v4
2
3 This guide will help you migrate your code from `go.yaml.in/yaml/v3`
4 (or `gopkg.in/yaml.v3`) to `go.yaml.in/yaml/v4`.
5
6 ## Quick Migration Checklist
7
8 - [ ] Update import path
9 - [ ] Optionally migrate to new API (Load/Dump, Loader/Dumper)
10 - [ ] Adjust formatting expectations or use yaml.WithV3Defaults() preset
11 - [ ] Update tests
12
13 ## Import Path Change
14
15 **v3:**
16 ```go
17 import "gopkg.in/yaml.v3"
18 // or
19 import "go.yaml.in/yaml/v3"
20 ```
21
22 **v4:**
23 ```go
24 import "go.yaml.in/yaml/v4"
25 ```
26
27 Update all import statements throughout your codebase.
28
29 ## API Changes
30
31 ### Recommended: Use New API
32
33 v4 introduces a cleaner API with better naming.
34
35 #### Loading YAML
36
37 **v3:**
38 ```go
39 err := yaml.Unmarshal(data, &config)
40 ```
41
42 **v4:**
43 ```go
44 err := yaml.Load(data, &config)
45 ```
46
47 #### Dumping YAML
48
49 **v3:**
50 ```go
51 data, err := yaml.Marshal(&config)
52 ```
53
54 **v4:**
55 ```go
56 data, err := yaml.Dump(&config)
57 ```
58
59 #### Streaming Decoding
60
61 **v3:**
62 ```go
63 decoder := yaml.NewDecoder(reader)
64 err := decoder.Decode(&config)
65 ```
66
67 **v4:**
68 ```go
69 loader := yaml.NewLoader(reader)
70 err := loader.Load(&config)
71 ```
72
73 #### Streaming Encoding
74
75 **v3:**
76 ```go
77 encoder := yaml.NewEncoder(writer)
78 err := encoder.Encode(&config)
79 encoder.Close()
80 ```
81
82 **v4:**
83 ```go
84 dumper := yaml.NewDumper(writer)
85 err := dumper.Dump(&config)
86 dumper.Close()
87 ```
88
89 ## New Features in v4
90
91 ### Stream Nodes
92
93 v4 adds `StreamNode`, a new node kind that exposes stream-level
94 metadata not available in v3: encoding, `%YAML` version directives,
95 and `%TAG` directives.
96 This is accessed via `Node.Stream`, which is non-nil only on
97 `StreamNode` nodes.
98
99 Enable stream nodes with `WithStreamNodes()`:
100
101 ```go
102 loader := yaml.NewLoader(reader, yaml.WithStreamNodes())
103 for {
104 var node yaml.Node
105 err := loader.Load(&node)
106 if errors.Is(err, io.EOF) {
107 break
108 }
109 if node.Kind == yaml.StreamNode && node.Stream != nil {
110 enc := node.Stream.Encoding
111 ver := node.Stream.Version // *yaml.VersionDirective
112 tags := node.Stream.TagDirectives // []yaml.TagDirective
113 }
114 }
115 ```
116
117 With stream nodes enabled, the loader emits nodes in the pattern
118 `[Stream, Doc, Stream, Doc, ..., Stream]` — one opening stream node
119 per document boundary, plus a final closing stream node.
120
121 ### Functional Options
122
123 v4 introduces a functional options pattern for configuration:
124
125 ```go
126 // Version presets
127 yaml.Dump(&data, yaml.WithV2Defaults()) // Use v2 defaults
128 yaml.Dump(&data, yaml.WithV3Defaults()) // Use v3 defaults
129 yaml.Dump(&data, yaml.WithV4Defaults()) // Use v4 defaults (2-space, compact)
130
131 // Custom options
132 yaml.Dump(&data,
133 yaml.WithIndent(4),
134 yaml.WithCompactSeqIndent(false),
135 yaml.WithLineWidth(100),
136 )
137
138 // Combine presets with overrides
139 yaml.Dump(&data, yaml.WithV3Defaults(), yaml.WithIndent(2))
140
141 // Loading options
142 yaml.Load(data, &config,
143 yaml.WithKnownFields(), // Strict field checking
144 yaml.WithUniqueKeys(), // Enforce unique keys
145 )
146 ```
147
148 Available dump options:
149 - `WithIndent(n)` - Set indentation spaces
150 - `WithCompactSeqIndent(bool)` - Compact sequence indentation
151 - `WithLineWidth(n)` - Maximum line width
152 - `WithUnicode(bool)` - Use Unicode characters
153 - `WithCanonical(bool)` - Canonical output format
154 - `WithLineBreak(lb)` - Line break style (LN, CR, CRLN)
155 - `WithExplicitStart(bool)` - Add `---` document start
156 - `WithExplicitEnd(bool)` - Add `...` document end
157 - `WithFlowSimpleCollections(bool)` - Use flow style for simple
158 collections
159
160 Available load options:
161 - `WithKnownFields()` - Reject unknown struct fields
162 - `WithUniqueKeys()` - Enforce unique mapping keys
163 - `WithSingleDocument()` - Expect only one document
164
165 ### Options from YAML
166
167 You can configure options using YAML:
168
169 ```go
170 optsYAML := `
171 indent: 4
172 compact-seq-indent: false
173 line-width: 100
174 `
175
176 opts, err := yaml.OptsYAML(optsYAML)
177 if err != nil {
178 log.Fatal(err)
179 }
180
181 data, err := yaml.Dump(&config, opts)
182 ```
183
184 ## Formatting Differences
185
186 v4 has different default formatting than v3:
187
188 | Aspect | v3 Default | v4 Default |
189 |--------|-----------|-----------|
190 | Indentation | 4 spaces | 2 spaces |
191 | Sequence style | Normal | Compact |
192
193 **Example:**
194
195 ```yaml
196 # v3 default output
197 items:
198 - name: foo
199 value: 1
200 - name: bar
201 value: 2
202
203 # v4 default output
204 items:
205 - name: foo
206 value: 1
207 - name: bar
208 value: 2
209 ```
210
211 ### Preserving v3 Behavior
212
213 If you need v3's formatting, use the `yaml.WithV3Defaults()` preset:
214
215 ```go
216 // Get v3-style formatting in v4
217 data, err := yaml.Dump(&config, yaml.WithV3Defaults())
218 ```
219
220 Or customize individual options:
221
222 ```go
223 data, err := yaml.Dump(&config,
224 yaml.WithIndent(4),
225 yaml.WithCompactSeqIndent(false),
226 )
227 ```
228
229 ## Backward Compatibility
230
231 All v3 APIs continue to work in v4. The classic API remains supported
232 for simple use cases:
233
234 - `Unmarshal()` - Classic API (or use `Load()` for more flexibility)
235 - `Marshal()` - Classic API (or use `Dump()` for more flexibility)
236 - `NewDecoder()` - Classic API (or use `NewLoader()` for more flexibility)
237 - `NewEncoder()` - Classic API (or use `NewDumper()` for more flexibility)
238
239 You can migrate incrementally:
240 1. Update import path to v4
241 2. Verify tests pass
242 3. Optionally migrate to new API for additional features
243 4. Update TypeError.Errors handling if applicable
244
245 ## Migration Strategies
246
247 ### Strategy 1: Minimal Change (Fastest)
248
249 1. Update import path
250 2. If using TypeError.Errors directly, update that code
251 3. Add `yaml.WithV3Defaults()` preset to maintain v3 formatting
252 4. Done!
253
254 ```go
255 // Only change needed for basic migration
256 data, err := yaml.Dump(&config, yaml.WithV3Defaults())
257 ```
258
259 ### Strategy 2: Adopt New API (Recommended)
260
261 1. Update import path
262 2. Replace `Unmarshal` → `Load`, `Marshal` → `Dump`
263 3. Replace `NewDecoder` → `NewLoader`, `NewEncoder` → `NewDumper`
264 4. Test with v4 defaults or choose formatting explicitly
265
266 ### Strategy 3: Feature Adoption (Maximum Value)
267
268 1. Follow Strategy 2
269 2. Explore new functional options
270 3. Leverage structured error information
271 4. Adopt version presets for different use cases
272
273 ## Testing Your Migration
274
275 ```bash
276 # Run your existing tests
277 go test ./...
278
279 # Verify YAML output formatting
280 # Use the go-yaml CLI tool to compare
281 go install go.yaml.in/yaml/v4/cmd/go-yaml@latest
282 ./go-yaml -n < testfile.yaml
283 ```
284
285 ## Common Issues
286
287 ### Issue: Output formatting changed
288
289 **Solution:** Use `yaml.WithV3Defaults()` preset to maintain v3 formatting:
290 ```go
291 yaml.Dump(&data, yaml.WithV3Defaults())
292 ```
293
294 ### Issue: Want more flexibility from classic API
295
296 **Solution:** Migrate to the new API for options support:
297 - `Unmarshal` → `Load`
298 - `Marshal` → `Dump`
299 - `NewDecoder` → `NewLoader`
300 - `NewEncoder` → `NewDumper`
301
302 ## Getting Help
303
304 If you encounter issues during migration:
305
306 - Check the [API documentation](https://pkg.go.dev/go.yaml.in/yaml/v4)
307 - Browse [examples](example/)
308 - Open an [issue](https://github.com/yaml/go-yaml/issues)
309 - Ask in [Slack](https://cloud-native.slack.com/archives/C08PPAT8PS7)
310
311 ## Next Steps
312
313 - Explore the new [functional options](#functional-options)
314 - Review the [examples](example/) directory
315 - Read the [full API documentation](
316 https://pkg.go.dev/go.yaml.in/yaml/v4)
317 - Try the [go-yaml CLI tool](README.md#the-go-yaml-cli-tool) for
318 debugging