1package configdir
2
3import (
4	"os"
5	"path/filepath"
6)
7
8// VERSION is the semantic version number of the configdir library.
9const VERSION = "0.1.0"
10
11func init() {
12	findPaths()
13}
14
15// Refresh will rediscover the config paths, checking current environment
16// variables again.
17//
18// This function is automatically called when the program initializes. If you
19// change the environment variables at run-time, though, you may call the
20// Refresh() function to reevaluate the config paths.
21func Refresh() {
22	findPaths()
23}
24
25// SystemConfig returns the system-wide configuration paths, with optional path
26// components added to the end for vendor/application-specific settings.
27func SystemConfig(folder ...string) []string {
28	if len(folder) == 0 {
29		return systemConfig
30	}
31
32	var paths []string
33	for _, root := range systemConfig {
34		p := append([]string{root}, filepath.Join(folder...))
35		paths = append(paths, filepath.Join(p...))
36	}
37
38	return paths
39}
40
41// LocalConfig returns the local user configuration path, with optional
42// path components added to the end for vendor/application-specific settings.
43func LocalConfig(folder ...string) string {
44	if len(folder) == 0 {
45		return localConfig
46	}
47
48	return filepath.Join(localConfig, filepath.Join(folder...))
49}
50
51// LocalCache returns the local user cache folder, with optional path
52// components added to the end for vendor/application-specific settings.
53func LocalCache(folder ...string) string {
54	if len(folder) == 0 {
55		return localCache
56	}
57
58	return filepath.Join(localCache, filepath.Join(folder...))
59}
60
61// DefaultFileMode controls the default permissions on any paths created by
62// using MakePath.
63var DefaultFileMode = os.FileMode(0755)
64
65// MakePath ensures that the full path you wanted, including vendor or
66// application-specific components, exists. You can give this the output of
67// any of the config path functions (SystemConfig, LocalConfig or LocalCache).
68//
69// In the event that the path function gives multiple answers, e.g. for
70// SystemConfig, MakePath() will only attempt to create the sub-folders on
71// the *first* path found. If this isn't what you want, you may want to just
72// use the os.MkdirAll() functionality directly.
73func MakePath(paths ...string) error {
74	if len(paths) >= 1 {
75		err := os.MkdirAll(paths[0], DefaultFileMode)
76		if err != nil {
77			return err
78		}
79	}
80
81	return nil
82}
83