Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // +build linux
- package libconf
- import "path/filepath"
- import "os"
- import "bytes"
- func userJoin(rest string) string {
- userp := os.Getenv("HOME")
- return filepath.Join(userp, rest)
- }
- func UserConfigDir() string {
- return userJoin(".config/")
- }
- func UserLocalDir() string {
- return userJoin(".local/share/")
- }
- func UserCacheDir() string {
- return userJoin(".cache/")
- }
- func FromUserDirJoin(rest string) string {
- return userJoin(rest)
- }
- const (
- userConfDirs string = "$HOME/.config/:/etc/xdg/"
- userCacheDirs string = "$HOME/.cache/"
- userDataDirs string = "$HOME/local/share/:/usr/local/share/:/usr/share/"
- )
- func UserConfDirs() string {
- if paths := os.Getenv("XDG_CONFIG_DIRS"); paths != "" {
- return paths
- }
- return os.ExpandEnv(userConfDirs)
- }
- func UserCacheDirs() string {
- if paths := os.Getenv("XDG_CACHE_DIRS"); paths != "" {
- return paths
- }
- return os.ExpandEnv(userCacheDirs)
- }
- func UserDataDirs() string {
- if paths := os.Getenv("XDG_DATA_DIRS"); paths != "" {
- return paths
- }
- return os.ExpandEnv(userDataDirs)
- }
- func isStatOk(path string) bool {
- stat, err := os.Stat(path)
- return stat != nil && err == nil
- }
- func byteSearch(paths string, file string) string {
- buf := bytes.Split([]byte(paths), []byte(":"))
- for _, n := range buf {
- conf := filepath.Join(string(n), file)
- if isStatOk(conf) {
- return conf
- }
- }
- return ""
- }
- func ConfFileSearch(path string) string {
- result := byteSearch(UserConfDirs(), path)
- return result
- }
- func CacheFileSearch(path string) string {
- result := byteSearch(UserCacheDirs(), path)
- return result
- }
- func DataFileSearch(path string) string {
- result := byteSearch(UserDataDirs(), path)
- return result
- }
- const (
- table = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
- )
- func RandomFileName(name string) string {
- keys := []rune(table)
- rand.Shuffle(len(keys), func(i, j int) { keys[i], keys[j] = keys[j], keys[i] })
- var buf string
- var x int
- for _, r := range name {
- if r == 'X' {
- buf += string(keys[x])
- x++
- } else {
- buf += string(r)
- }
- }
- return buf
- }
- func DoesExist(path string) bool {
- return isStatOk(path)
- }
- func OpenFile(path string, opts int, mode os.FileMode) *os.File {
- file, err := os.OpenFile(path, opts, mode)
- if err != nil {
- return nil
- }
- return file
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement