agedit/pkg/env/env.go

89 lines
2.1 KiB
Go
Raw Normal View History

2024-03-11 20:23:36 -04:00
package env
import (
"os"
"regexp"
"runtime"
"strings"
2024-05-29 15:50:03 -04:00
"github.com/adrg/xdg"
2024-03-11 20:23:36 -04:00
)
// GetEditor gets the configured editor by checking environmental
// variables EDITOR and VISUAL
func GetEditor() string {
var editor string
if v, ok := os.LookupEnv("EDITOR"); ok {
editor = v
} else if v, ok := os.LookupEnv("VISUAL"); ok {
editor = v
2024-03-11 20:23:36 -04:00
} /* else {
// TODO: maybe pick something based on the OS
} */
return editor
}
// GetConfigDir gets a config directory based from environmental variables + the app name
//
// On Windows, %APPDATA%\agedit is used
//
// On UNIX-like systems, $XDG_CONFIG_HOME/agedit is tried, if it isn't defined, $HOME/.config/agedit is used
func GetConfigDir(appname string) string {
2024-05-29 15:50:03 -04:00
return make_path(xdg.ConfigHome, appname)
2024-03-11 20:23:36 -04:00
}
// GetConfigDir gets a config directory based from environmental variables + the app name
//
// On Windows, %LOCALAPPDATA%\agedit is used
//
// On UNIX-like systems, $XDG_DATA_HOME/agedit is tried, if it isn't defined, $HOME/.local/share/agedit is used
func GetDataDir(appname string) string {
2024-05-29 15:50:03 -04:00
return make_path(xdg.DataHome, appname)
2024-03-11 20:23:36 -04:00
}
// GetTempDirectory returns the systems temporary directory
//
// returns %TEMP% on Windows, /tmp on UNIX-like systems
func GetTempDirectory() string {
var tmp string
2024-03-11 20:23:36 -04:00
switch runtime.GOOS {
case "windows":
tmp = os.Getenv("TEMP")
case "android":
if t := os.Getenv("TMPDIR"); t != "" {
tmp = t
} else if t = os.Getenv("PREFIX"); t != "" {
tmp = t + "/tmp"
}
2024-03-11 20:23:36 -04:00
default:
fallthrough
case "darwin":
fallthrough
case "linux":
tmp = "/tmp"
2024-03-11 20:23:36 -04:00
}
return tmp
2024-03-11 20:23:36 -04:00
}
func make_path(paths ...string) string {
sep := string(os.PathSeparator)
output := strings.Builder{}
// add / to the start if it's not already there and we're not on Windows
if match, err := regexp.Match("^\\w", []byte(paths[0])); err == nil && match && runtime.GOOS != "windows" {
output.WriteString(sep)
}
for _, path := range paths {
2024-05-07 19:24:08 -04:00
// don't add / to the end if it's there
if strings.HasSuffix(path, sep) {
output.WriteString(path)
} else {
output.WriteString(path + sep)
}
2024-03-11 20:23:36 -04:00
}
return output.String()
}