From fbcbdf80fd38a71ee2060d442ed37dfeb7b0c59e Mon Sep 17 00:00:00 2001 From: Joe Chen Date: Sun, 15 Nov 2026 01:47:47 +0000 Subject: [PATCH 1/2] Add Marshal and Unmarshal Unmarshal maps INI data to a struct as StrictMapTo does, and Marshal reflects a struct into an empty file and writes it, so INI works like encoding/json for the common case (#337). --- doc.go | 7 ++++--- docs/migrate-v1-to-v2.md | 2 ++ example_test.go | 33 +++++++++++++++++++++++++++++++++ struct.go | 22 ++++++++++++++++++++++ struct_test.go | 22 ++++++++++++++++++++++ 5 files changed, 83 insertions(+), 3 deletions(-) diff --git a/doc.go b/doc.go index 51eba1f..cf72038 100644 --- a/doc.go +++ b/doc.go @@ -34,9 +34,10 @@ // # Structs // // [MapTo] and [StrictMapTo] fill a struct from a data source or a [File], -// and [File.ReflectFrom] fills a File from a struct. Field names map to key -// and section names unchanged unless [NameMapping] sets a mapper, and the -// ini, delim and comment struct tags adjust each field. A type that +// and [File.ReflectFrom] fills a File from a struct. [Marshal] and +// [Unmarshal] convert between a struct and INI text in one call. Field +// names map to key and section names unchanged unless [NameMapping] sets a +// mapper, and the ini, delim and comment struct tags adjust each field. A type that // implements [Marshaler] or [Unmarshaler] formats or parses its own values. // // # Writing diff --git a/docs/migrate-v1-to-v2.md b/docs/migrate-v1-to-v2.md index f3a58a8..fa70f06 100644 --- a/docs/migrate-v1-to-v2.md +++ b/docs/migrate-v1-to-v2.md @@ -123,6 +123,8 @@ Each `LoadOptions` field becomes an option function of the same name, such as `i New options: `CommentSymbols`, `PreserveEmptyShadowValues` and `DefaultSectionName`. +`Marshal` and `Unmarshal` convert between a struct and INI text in one call. + ### Writing The package variables that changed every file's output are now options of `File.Write` and `File.SaveTo`. Their defaults write what v1 wrote. diff --git a/example_test.go b/example_test.go index c274807..15ddd1f 100644 --- a/example_test.go +++ b/example_test.go @@ -134,6 +134,39 @@ func ExampleSection_MapTo() { // 9090 30s } +func ExampleMarshal() { + var cfg Config + cfg.AppName = "demo" + cfg.Server.Port = 8080 + cfg.Server.Hosts = []string{"a.example.com", "b.example.com"} + + data, err := ini.Marshal(&cfg) + if err != nil { + panic(err) + } + fmt.Print(string(data)) + // Output: + // app_name = demo + // + // [server] + // ; Port to listen on + // Port = 8080 + // Hosts = a.example.com,b.example.com +} + +// Unmarshal returns an error for a value that doesn't fit its field. +func ExampleUnmarshal() { + var cfg Config + err := ini.Unmarshal([]byte("app_name = demo\n[server]\nPort = 8080\nTimeout = 1m\n"), &cfg) + fmt.Println(cfg.AppName, cfg.Server.Port, cfg.Server.Timeout, err) + + err = ini.Unmarshal([]byte("[server]\nPort = eighty\n"), &cfg) + fmt.Println(err) + // Output: + // demo 8080 1m0s + // map to field "server": set field "Port": strconv.ParseInt: parsing "eighty": invalid syntax +} + func ExampleFile_Write() { f := ini.Empty() f.Section("").Key("name").SetValue("demo") diff --git a/struct.go b/struct.go index 25db8ff..090f239 100644 --- a/struct.go +++ b/struct.go @@ -594,6 +594,28 @@ func StrictMapTo(v, source any, opts ...LoadOption) error { return cfg.StrictMapTo(v) } +// Unmarshal parses the INI data and maps it to v, a pointer to a struct, as +// StrictMapTo does. Like json.Unmarshal, it returns an error for a value +// that doesn't fit its field. +func Unmarshal(data []byte, v any, opts ...LoadOption) error { + return StrictMapTo(v, data, opts...) +} + +// Marshal returns the INI encoding of v, a pointer to a struct, as +// File.ReflectFrom fills an empty file loaded with opts and File.WriteTo +// writes it. To set the formatting, call ReflectFrom and Write yourself. +func Marshal(v any, opts ...LoadOption) ([]byte, error) { + f := Empty(opts...) + if err := f.ReflectFrom(v); err != nil { + return nil, err + } + buf, err := f.writeToBuffer(nil) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} + // encodeSlice does the opposite thing as decodeSlice. func encodeSlice(key *Key, field reflect.Value, delim string, allowShadow bool) error { if field.Len() == 0 { diff --git a/struct_test.go b/struct_test.go index 59625b4..af64e38 100644 --- a/struct_test.go +++ b/struct_test.go @@ -822,6 +822,28 @@ func Test_NameGetter(t *testing.T) { }) } +func TestMarshalUnmarshal(t *testing.T) { + type config struct { + AppName string + Server struct{ ListenPort int } + } + var in config + in.AppName = "demo" + in.Server.ListenPort = 8080 + + // Options reach both directions. + data, err := Marshal(&in, NameMapping(SnakeCase)) + require.NoError(t, err) + assert.Equal(t, "APP_NAME = demo\n\n[SERVER]\nLISTEN_PORT = 8080\n", string(data)) + + var out config + require.NoError(t, Unmarshal(data, &out, NameMapping(SnakeCase))) + assert.Equal(t, in, out) + + _, err = Marshal(in) + assert.Error(t, err) +} + type testDurationStruct struct { Duration time.Duration `ini:"Duration"` } From 2a48c17fc040318cc448c90596d8146f96b5bab1 Mon Sep 17 00:00:00 2001 From: Joe Chen Date: Sun, 15 Nov 2026 01:48:36 +0000 Subject: [PATCH 2/2] Move Marshal docs and test away from the StructTag changes --- doc.go | 10 +++++---- docs/migrate-v1-to-v2.md | 4 ++-- struct_test.go | 44 ++++++++++++++++++++-------------------- 3 files changed, 30 insertions(+), 28 deletions(-) diff --git a/doc.go b/doc.go index cf72038..921e47f 100644 --- a/doc.go +++ b/doc.go @@ -34,12 +34,14 @@ // # Structs // // [MapTo] and [StrictMapTo] fill a struct from a data source or a [File], -// and [File.ReflectFrom] fills a File from a struct. [Marshal] and -// [Unmarshal] convert between a struct and INI text in one call. Field -// names map to key and section names unchanged unless [NameMapping] sets a -// mapper, and the ini, delim and comment struct tags adjust each field. A type that +// and [File.ReflectFrom] fills a File from a struct. Field names map to key +// and section names unchanged unless [NameMapping] sets a mapper, and the +// ini, delim and comment struct tags adjust each field. A type that // implements [Marshaler] or [Unmarshaler] formats or parses its own values. // +// [Marshal] and [Unmarshal] convert between a struct and INI text in one +// call, as encoding/json does. +// // # Writing // // [File.Write] and [File.SaveTo] write a File back with its comments and in diff --git a/docs/migrate-v1-to-v2.md b/docs/migrate-v1-to-v2.md index fa70f06..d9bf7a7 100644 --- a/docs/migrate-v1-to-v2.md +++ b/docs/migrate-v1-to-v2.md @@ -123,8 +123,6 @@ Each `LoadOptions` field becomes an option function of the same name, such as `i New options: `CommentSymbols`, `PreserveEmptyShadowValues` and `DefaultSectionName`. -`Marshal` and `Unmarshal` convert between a struct and INI text in one call. - ### Writing The package variables that changed every file's output are now options of `File.Write` and `File.SaveTo`. Their defaults write what v1 wrote. @@ -142,6 +140,8 @@ The package variables that changed every file's output are now options of `File. `WriteTo` stays, so `*File` is still an `io.WriterTo`. +New: `Marshal(&v)` and `Unmarshal(data, &v)` convert between a struct and INI text in one call, as `encoding/json` does. + ### Sections and keys | v1 | v2 | diff --git a/struct_test.go b/struct_test.go index af64e38..99212c3 100644 --- a/struct_test.go +++ b/struct_test.go @@ -822,28 +822,6 @@ func Test_NameGetter(t *testing.T) { }) } -func TestMarshalUnmarshal(t *testing.T) { - type config struct { - AppName string - Server struct{ ListenPort int } - } - var in config - in.AppName = "demo" - in.Server.ListenPort = 8080 - - // Options reach both directions. - data, err := Marshal(&in, NameMapping(SnakeCase)) - require.NoError(t, err) - assert.Equal(t, "APP_NAME = demo\n\n[SERVER]\nLISTEN_PORT = 8080\n", string(data)) - - var out config - require.NoError(t, Unmarshal(data, &out, NameMapping(SnakeCase))) - assert.Equal(t, in, out) - - _, err = Marshal(in) - assert.Error(t, err) -} - type testDurationStruct struct { Duration time.Duration `ini:"Duration"` } @@ -1822,3 +1800,25 @@ func (*testUnmarshalOnlyList) UnmarshalINI([]byte) error { panic("called") } func (testMarshalOnlyStruct) MarshalINI() ([]byte, error) { panic("called") } func (testMarshalOnlyMap) MarshalINI() ([]byte, error) { panic("called") } + +func TestMarshalUnmarshal(t *testing.T) { + type config struct { + AppName string + Server struct{ ListenPort int } + } + var in config + in.AppName = "demo" + in.Server.ListenPort = 8080 + + // Options reach both directions. + data, err := Marshal(&in, NameMapping(SnakeCase)) + require.NoError(t, err) + assert.Equal(t, "APP_NAME = demo\n\n[SERVER]\nLISTEN_PORT = 8080\n", string(data)) + + var out config + require.NoError(t, Unmarshal(data, &out, NameMapping(SnakeCase))) + assert.Equal(t, in, out) + + _, err = Marshal(in) + assert.Error(t, err) +}