2018-04-02 05:25:32 +02:00
|
|
|
package core
|
|
|
|
|
|
|
|
import (
|
2021-03-01 12:41:35 +01:00
|
|
|
"fmt"
|
2018-04-02 05:25:32 +02:00
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"os/user"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2021-03-01 12:41:35 +01:00
|
|
|
"time"
|
2018-04-02 05:25:32 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
defaultTrimSet = "\r\n\t "
|
|
|
|
)
|
|
|
|
|
2020-07-29 01:17:05 +02:00
|
|
|
// Trim remove trailing spaces from a string.
|
2018-04-02 05:25:32 +02:00
|
|
|
func Trim(s string) string {
|
|
|
|
return strings.Trim(s, defaultTrimSet)
|
|
|
|
}
|
|
|
|
|
2020-07-29 01:17:05 +02:00
|
|
|
// Exec spawns a new process and reurns the output.
|
2018-04-02 05:25:32 +02:00
|
|
|
func Exec(executable string, args []string) (string, error) {
|
|
|
|
path, err := exec.LookPath(executable)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
raw, err := exec.Command(path, args...).CombinedOutput()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2020-07-29 01:17:05 +02:00
|
|
|
return Trim(string(raw)), nil
|
2018-04-02 05:25:32 +02:00
|
|
|
}
|
|
|
|
|
2020-07-29 01:17:05 +02:00
|
|
|
// Exists checks if a path exists.
|
2018-04-02 05:25:32 +02:00
|
|
|
func Exists(path string) bool {
|
|
|
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2020-07-29 01:17:05 +02:00
|
|
|
// ExpandPath replaces '~' shorthand with the user's home directory.
|
2018-04-02 05:25:32 +02:00
|
|
|
func ExpandPath(path string) (string, error) {
|
|
|
|
// Check if path is empty
|
|
|
|
if path != "" {
|
|
|
|
if strings.HasPrefix(path, "~") {
|
|
|
|
usr, err := user.Current()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
// Replace only the first occurrence of ~
|
|
|
|
path = strings.Replace(path, "~", usr.HomeDir, 1)
|
|
|
|
}
|
|
|
|
return filepath.Abs(path)
|
|
|
|
}
|
|
|
|
return "", nil
|
|
|
|
}
|
2021-03-01 12:41:35 +01:00
|
|
|
|
2022-10-01 22:27:07 +02:00
|
|
|
// IsAbsPath verifies if a path is absolute or not
|
|
|
|
func IsAbsPath(path string) bool {
|
|
|
|
return path[0] == 47 // 47 == '/'
|
|
|
|
}
|
|
|
|
|
2021-03-01 12:41:35 +01:00
|
|
|
// GetFileModTime checks if a file has been modified.
|
|
|
|
func GetFileModTime(filepath string) (time.Time, error) {
|
|
|
|
fi, err := os.Stat(filepath)
|
|
|
|
if err != nil || fi.IsDir() {
|
|
|
|
return time.Now(), fmt.Errorf("GetFileModTime() Invalid file")
|
|
|
|
}
|
|
|
|
return fi.ModTime(), nil
|
|
|
|
}
|