Skip to content

Commit c7d2bb5

Browse files
committed
pkg/homedir: new function SetXdgDirs
Signed-off-by: Giuseppe Scrivano <[email protected]>
1 parent e41bafc commit c7d2bb5

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

pkg/homedir/homedir.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package homedir
22

33
import (
44
"errors"
5+
"fmt"
56
"os"
67
"path/filepath"
78
)
@@ -35,3 +36,47 @@ func GetCacheHome() (string, error) {
3536
}
3637
return filepath.Join(home, ".cache"), nil
3738
}
39+
40+
// SetXdgDirs ensures the XDG_RUNTIME_DIR env and XDG_CONFIG_HOME variables are set.
41+
// containers/image uses XDG_RUNTIME_DIR to locate the auth file, XDG_CONFIG_HOME is
42+
// use for the containers.conf configuration file.
43+
func SetXdgDirs(rootless bool, rootlessUID int) error {
44+
if !rootless {
45+
os.Unsetenv("XDG_RUNTIME_DIR")
46+
os.Unsetenv("XDG_CONFIG_HOME")
47+
return nil
48+
}
49+
50+
// Set up XDG_RUNTIME_DIR
51+
runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
52+
53+
if runtimeDir == "" {
54+
var err error
55+
runtimeDir, err = GetRuntimeDirUser(rootless, rootlessUID)
56+
if err != nil {
57+
return err
58+
}
59+
}
60+
if err := os.Setenv("XDG_RUNTIME_DIR", runtimeDir); err != nil {
61+
return fmt.Errorf("cannot set XDG_RUNTIME_DIR: %w", err)
62+
}
63+
64+
if os.Getenv("DBUS_SESSION_BUS_ADDRESS") == "" {
65+
sessionAddr := filepath.Join(runtimeDir, "bus")
66+
if _, err := os.Stat(sessionAddr); err == nil {
67+
os.Setenv("DBUS_SESSION_BUS_ADDRESS", fmt.Sprintf("unix:path=%s", sessionAddr))
68+
}
69+
}
70+
71+
// Set up XDG_CONFIG_HOME
72+
if cfgHomeDir := os.Getenv("XDG_CONFIG_HOME"); cfgHomeDir == "" {
73+
cfgHomeDir, err := GetConfigHome()
74+
if err != nil {
75+
return err
76+
}
77+
if err := os.Setenv("XDG_CONFIG_HOME", cfgHomeDir); err != nil {
78+
return fmt.Errorf("cannot set XDG_CONFIG_HOME: %w", err)
79+
}
80+
}
81+
return nil
82+
}

0 commit comments

Comments
 (0)