From d76a18aa92b0fd39d101c76f86fd21a18cc0a6bf Mon Sep 17 00:00:00 2001 From: Arne Luenser Date: Tue, 19 Nov 2024 22:34:50 +0100 Subject: [PATCH] fix: don't leak goroutines if there are no files to watch --- configx/provider.go | 6 +++++- configx/provider_watch_test.go | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/configx/provider.go b/configx/provider.go index f5c1e665..51a931c4 100644 --- a/configx/provider.go +++ b/configx/provider.go @@ -142,8 +142,12 @@ func (p *Provider) createProviders(ctx context.Context) (providers []koanf.Provi p.logger.WithField("files", paths).Debug("Adding config files.") c := make(watcherx.EventChannel) - go p.watchForFileChanges(ctx, c) + defer func() { + if err == nil && len(paths) > 0 { + go p.watchForFileChanges(ctx, c) + } + }() for _, path := range paths { fp, err := NewKoanfFile(path) if err != nil { diff --git a/configx/provider_watch_test.go b/configx/provider_watch_test.go index 22dd1749..f8e3193b 100644 --- a/configx/provider_watch_test.go +++ b/configx/provider_watch_test.go @@ -49,11 +49,11 @@ func assertNoOpenFDs(t require.TestingT, dir, name string) { } var b, be bytes.Buffer // we are only interested in the file descriptors, so we use the `-F f` option - c := exec.Command("lsof", "-n", "-F", "f", filepath.Join(dir, name)) + c := exec.Command("lsof", "-n", "-F", "f", "--", filepath.Join(dir, name)) c.Stdout = &b c.Stderr = &be exitErr := new(exec.ExitError) - require.ErrorAs(t, c.Run(), &exitErr, "got stout: %s\nstderr: %s", b.String(), be.String()) + require.ErrorAsf(t, c.Run(), &exitErr, "File %q has open file descriptor.\nGot stout: %s\nstderr: %s", filepath.Join(dir, name), b.String(), be.String()) assert.Equal(t, 1, exitErr.ExitCode(), "got stout: %s\nstderr: %s", b.String(), be.String()) }