-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
62 lines (56 loc) · 1.35 KB
/
utils.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
package gounix
import (
"fmt"
"os"
"os/exec"
"strings"
)
// cmdError handle execute error with exit code.
func cmdError(err error) error {
if err == nil {
return nil
} else if exitErr, ok := err.(*exec.ExitError); ok {
return fmt.Errorf("Exit %d, %s", exitErr.ExitCode(), string(exitErr.Stderr))
} else {
return err
}
}
// fileExists check if file exists.
func fileExists(filePath string) (bool, error) {
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
} else {
return true, nil
}
}
// parseCommand extracts the command from a cron expression.
func parseCommand(cronExpr string) (bool, string) {
// Handle predefined constants
aliases := []string{
"@reboot ", "@yearly ", "@annually ",
"@monthly ", "@weekly ", "@daily ",
"@midnight ", "@hourly ",
}
for _, alias := range aliases {
if strings.HasPrefix(cronExpr, alias) {
return true, strings.TrimPrefix(cronExpr, alias)
}
}
// Handle custom cron expressions
parts := strings.Fields(cronExpr)
if len(parts) < 6 {
return false, ""
}
return true, strings.Join(parts[5:], " ")
}
// allCrons get all system cron jobs.
func allCrons() ([]string, error) {
out, err := exec.Command("sudo", "crontab", "-l").Output()
err = cmdError(err)
if err != nil {
return nil, err
}
return strings.Split(string(out), "\n"), nil
}