Skip to content

Commit 75e44d8

Browse files
committed
Use exclusive file creation in Init() to prevent race conditions
1 parent 5b48046 commit 75e44d8

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

internal/config/config.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package config
22

33
import (
44
_ "embed"
5+
"errors"
56
"fmt"
67
"os"
78
"path/filepath"
@@ -64,8 +65,20 @@ func Init() error {
6465
}
6566

6667
configPath := filepath.Join(creationDir, userConfigFileName)
67-
if err := os.WriteFile(configPath, []byte(defaultConfigTemplate), 0644); err != nil {
68-
return fmt.Errorf("failed to write config file: %w", err)
68+
f, err := os.OpenFile(configPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
69+
if err != nil {
70+
if errors.Is(err, os.ErrExist) {
71+
return loadConfig(configPath)
72+
}
73+
return fmt.Errorf("failed to create config file: %w", err)
74+
}
75+
_, writeErr := f.WriteString(defaultConfigTemplate)
76+
closeErr := f.Close()
77+
if writeErr != nil {
78+
return fmt.Errorf("failed to write config file: %w", writeErr)
79+
}
80+
if closeErr != nil {
81+
return fmt.Errorf("failed to close config file: %w", closeErr)
6982
}
7083

7184
return loadConfig(configPath)

0 commit comments

Comments
 (0)