-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
82 lines (77 loc) · 1.97 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
func (c BackupsConfig) PrepareBackupsDir(filename string, startTime time.Time) (string, error) {
backupsPath := ""
ts := startTime.Format("2006-01-02T15-04-05")
absFilePath, err := filepath.Abs(filename)
if err != nil {
return "", err
}
var parentMode os.FileMode
if c.BackupsLocation == BackupsLocSubDir {
backupsPath = filepath.Join(
filepath.Dir(absFilePath),
fmt.Sprintf("%s_%s", c.BackupsFolder, ts),
)
stat, err := os.Stat(filepath.Dir(absFilePath))
if err != nil {
return "", err
}
parentMode = stat.Mode() & os.ModePerm
} else if c.BackupsLocation == BackupsLocAbsPath {
backupsPath = filepath.Join(
c.BackupsFolder,
fmt.Sprintf("%s %s", ts, filepath.Base(filepath.Dir(absFilePath))),
)
stat, err := os.Stat(c.BackupsFolder)
if err != nil {
return "", err
}
parentMode = stat.Mode() & os.ModePerm
}
if backupsPath != "" {
err := os.MkdirAll(backupsPath, parentMode)
if err != nil {
return "", fmt.Errorf("failed to create backups directory '%s': %w", backupsPath, err)
}
}
return backupsPath, nil
}
func MustUserHomeDir() string {
retv, err := os.UserHomeDir()
if err != nil {
panic("MustUserHomeDir: " + err.Error())
}
return filepath.Clean(retv)
}
func IsExecAny(mode os.FileMode) bool {
return mode&0111 != 0
}
func RunCmd(bin string, args []string) (string, error) {
cmd := exec.Command(bin, args...)
cmdOut, err := cmd.CombinedOutput()
if err != nil {
var exitError *exec.ExitError
if !errors.As(err, &exitError) {
return "", fmt.Errorf("failed to run %s: %w", filepath.Base(bin), err)
}
}
if cmd.ProcessState == nil {
panic("cmd.ProcessState should not be nil after running")
}
exitCode := cmd.ProcessState.ExitCode()
cmdOutStr := string(cmdOut)
cmdOutStr = strings.TrimSpace(cmdOutStr)
if exitCode != 0 {
return cmdOutStr, fmt.Errorf("%s error: %s", filepath.Base(bin), cmdOutStr)
}
return cmdOutStr, nil
}