Return error from GetDefaultStateDir when home directory unavailable
When os.UserConfigDir() fails, DetermineStateDir falls back to os.UserHomeDir(). Previously the error from UserHomeDir was discarded, which could result in a dangerous root-relative path (/.config/...) if both calls fail. Now DetermineStateDir returns (string, error) and propagates failures from both UserConfigDir and UserHomeDir. Closes #14
This commit is contained in:
@@ -28,16 +28,17 @@ func generateRandomString(length int, charset string) (string, error) {
|
||||
return string(result), nil
|
||||
}
|
||||
|
||||
// DetermineStateDir determines the state directory based on environment variables and OS
|
||||
func DetermineStateDir(customConfigDir string) string {
|
||||
// DetermineStateDir determines the state directory based on environment variables and OS.
|
||||
// It returns an error if no usable directory can be determined.
|
||||
func DetermineStateDir(customConfigDir string) (string, error) {
|
||||
// Check for environment variable first
|
||||
if envStateDir := os.Getenv(EnvStateDir); envStateDir != "" {
|
||||
return envStateDir
|
||||
return envStateDir, nil
|
||||
}
|
||||
|
||||
// Use custom config dir if provided
|
||||
if customConfigDir != "" {
|
||||
return filepath.Join(customConfigDir, AppID)
|
||||
return filepath.Join(customConfigDir, AppID), nil
|
||||
}
|
||||
|
||||
// Use os.UserConfigDir() which handles platform-specific directories:
|
||||
@@ -47,10 +48,13 @@ func DetermineStateDir(customConfigDir string) string {
|
||||
configDir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
// Fallback to a reasonable default if we can't determine user config dir
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
homeDir, homeErr := os.UserHomeDir()
|
||||
if homeErr != nil {
|
||||
return "", fmt.Errorf("unable to determine state directory: config dir: %w, home dir: %w", err, homeErr)
|
||||
}
|
||||
|
||||
return filepath.Join(homeDir, ".config", AppID)
|
||||
return filepath.Join(homeDir, ".config", AppID), nil
|
||||
}
|
||||
|
||||
return filepath.Join(configDir, AppID)
|
||||
return filepath.Join(configDir, AppID), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user