Debian Codegraph @

internal/config/config.go

raw
1 package config
2
3 import (
4 "errors"
5 "os"
6 "path/filepath"
7
8 homedir "github.com/mitchellh/go-homedir"
9 )
10
11 var ConfigDir string
12
13 // InitConfigDir finds the configuration directory for micro according to the XDG spec.
14 // If no directory is found, it creates one.
15 func InitConfigDir(flagConfigDir string) error {
16 var e error
17
18 microHome := os.Getenv("MICRO_CONFIG_HOME")
19 if microHome == "" {
20 // The user has not set $MICRO_CONFIG_HOME so we'll try $XDG_CONFIG_HOME
21 xdgHome := os.Getenv("XDG_CONFIG_HOME")
22 if xdgHome == "" {
23 // The user has not set $XDG_CONFIG_HOME so we should act like it was set to ~/.config
24 home, err := homedir.Dir()
25 if err != nil {
26 return errors.New("Error finding your home directory\nCan't load config files: " + err.Error())
27 }
28 xdgHome = filepath.Join(home, ".config")
29 }
30
31 microHome = filepath.Join(xdgHome, "micro")
32 }
33 ConfigDir = microHome
34
35 if len(flagConfigDir) > 0 {
36 if _, err := os.Stat(flagConfigDir); os.IsNotExist(err) {
37 e = errors.New("Error: " + flagConfigDir + " does not exist. Defaulting to " + ConfigDir + ".")
38 } else {
39 ConfigDir = flagConfigDir
40 return nil
41 }
42 }
43
44 // Create micro config home directory if it does not exist
45 // This creates parent directories and does nothing if it already exists
46 err := os.MkdirAll(ConfigDir, os.ModePerm)
47 if err != nil {
48 return errors.New("Error creating configuration directory: " + err.Error())
49 }
50
51 return e
52 }