From 609aefd8087cd17cae8dd3423c1d09b1a5c2aeff Mon Sep 17 00:00:00 2001 From: John Hooks Date: Fri, 5 Jul 2019 14:53:33 -0400 Subject: [PATCH] lib: Support for systemd STATE_DIRECTORY or XDG cache dir If running mgmt from a systemd unit, this enables the STATE_DIRECTORY environment variable to be used for creating the cache directory defined by StateDirectory= in the unit file. It also enables the XDG_CACHE_HOME environment variable to be used. If the user isn't root and the environment variable isn't set, it will use the default XDG_CACHE_HOME directory. --- lib/main.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/lib/main.go b/lib/main.go index 29a77777..667ed9f4 100644 --- a/lib/main.go +++ b/lib/main.go @@ -23,6 +23,7 @@ import ( "io/ioutil" "log" "os" + "os/user" "path" "strings" "sync" @@ -214,7 +215,35 @@ func (obj *Main) Run() error { return fmt.Errorf("hostname cannot be empty") } + user, err := user.Current() + if err != nil { + return errwrap.Wrapf(err, "can't get current user") + } + + // Use systemd StateDirectory if set. If not, use XDG_CACHE_DIR unless user + // is root, then use /var/lib/mgmt/. var prefix = fmt.Sprintf("/var/lib/%s/", obj.Program) // default prefix + stateDir := os.Getenv("STATE_DIRECTORY") + // Ensure there is a / at the end of the directory path. + if stateDir != "" && !strings.HasSuffix(stateDir, "/") { + stateDir = stateDir + "/" + } + + xdg := os.Getenv("XDG_CACHE_HOME") + // Ensure there is a / at the end of the directory path. + if xdg != "" && !strings.HasSuffix(xdg, "/") { + xdg = xdg + "/" + } + if xdg == "" && user.HomeDir != "" { + xdg = fmt.Sprintf("%s/.cache/%s/", user.HomeDir, obj.Program) + } + + if stateDir != "" { + prefix = stateDir + } else if user.Uid != "0" { + prefix = xdg + } + if p := obj.Prefix; p != nil { prefix = *p }