Skip to content

Commit 2ac8cff

Browse files
authored
fix format with empty value (#654)
1 parent 548e1b8 commit 2ac8cff

File tree

2 files changed

+38
-8
lines changed

2 files changed

+38
-8
lines changed

decode_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3196,6 +3196,41 @@ foo:
31963196
}
31973197
}
31983198

3199+
func TestBytesUnmarshalerWithEmptyValue(t *testing.T) {
3200+
type T struct{}
3201+
3202+
unmarshaler := func(dst *T, b []byte) error {
3203+
var v any
3204+
return yaml.Unmarshal(b, &v)
3205+
}
3206+
3207+
yml := `
3208+
map: &m {}
3209+
seq: &seq []
3210+
foo: # comment
3211+
bar: *m
3212+
baz: *seq
3213+
`
3214+
m := yaml.CommentMap{}
3215+
var v T
3216+
if err := yaml.UnmarshalWithOptions(
3217+
[]byte(yml),
3218+
&v,
3219+
yaml.CommentToMap(m),
3220+
yaml.CustomUnmarshaler[T](unmarshaler),
3221+
); err != nil {
3222+
t.Fatal(err)
3223+
}
3224+
if err := yaml.UnmarshalWithOptions(
3225+
[]byte(yml),
3226+
&v,
3227+
yaml.CustomUnmarshaler[T](unmarshaler),
3228+
); err != nil {
3229+
t.Fatal(err)
3230+
}
3231+
3232+
}
3233+
31993234
func TestIssue650(t *testing.T) {
32003235
type Disk struct {
32013236
Name string `yaml:"name"`

internal/format/format.go

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,9 @@ func (f *Formatter) formatFile(file *ast.File) string {
284284
}
285285

286286
func (f *Formatter) origin(tk *token.Token) string {
287+
if tk == nil {
288+
return ""
289+
}
287290
if f.existsComment {
288291
return tk.Origin
289292
}
@@ -349,10 +352,6 @@ func (f *Formatter) formatDirective(n *ast.DirectiveNode) string {
349352
}
350353

351354
func (f *Formatter) formatMapping(n *ast.MappingNode) string {
352-
if len(n.Values) == 0 {
353-
return "{}"
354-
}
355-
356355
var ret string
357356
if n.IsFlowStyle {
358357
ret = f.origin(n.Start)
@@ -379,10 +378,6 @@ func (f *Formatter) formatMappingKey(n *ast.MappingKeyNode) string {
379378
}
380379

381380
func (f *Formatter) formatSequence(n *ast.SequenceNode) string {
382-
if len(n.Values) == 0 {
383-
return "[]"
384-
}
385-
386381
var ret string
387382
if n.IsFlowStyle {
388383
ret = f.origin(n.Start)

0 commit comments

Comments
 (0)