Dan Anglin
d38431d9e8
Summary: If the user hasn't supplied the path to a configuration directory and Enbas fails to find the user's default home configuration directory, Enbas will now return an error message back to the user. Previously Enbas would try to, instead, calculate the configuration directory using the user's current directory. Changes: - Return an error if the user's home configuration directory cannot be found. - Add tests to the internal.config package. - Update the tests in internal.utilities package. PR: #54
78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
package utilities
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"codeflow.dananglin.me.uk/apollo/enbas/internal"
|
|
)
|
|
|
|
const (
|
|
cacheMediaDir = "media"
|
|
cacheStatusesDir = "statuses"
|
|
)
|
|
|
|
func CalculateConfigDir(configDir string) (string, error) {
|
|
if configDir != "" {
|
|
return configDir, nil
|
|
}
|
|
|
|
configRoot, err := os.UserConfigDir()
|
|
if err != nil {
|
|
return "", fmt.Errorf("unable to get your default config diretory: %w", err)
|
|
}
|
|
|
|
return filepath.Join(configRoot, internal.ApplicationName), nil
|
|
}
|
|
|
|
func CalculateMediaCacheDir(cacheRoot, instance string) (string, error) {
|
|
cacheDir, err := calculateCacheDir(cacheRoot, instance)
|
|
if err != nil {
|
|
return "", fmt.Errorf("unable to calculate the cache directory: %w", err)
|
|
}
|
|
|
|
return filepath.Join(cacheDir, cacheMediaDir), nil
|
|
}
|
|
|
|
func CalculateStatusesCacheDir(cacheRoot, instance string) (string, error) {
|
|
cacheDir, err := calculateCacheDir(cacheRoot, instance)
|
|
if err != nil {
|
|
return "", fmt.Errorf("unable to calculate the cache directory: %w", err)
|
|
}
|
|
|
|
return filepath.Join(cacheDir, cacheStatusesDir), nil
|
|
}
|
|
|
|
func calculateCacheDir(cacheRoot, instance string) (string, error) {
|
|
fqdn := GetFQDN(instance)
|
|
|
|
if cacheRoot != "" {
|
|
return filepath.Join(cacheRoot, fqdn), nil
|
|
}
|
|
|
|
cacheRoot, err := os.UserCacheDir()
|
|
if err != nil {
|
|
return "", fmt.Errorf("unable to get your default cache directory: %w", err)
|
|
}
|
|
|
|
return filepath.Join(cacheRoot, internal.ApplicationName, fqdn), nil
|
|
}
|
|
|
|
func EnsureDirectory(dir string) error {
|
|
if _, err := os.Stat(dir); err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
if err := os.MkdirAll(dir, 0o750); err != nil {
|
|
return fmt.Errorf("unable to create %s: %w", dir, err)
|
|
}
|
|
} else {
|
|
return fmt.Errorf(
|
|
"received an unknown error after getting the directory information: %w",
|
|
err,
|
|
)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|