diff --git a/serve/config/dotenv.go b/serve/config/dotenv.go index 178c6f8..125bff3 100644 --- a/serve/config/dotenv.go +++ b/serve/config/dotenv.go @@ -25,8 +25,9 @@ func CreateDotEnv(workingDirectory string, onChange func(variables map[string]*s slog.Info(fmt.Sprintf("Detected .env file at %v. Reading variables and adding watch.", configEnvPath)) env = parseDotEnv(configEnvPath) } else { - slog.Info(fmt.Sprintf("Detected .env file at %v. Reading variables.", configEnvPath)) - env = parseDotEnv(filepath.Join(workingDirectory, ".env")) + localEnv := filepath.Join(workingDirectory, ".env") + slog.Info(fmt.Sprintf("Detected .env file at %v. Reading variables.", localEnv)) + env = parseDotEnv(localEnv) } instance := DotEnv{ diff --git a/serve/config/filewatcher.go b/serve/config/filewatcher.go index c3bb8f7..18c1fff 100644 --- a/serve/config/filewatcher.go +++ b/serve/config/filewatcher.go @@ -3,6 +3,7 @@ package config import ( "log/slog" "path" + "time" "github.com/fsnotify/fsnotify" ) @@ -44,6 +45,12 @@ func CreateFileWatcher() *FileWatcher { if ok { for _, watchable := range watchables { if watchable.Name() == name { + // When e.g. using os.WriteFile, the truncation already triggers + // a change event, which results in the file being empty when + // calling HandleChange. + // Due to this, we wait for a millisecond, which should be enough for + // the write operation to finish. + time.Sleep(time.Millisecond) watchable.HandleChange() } return diff --git a/serve/config/filewatcher_test.go b/serve/config/filewatcher_test.go index 513b93b..a8247d6 100644 --- a/serve/config/filewatcher_test.go +++ b/serve/config/filewatcher_test.go @@ -33,23 +33,12 @@ func TestShouldUpdateDotEnvOnChange(t *testing.T) { test.AssertEqual(t, len(testEnv.env), 3) - f, err := os.OpenFile(envFilePath, os.O_WRONLY, 0666) + err = os.WriteFile(envFilePath, []byte("TEST = example"), 0666) if err != nil { t.Fatalf("failed to write to file: %s", err) } - f.Sync() - time.Sleep(time.Millisecond) - f.WriteString("TEST = example") - f.Sync() - f.Close() - - // This test is flaky on GitHub Actions, so we do this workaround - counter := 0 - for counter < 200 && len(testEnv.env) != 1 { - time.Sleep(time.Millisecond * 50) - counter++ - } + time.Sleep(time.Millisecond * 50) test.AssertEqual(t, len(testEnv.env), 1) test.AssertEqual(t, readValue(t, testEnv.env, "TEST"), "example")