2022-07-02 22:55:10 +08:00
|
|
|
package constant
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2022-10-25 12:55:00 +08:00
|
|
|
"strings"
|
2022-07-02 22:55:10 +08:00
|
|
|
|
|
|
|
"github.com/sagernet/sing/common/rw"
|
|
|
|
)
|
|
|
|
|
|
|
|
const dirName = "sing-box"
|
|
|
|
|
2022-10-25 12:55:00 +08:00
|
|
|
var (
|
|
|
|
basePath string
|
2023-04-09 12:39:26 +08:00
|
|
|
tempPath string
|
2022-10-25 12:55:00 +08:00
|
|
|
resourcePaths []string
|
|
|
|
)
|
|
|
|
|
|
|
|
func BasePath(name string) string {
|
|
|
|
if basePath == "" || strings.HasPrefix(name, "/") {
|
|
|
|
return name
|
|
|
|
}
|
|
|
|
return filepath.Join(basePath, name)
|
|
|
|
}
|
|
|
|
|
2023-04-09 12:39:26 +08:00
|
|
|
func CreateTemp(pattern string) (*os.File, error) {
|
|
|
|
if tempPath == "" {
|
|
|
|
tempPath = os.TempDir()
|
|
|
|
}
|
|
|
|
return os.CreateTemp(tempPath, pattern)
|
|
|
|
}
|
|
|
|
|
2022-10-25 12:55:00 +08:00
|
|
|
func SetBasePath(path string) {
|
|
|
|
basePath = path
|
|
|
|
}
|
2022-07-02 22:55:10 +08:00
|
|
|
|
2023-04-09 12:39:26 +08:00
|
|
|
func SetTempPath(path string) {
|
|
|
|
tempPath = path
|
|
|
|
}
|
|
|
|
|
2022-07-06 14:44:51 +08:00
|
|
|
func FindPath(name string) (string, bool) {
|
2022-07-02 22:55:10 +08:00
|
|
|
name = os.ExpandEnv(name)
|
|
|
|
if rw.FileExists(name) {
|
|
|
|
return name, true
|
|
|
|
}
|
|
|
|
for _, dir := range resourcePaths {
|
|
|
|
if path := filepath.Join(dir, dirName, name); rw.FileExists(path) {
|
|
|
|
return path, true
|
|
|
|
}
|
2022-07-14 20:30:57 +08:00
|
|
|
if path := filepath.Join(dir, name); rw.FileExists(path) {
|
|
|
|
return path, true
|
|
|
|
}
|
2022-07-02 22:55:10 +08:00
|
|
|
}
|
|
|
|
return name, false
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
resourcePaths = append(resourcePaths, ".")
|
2022-07-14 20:30:57 +08:00
|
|
|
if home := os.Getenv("HOME"); home != "" {
|
|
|
|
resourcePaths = append(resourcePaths, home)
|
|
|
|
}
|
2022-07-02 22:55:10 +08:00
|
|
|
if userConfigDir, err := os.UserConfigDir(); err == nil {
|
|
|
|
resourcePaths = append(resourcePaths, userConfigDir)
|
|
|
|
}
|
|
|
|
if userCacheDir, err := os.UserCacheDir(); err == nil {
|
|
|
|
resourcePaths = append(resourcePaths, userCacheDir)
|
|
|
|
}
|
|
|
|
}
|