Skip to content
This repository was archived by the owner on Oct 9, 2024. It is now read-only.

Commit 6a2480e

Browse files
authored
fix: address timing issue with .env file watcher (#16)
1 parent 0ce12e4 commit 6a2480e

File tree

3 files changed

+12
-15
lines changed

3 files changed

+12
-15
lines changed

serve/config/dotenv.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,9 @@ func CreateDotEnv(workingDirectory string, onChange func(variables map[string]*s
2525
slog.Info(fmt.Sprintf("Detected .env file at %v. Reading variables and adding watch.", configEnvPath))
2626
env = parseDotEnv(configEnvPath)
2727
} else {
28-
slog.Info(fmt.Sprintf("Detected .env file at %v. Reading variables.", configEnvPath))
29-
env = parseDotEnv(filepath.Join(workingDirectory, ".env"))
28+
localEnv := filepath.Join(workingDirectory, ".env")
29+
slog.Info(fmt.Sprintf("Detected .env file at %v. Reading variables.", localEnv))
30+
env = parseDotEnv(localEnv)
3031
}
3132

3233
instance := DotEnv{

serve/config/filewatcher.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package config
33
import (
44
"log/slog"
55
"path"
6+
"time"
67

78
"github.com/fsnotify/fsnotify"
89
)
@@ -44,6 +45,12 @@ func CreateFileWatcher() *FileWatcher {
4445
if ok {
4546
for _, watchable := range watchables {
4647
if watchable.Name() == name {
48+
// When e.g. using os.WriteFile, the truncation already triggers
49+
// a change event, which results in the file being empty when
50+
// calling HandleChange.
51+
// Due to this, we wait for a millisecond, which should be enough for
52+
// the write operation to finish.
53+
time.Sleep(time.Millisecond)
4754
watchable.HandleChange()
4855
}
4956
return

serve/config/filewatcher_test.go

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -33,23 +33,12 @@ func TestShouldUpdateDotEnvOnChange(t *testing.T) {
3333

3434
test.AssertEqual(t, len(testEnv.env), 3)
3535

36-
f, err := os.OpenFile(envFilePath, os.O_WRONLY, 0666)
36+
err = os.WriteFile(envFilePath, []byte("TEST = example"), 0666)
3737
if err != nil {
3838
t.Fatalf("failed to write to file: %s", err)
3939
}
4040

41-
f.Sync()
42-
time.Sleep(time.Millisecond)
43-
f.WriteString("TEST = example")
44-
f.Sync()
45-
f.Close()
46-
47-
// This test is flaky on GitHub Actions, so we do this workaround
48-
counter := 0
49-
for counter < 200 && len(testEnv.env) != 1 {
50-
time.Sleep(time.Millisecond * 50)
51-
counter++
52-
}
41+
time.Sleep(time.Millisecond * 50)
5342

5443
test.AssertEqual(t, len(testEnv.env), 1)
5544
test.AssertEqual(t, readValue(t, testEnv.env, "TEST"), "example")

0 commit comments

Comments
 (0)