github.com/jstaf/onedriver@v0.14.2-0.20240420231225-f07678f9e6ef/cmd/common/config.go (about)

     1  package common
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/imdario/mergo"
     9  	"github.com/jstaf/onedriver/fs/graph"
    10  	"github.com/jstaf/onedriver/ui"
    11  	"github.com/rs/zerolog/log"
    12  	yaml "gopkg.in/yaml.v3"
    13  )
    14  
    15  type Config struct {
    16  	CacheDir         string `yaml:"cacheDir"`
    17  	LogLevel         string `yaml:"log"`
    18  	graph.AuthConfig `yaml:"auth"`
    19  }
    20  
    21  // DefaultConfigPath returns the default config location for onedriver
    22  func DefaultConfigPath() string {
    23  	confDir, err := os.UserConfigDir()
    24  	if err != nil {
    25  		log.Error().Err(err).Msg("Could not determine configuration directory.")
    26  	}
    27  	return filepath.Join(confDir, "onedriver/config.yml")
    28  }
    29  
    30  // LoadConfig is the primary way of loading onedriver's config
    31  func LoadConfig(path string) *Config {
    32  	xdgCacheDir, _ := os.UserCacheDir()
    33  	defaults := Config{
    34  		CacheDir: filepath.Join(xdgCacheDir, "onedriver"),
    35  		LogLevel: "debug",
    36  	}
    37  
    38  	conf, err := ioutil.ReadFile(path)
    39  	if err != nil {
    40  		log.Warn().
    41  			Err(err).
    42  			Str("path", path).
    43  			Msg("Configuration file not found, using defaults.")
    44  		return &defaults
    45  	}
    46  	config := &Config{}
    47  	if err = yaml.Unmarshal(conf, config); err != nil {
    48  		log.Error().
    49  			Err(err).
    50  			Str("path", path).
    51  			Msg("Could not parse configuration file, using defaults.")
    52  	}
    53  	if err = mergo.Merge(config, defaults); err != nil {
    54  		log.Error().
    55  			Err(err).
    56  			Str("path", path).
    57  			Msg("Could not merge configuration file with defaults, using defaults only.")
    58  	}
    59  
    60  	config.CacheDir = ui.UnescapeHome(config.CacheDir)
    61  	return config
    62  }
    63  
    64  // Write config to a file
    65  func (c Config) WriteConfig(path string) error {
    66  	out, err := yaml.Marshal(c)
    67  	if err != nil {
    68  		log.Error().Err(err).Msg("Could not marshal config!")
    69  		return err
    70  	}
    71  	os.MkdirAll(filepath.Dir(path), 0700)
    72  	err = ioutil.WriteFile(path, out, 0600)
    73  	if err != nil {
    74  		log.Error().Err(err).Msg("Could not write config to disk.")
    75  	}
    76  	return err
    77  }