From d4afcb63c1e3935e86771be990f48971f59278b0 Mon Sep 17 00:00:00 2001 From: wissaaamm <172216098+wissaaamm@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:40:53 +0200 Subject: [PATCH] Keep concurrently appended sources when reloading --- file.go | 24 ++++++++++++++-------- reload_test.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 8 deletions(-) create mode 100644 reload_test.go diff --git a/file.go b/file.go index eb12f32..5865378 100644 --- a/file.go +++ b/file.go @@ -418,15 +418,23 @@ func (f *File) loadSource(s dataSource) error { // *Section and *Key values, so pointers to them see the new contents. On // error the file is unchanged. func (f *File) Reload() error { - f.maybeRLock() - sources := f.dataSources - f.maybeRUnlock() - next := &File{options: f.options, byName: make(map[string][]*Section)} - if err := next.load(sources); err != nil { - return err - } + var next *File + for { + f.maybeRLock() + sources := f.dataSources + f.maybeRUnlock() + next = &File{options: f.options, byName: make(map[string][]*Section)} + if err := next.load(sources); err != nil { + return err + } - f.maybeLock() + f.maybeLock() + if len(sources) == len(f.dataSources) { + break + } + // Append added sources while we were loading. Retry with the full list. + f.maybeUnlock() + } defer f.maybeUnlock() for name, secs := range next.byName { old := f.byName[name] diff --git a/reload_test.go b/reload_test.go new file mode 100644 index 0000000..341f5bb --- /dev/null +++ b/reload_test.go @@ -0,0 +1,54 @@ +package ini + +import ( + "sync" + "testing" +) + +type blockingReloadSource struct { + dataSource + once sync.Once + started chan struct{} + resume chan struct{} +} + +func (s *blockingReloadSource) read() (string, error) { + s.once.Do(func() { + close(s.started) + <-s.resume + }) + return s.dataSource.read() +} + +func TestFile_ReloadKeepsConcurrentAppend(t *testing.T) { + f, err := Load([]byte("base = original\n")) + if err != nil { + t.Fatal(err) + } + source := &blockingReloadSource{ + dataSource: f.dataSources[0], + started: make(chan struct{}), + resume: make(chan struct{}), + } + f.dataSources[0] = source + + reloaded := make(chan error, 1) + go func() { reloaded <- f.Reload() }() + <-source.started + + // Reload has captured its source list. Append before letting it continue. + err = f.Append([]byte("base = updated\nextra = present\n")) + close(source.resume) + if err != nil { + t.Fatal(err) + } + if err := <-reloaded; err != nil { + t.Fatal(err) + } + if got := f.Section("").Key("base").String(); got != "updated" { + t.Errorf("base = %q, want updated", got) + } + if got := f.Section("").Key("extra").String(); got != "present" { + t.Errorf("extra = %q, want present", got) + } +}