Skip to content

Commit

Permalink
pkg/homedir: new function SetXdgDirs
Browse files Browse the repository at this point in the history
Signed-off-by: Giuseppe Scrivano <gscrivan@redhat.com>
  • Loading branch information
giuseppe committed Oct 31, 2023
1 parent abd5f97 commit 06acced
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions pkg/homedir/homedir.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ package homedir

import (
"errors"
"fmt"
"os"
"path/filepath"

"github.com/containers/storage/pkg/unshare"
)

// GetDataHome returns XDG_DATA_HOME.
Expand Down Expand Up @@ -35,3 +38,47 @@ func GetCacheHome() (string, error) {
}
return filepath.Join(home, ".cache"), nil
}

// SetXdgDirs ensures the XDG_RUNTIME_DIR, DBUS_SESSION_BUS_ADDRESS and XDG_CONFIG_HOME env
// variables are set when running as rootless.
// containers/image uses XDG_RUNTIME_DIR to locate the auth file, XDG_CONFIG_HOME is
// use for the containers.conf configuration file.
func SetXdgDirs() error {
rootless := unshare.IsRootless()
if !rootless {
return nil
}

// Set up XDG_RUNTIME_DIR
runtimeDir := os.Getenv("XDG_RUNTIME_DIR")

if runtimeDir == "" {
var err error
runtimeDir, err = GetRuntimeDir()
if err != nil {
return err
}
}
if err := os.Setenv("XDG_RUNTIME_DIR", runtimeDir); err != nil {
return fmt.Errorf("cannot set XDG_RUNTIME_DIR: %w", err)
}

if os.Getenv("DBUS_SESSION_BUS_ADDRESS") == "" {
sessionAddr := filepath.Join(runtimeDir, "bus")
if _, err := os.Stat(sessionAddr); err == nil {
os.Setenv("DBUS_SESSION_BUS_ADDRESS", fmt.Sprintf("unix:path=%s", sessionAddr))
}
}

// Set up XDG_CONFIG_HOME
if cfgHomeDir := os.Getenv("XDG_CONFIG_HOME"); cfgHomeDir == "" {
cfgHomeDir, err := GetConfigHome()
if err != nil {
return err
}
if err := os.Setenv("XDG_CONFIG_HOME", cfgHomeDir); err != nil {
return fmt.Errorf("cannot set XDG_CONFIG_HOME: %w", err)
}
}
return nil
}

0 comments on commit 06acced

Please sign in to comment.