fix(init): error on invalid JSON instead of overwriting settings (#404)

Previously, setupClaudeSettings would silently create an empty settings
map when json.Unmarshal failed, then write just a prompt field to the
file - destroying all existing user settings (permissions, hooks, etc).

Now returns a clear error asking the user to fix the JSON syntax
manually, preserving their original file contents.

Also properly handles permission errors when reading existing files.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Jimmy Stridh <jimmystridh@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Jimmy Stridh
2025-11-29 03:51:27 +01:00
committed by GitHub
parent 1ec78c0b13
commit bb16f247c6
2 changed files with 173 additions and 1 deletions

View File

@@ -1324,9 +1324,15 @@ func setupClaudeSettings(verbose bool) error {
// #nosec G304 - user config path
if content, err := os.ReadFile(settingsPath); err == nil {
if err := json.Unmarshal(content, &existingSettings); err != nil {
existingSettings = make(map[string]interface{})
// Don't silently overwrite - the user has a file with invalid JSON
// that likely contains important settings they don't want to lose
return fmt.Errorf("existing %s contains invalid JSON: %w\nPlease fix the JSON syntax manually before running bd init", settingsPath, err)
}
} else if !os.IsNotExist(err) {
// File exists but couldn't be read (permissions issue, etc.)
return fmt.Errorf("failed to read existing %s: %w", settingsPath, err)
} else {
// File doesn't exist - create new empty settings
existingSettings = make(map[string]interface{})
}