all repos — paprika @ 1082dd587023cb5c21c88497d9a0e3665915bae2

go rewrite of taigabot

config/confpath.go (view raw)

 1package config
 2
 3import (
 4	_ "embed"
 5	"log"
 6	"os"
 7	"path"
 8)
 9
10//go:embed example.yml
11var exampleConfig []byte
12
13func configPaths() []string {
14	var configChoices []string
15	// from most desirable to least desirable config path
16	if xdgConfigHome := os.Getenv("XDG_CONFIG_HOME"); xdgConfigHome != "" {
17		configChoices = append(configChoices, path.Join(xdgConfigHome, "paprika.yml"))
18	}
19	if home := os.Getenv("HOME"); home != "" {
20		configChoices = append(configChoices, path.Join(home, ".config", "paprika.yml"))
21	}
22	systemdConfigDir := os.Getenv("CONFIGURATION_DIRECTORY")
23	if systemdConfigDir != "" {
24		configChoices = append(configChoices, path.Join(systemdConfigDir, "paprika.yml"))
25	} else {
26		configChoices = append(configChoices, path.Join("/etc", "paprika.yml"))
27	}
28	return configChoices
29}
30
31func createConfig(userPath string) {
32	var file *os.File
33	fpath := userPath
34	var err error
35	var errs []error
36
37	if userPath != "" {
38		file, err = os.Create(userPath)
39		if err != nil {
40			log.Fatalf("Error: Failed to create config: %s", err)
41		}
42	} else {
43		configChoices := configPaths()
44		for _, v := range configChoices {
45			file, err = os.Create(v)
46			if err == nil {
47				fpath = v
48				break
49			} else {
50				errs = append(errs, err)
51			}
52		}
53		if file == nil {
54			log.Print("Error: Failed to create config file.")
55			for i := range configChoices {
56				log.Printf("- reason: %s", errs[i])
57			}
58			os.Exit(1)
59		}
60	}
61	defer file.Close()
62
63	if _, err = file.Write(exampleConfig); err != nil {
64		log.Fatalf("Error: Failed to create config: %s", err)
65	} else {
66		log.Printf("- %s", fpath)
67		os.Exit(0)
68	}
69}
70
71func findConfig() *os.File {
72	configChoices := configPaths()
73
74	var errs []error
75	for _, v := range configChoices {
76		file, err := os.Open(v)
77		if err == nil {
78			return file
79		} else {
80			errs = append(errs, err)
81		}
82	}
83
84	log.Print("Error: Could not open any config paths.")
85	for i := range configChoices {
86		log.Printf("- %s", errs[i])
87	}
88	os.Exit(1)
89	return nil
90}