manager/magefiles/internal/config/config.go

113 lines
2.8 KiB
Go
Raw Normal View History

package config
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
const configDir string = "hosts"
type Config struct {
ManagedConfigurations []string `json:"managedConfigurations"`
BashProfile ConfigBashProfile `json:"bashProfile"`
Directories ConfigDirectories `json:"directories"`
Git ConfigGit `json:"git"`
}
type ConfigDirectories struct {
UseDefaultDirectories bool `json:"useDefaultDirectories"`
IncludeXDGDirectories bool `json:"includeXDGDirectories"`
AdditionalDirectories []string `json:"additionalDirectories"`
}
type ConfigGit struct {
GpgSign bool `json:"gpgSign"`
User ConfigGitUser `json:"user"`
}
type ConfigGitUser struct {
Email string `json:"email"`
Name string `json:"name"`
SigningKey string `json:"signingKey"`
}
type ConfigBashProfile struct {
Manage bool `json:"manage"`
Filename string `json:"filename"`
SessionPaths []ConfigBashProfileSessionPath `json:"sessionPaths"`
XdgDirectories map[string]string `json:"xdgDirectories"`
EnvironmentVariables map[string]string `json:"environmentVariables"`
Aliases map[string]string `json:"aliases"`
Commands []ConfigBashProfileCommand `json:"commands"`
}
type ConfigBashProfileSessionPath struct {
Path string `json:"path"`
Description string `json:"description"`
}
type ConfigBashProfileCommand struct {
Command string `json:"command"`
Description string `json:"description"`
}
func NewConfig() (Config, error) {
cfg := defaultConfig()
path, err := configFilePath()
if err != nil {
return Config{}, fmt.Errorf("unable to calculate the config file path: %w", err)
}
file, err := os.Open(path)
if err != nil {
return Config{}, fmt.Errorf("unable to open the file: %w", err)
}
defer file.Close()
if err = json.NewDecoder(file).Decode(&cfg); err != nil {
return Config{}, fmt.Errorf("unable to decode the JSON file: %w", err)
}
return cfg, nil
}
func configFilePath() (string, error) {
hostname, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("unable to get the machine's hostname: %w", err)
}
hostnameParts := strings.SplitN(hostname, "-", 3)
if len(hostnameParts) != 3 {
return "", fmt.Errorf("unexpected hostname format")
}
identifier := hostnameParts[1]
return filepath.Join(configDir, identifier+".json"), nil
}
func defaultConfig() Config {
return Config{
Directories: ConfigDirectories{
UseDefaultDirectories: true,
IncludeXDGDirectories: true,
AdditionalDirectories: []string{},
},
Git: ConfigGit{
GpgSign: false,
User: ConfigGitUser{
Email: "",
Name: "",
SigningKey: "",
},
},
ManagedConfigurations: []string{},
}
}