feedizer/cmd/feedizer/config/files.go

71 lines
1.4 KiB
Go

package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/adrg/xdg"
"gopkg.in/yaml.v3"
)
var ErrUnsupportedFormat = errors.New("unsupported format")
var ErrFileExists = errors.New("file already exists")
func ReadFiles(files []string, out *Config) (usedFiles []string, err error) {
for _, path := range files {
f, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return nil, fmt.Errorf("cannot read config file %s: %w", path, err)
}
ext := filepath.Ext(path)
if len(ext) > 0 {
ext = ext[1:]
}
switch ext {
case "yaml", "yml":
if err = yaml.NewDecoder(f).Decode(out); err != nil {
return nil, fmt.Errorf("cannot parse yaml config file %s: %w", path, err)
}
default:
return nil, fmt.Errorf("cannot read config file %s: %w", path, ErrUnsupportedFormat)
}
usedFiles = append(usedFiles, path)
}
return usedFiles, nil
}
func WriteFile(path string) (string, error) {
if path == "" {
var err error
if path, err = xdg.ConfigFile(filepath.Join(appName, appName+".yaml")); err != nil {
return "", err
}
}
println(path)
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
if err == nil {
return "", ErrFileExists
}
return "", err
}
f, err := os.OpenFile(path, os.O_CREATE, 0o600)
if err != nil {
return "", err
}
if err = yaml.NewEncoder(f).Encode(config); err != nil {
return "", err
}
return path, f.Close()
}