go-pkg/xdg/xdg.go

84 lines
2.3 KiB
Go
Raw Normal View History

// SPDX-FileCopyrightText: 2023 Jon Lundy <jon@xuu.cc>
// SPDX-License-Identifier: BSD-3-Clause
2023-07-12 12:43:25 -06:00
package xdg
import (
2024-01-22 16:00:58 -07:00
"errors"
2023-07-12 12:43:25 -06:00
"os"
"path/filepath"
"strings"
)
var (
EnvDataHome = setENV("XDG_DATA_HOME", defaultDataHome)
EnvDataDirs = setENV("XDG_DATA_DIRS", defaultDataDirs)
EnvConfigHome = setENV("XDG_CONFIG_HOME", defaultConfigHome)
EnvConfigDirs = setENV("XDG_CONFIG_DIRS", defaultConfigDirs)
EnvCacheHome = setENV("XDG_CACHE_HOME", defaultCacheHome)
EnvStateHome = setENV("XDG_STATE_HOME", defaultStateHome)
EnvRuntime = setENV("XDG_RUNTIME_DIR", defaultRuntime)
EnvDesktopDir = setENV("XDG_DESKTOP_DIR", defaultDesktop)
EnvDownloadDir = setENV("XDG_DOWNLOAD_DIR", defaultDownload)
EnvDocumentsDir = setENV("XDG_DOCUMENTS_DIR", defaultDocuments)
EnvMusicDir = setENV("XDG_MUSIC_DIR", defaultMusic)
EnvPicturesDir = setENV("XDG_PICTURES_DIR", defaultPictures)
EnvVideosDir = setENV("XDG_VIDEOS_DIR", defaultVideos)
EnvTemplatesDir = setENV("XDG_TEMPLATES_DIR", defaultTemplates)
EnvPublicShareDir = setENV("XDG_PUBLICSHARE_DIR", defaultPublic)
EnvApplicationsDir = setENV("XDG_APPLICATIONS_DIR", defaultApplicationDirs)
EnvFontsDir = setENV("XDG_FONTS_DIR", defaultFontDirs)
)
func setENV(name, value string) string {
if _, ok := os.LookupEnv(name); !ok {
os.Setenv(name, value)
}
return literal(name)
}
func Get(base, suffix string) string {
2024-01-22 16:00:58 -07:00
return strings.Join(paths(base, suffix), string(os.PathListSeparator))
}
func paths(base, suffix string) []string {
2023-07-12 12:43:25 -06:00
paths := strings.Split(os.ExpandEnv(base), string(os.PathListSeparator))
for i, path := range paths {
if strings.HasPrefix(path, "~") {
path = strings.Replace(path, "~", getHome(), 1)
}
paths[i] = os.ExpandEnv(filepath.Join(path, suffix))
}
2024-01-22 16:00:58 -07:00
return paths
}
func Find(base, filename string) []string {
var files []string
for _, f := range paths(base, filename) {
if ok, _ := exists(f); !ok {
continue
}
files = append(files, f)
}
return files
2023-07-12 12:43:25 -06:00
}
func getHome() string {
home, err := os.UserHomeDir()
if err != nil {
return "."
}
return home
}
2024-01-22 16:00:58 -07:00
func exists(name string) (bool, error) {
s, err := os.Stat(name)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
if s.IsDir() {
return false, nil
}
return false, err
}