feat: add global OmitEmpty encoding option (#691)

Thanks for an amazing project! Go ecosystem struggle (e.g. https://github.com/GoogleCloudPlatform/prometheus-engine/issues/1629)
with 3P types that lack a good marshalling practices. Many project have
config structs only designed for parsing. See https://github.com/goccy/go-yaml/issues/306
for the detailed motivation.

Fixes: https://github.com/goccy/go-yaml/issues/306

The feature mechanism is simple -- we ignore struct tag setting for omitempty.
We assume it's always 'omitempty' if yaml.OmitEmpty() setting is set.

Signed-off-by: bwplotka <bwplotka@gmail.com>
This commit is contained in:
Bartlomiej Plotka 2025-04-11 12:13:15 +02:00 committed by GitHub
parent ba0598a7f0
commit ee37df774b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 34 additions and 9 deletions

View file

@ -465,7 +465,7 @@ func TestEncoder(t *testing.T) {
nil,
},
// Conditional flag
// Omitempty flag.
{
"a: 1\n",
struct {
@ -482,7 +482,6 @@ func TestEncoder(t *testing.T) {
}{0, 0},
nil,
},
{
"a:\n \"y\": \"\"\n",
struct {
@ -496,7 +495,6 @@ func TestEncoder(t *testing.T) {
}{}},
nil,
},
{
"a: {}\n",
struct {
@ -510,7 +508,6 @@ func TestEncoder(t *testing.T) {
}{}},
nil,
},
{
"a: {x: 1}\n",
struct {
@ -518,7 +515,6 @@ func TestEncoder(t *testing.T) {
}{&struct{ X, y int }{1, 2}},
nil,
},
{
"{}\n",
struct {
@ -526,7 +522,6 @@ func TestEncoder(t *testing.T) {
}{nil},
nil,
},
{
"a: {x: 0}\n",
struct {
@ -534,7 +529,6 @@ func TestEncoder(t *testing.T) {
}{&struct{ X, y int }{}},
nil,
},
{
"a: {x: 1}\n",
struct {
@ -567,8 +561,29 @@ func TestEncoder(t *testing.T) {
},
nil,
},
// OmitEmpty global option.
{
"a: 1\n",
struct {
A int
B int `yaml:"b,omitempty"`
}{1, 0},
[]yaml.EncodeOption{
yaml.OmitEmpty(),
},
},
{
"{}\n",
struct {
A int
B int `yaml:"b,omitempty"`
}{0, 0},
[]yaml.EncodeOption{
yaml.OmitEmpty(),
},
},
// Flow flag
// Flow flag.
{
"a: [1, 2]\n",
struct {