98 lines
2.0 KiB
Go
98 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"git.milar.in/milarin/configfile"
|
|
)
|
|
|
|
type Config struct {
|
|
OutputDir string `json:"output_dir"`
|
|
OutputFile string `json:"output_file"`
|
|
|
|
OS []string `json:"os"`
|
|
Arch []string `json:"arch"`
|
|
|
|
Silent bool `json:"silent"`
|
|
NoCompress bool `json:"no_compress"`
|
|
NumThreads int `json:"num_threads"`
|
|
}
|
|
|
|
func SetFlagIfDefault[T comparable](flag *T, newValue T, defaultValue T) {
|
|
if *flag == defaultValue {
|
|
*flag = newValue
|
|
}
|
|
}
|
|
|
|
func LoadConfig() error {
|
|
configFilePath, err := configfile.Path("json")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
file, err := os.Open(configFilePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
|
|
cfg := &Config{}
|
|
if err := json.NewDecoder(file).Decode(cfg); err != nil {
|
|
if errors.Is(err, io.EOF) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
SetFlagIfDefault(OutputDir, cfg.OutputDir, DefaultOutputDir)
|
|
SetFlagIfDefault(OutputFile, cfg.OutputFile, DefaultOutputFile)
|
|
SetFlagIfDefault(OS, strings.Join(cfg.OS, ","), DefaultOS)
|
|
SetFlagIfDefault(Arch, strings.Join(cfg.Arch, ","), DefaultArch)
|
|
SetFlagIfDefault(Silent, cfg.Silent, DefaultSilent)
|
|
SetFlagIfDefault(NoCompress, cfg.NoCompress, DefaultNoCompress)
|
|
SetFlagIfDefault(NumThreads, cfg.NumThreads, DefaultNumThreads)
|
|
|
|
return nil
|
|
}
|
|
|
|
func SaveConfig() (string, error) {
|
|
configFilePath, err := configfile.Path("json")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
if err := os.MkdirAll(filepath.Dir(configFilePath), 0744); err != nil {
|
|
return configFilePath, err
|
|
}
|
|
|
|
file, err := os.Create(configFilePath)
|
|
if err != nil {
|
|
return configFilePath, err
|
|
}
|
|
defer file.Close()
|
|
|
|
enc := json.NewEncoder(file)
|
|
enc.SetIndent("", "\t")
|
|
|
|
cfg := &Config{
|
|
OutputDir: *OutputDir,
|
|
OutputFile: *OutputFile,
|
|
OS: strings.Split(*OS, ","),
|
|
Arch: strings.Split(*Arch, ","),
|
|
Silent: *Silent,
|
|
NoCompress: *NoCompress,
|
|
NumThreads: *NumThreads,
|
|
}
|
|
|
|
if err := enc.Encode(cfg); err != nil {
|
|
return configFilePath, err
|
|
}
|
|
|
|
return configFilePath, nil
|
|
}
|