feat: honour the omitzero and omitempty tag options on encode

Assisted-by: GLM 5.3 Flash
This commit is contained in:
2026-09-17 19:57:23 +02:00
parent 58e7dfb1d0
commit 93c36cf376
6 changed files with 160 additions and 4 deletions
+79
View File
@@ -748,6 +748,85 @@ func TestMarshalEmbeddedStructAsTable(t *testing.T) {
}
}
func TestMarshalTagOptionOmitZero(t *testing.T) {
type Server struct {
Host string `toml:"host"`
}
type Cfg struct {
Name string `toml:"name,omitzero"`
Count int `toml:"count,omitzero"`
Ratio float64 `toml:"ratio,omitzero"`
When time.Time `toml:"when,omitzero"`
Server Server `toml:"server,omitzero"`
Always string `toml:"always"`
}
out, err := Marshal(Cfg{Always: "kept"})
if err != nil {
t.Fatalf("marshal: %v", err)
}
// Every omitzero field sits at its zero value, so only always is emitted.
want := "always = \"kept\"\n"
if string(out) != want {
t.Fatalf("output mismatch:\ngot: %q\nwant: %q", out, want)
}
when := time.Date(2026, 9, 17, 12, 0, 0, 0, time.UTC)
out, err = Marshal(Cfg{Name: "x", Count: 1, Ratio: 0.5, When: when, Server: Server{Host: "h"}, Always: "kept"})
if err != nil {
t.Fatalf("marshal: %v", err)
}
want = "name = \"x\"\ncount = 1\nratio = 0.5\nwhen = 2026-09-17T12:00:00Z\nalways = \"kept\"\n\n[server]\nhost = \"h\"\n"
if string(out) != want {
t.Fatalf("output mismatch:\ngot: %q\nwant: %q", out, want)
}
}
func TestMarshalTagOptionOmitEmpty(t *testing.T) {
type Cfg struct {
Tags []string `toml:"tags,omitempty"`
Ports []int `toml:"ports,omitempty"`
Matrix [][]int `toml:"matrix,omitempty"`
Extra map[string]any `toml:"extra,omitempty"`
Name string `toml:"name,omitempty"`
Keep []string `toml:"keep"`
}
out, err := Marshal(Cfg{
Ports: []int{},
Matrix: [][]int{{1}},
Extra: map[string]any{},
Name: "set",
Keep: []string{},
})
if err != nil {
t.Fatalf("marshal: %v", err)
}
// tags is nil (omitted anyway), ports and extra are empty collections
// dropped by omitempty, matrix is populated, name is a string the option
// does not cover, keep is empty but carries no option so it emits [].
want := "matrix = [[1]]\nname = \"set\"\nkeep = []\n"
if string(out) != want {
t.Fatalf("output mismatch:\ngot: %q\nwant: %q", out, want)
}
}
func TestMarshalTagOptionOnTaggedEmbeddedStruct(t *testing.T) {
type Inner struct {
N int `toml:"n"`
}
type Cfg struct {
Inner Inner `toml:"inner,omitzero"`
Name string `toml:"name"`
}
out, err := Marshal(Cfg{Name: "x"})
if err != nil {
t.Fatalf("marshal: %v", err)
}
want := "name = \"x\"\n"
if string(out) != want {
t.Fatalf("output mismatch:\ngot: %q\nwant: %q", out, want)
}
}
func TestMarshalMapKeysSorted(t *testing.T) {
m := map[string]any{
"zeta": 1,