Repository navigation
Expand file tree
/
Copy pathcheck.go
More file actions
106 lines (91 loc) · 2.42 KB
/
Copy pathcheck.go
File metadata and controls
106 lines (91 loc) · 2.42 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
"github.com/mackerelio/checkers"
"github.com/monitoring-forge/saferio"
)
func (opt *Opt) cmd(file *os.File) error {
cmd := exec.Command(opt.Command, opt.Args...)
var stderr bytes.Buffer
cmd.Stdout = file
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return err
}
err := cmd.Wait()
if err != nil {
return fmt.Errorf("%w - %s", err, stderr.String())
}
return nil
}
func (opt *Opt) check() *checkers.Checker {
hasher := sha256.New()
fmt.Fprintf(hasher, "%s\x00%s\x00%s", opt.Identifier, opt.Command, strings.Join(opt.Args, "\x00"))
curUser, err := user.Current()
if err != nil {
return checkers.Critical(err.Error())
}
prevFileName := fmt.Sprintf("check-diff-%s-%x", curUser.Uid, hasher.Sum(nil))
newFile, err := os.CreateTemp(opt.Workdir, "check-diff-")
if err != nil {
return checkers.Critical(err.Error())
}
defer func() {
_ = newFile.Close()
_ = os.Remove(newFile.Name())
}()
err = opt.cmd(newFile)
if err != nil {
return checkers.Critical(err.Error())
}
err = newFile.Close()
if err != nil {
return checkers.Critical(err.Error())
}
if !saferio.FileExists(opt.Workdir, prevFileName) {
err = os.Rename(newFile.Name(), filepath.Join(opt.Workdir, prevFileName))
if err != nil {
return checkers.Critical(err.Error())
}
if len(opt.Args) > 0 {
return checkers.Ok(fmt.Sprintf("first time execution command: '%s %s'", opt.Command, strings.Join(opt.Args, " ")))
}
return checkers.Ok(fmt.Sprintf("first time execution command: '%s'", opt.Command))
}
textdiff := ""
var errDiff error
if opt.JSON {
textdiff, errDiff = diffJson(filepath.Join(opt.Workdir, prevFileName), newFile.Name(), opt.jq)
if errDiff != nil {
return checkers.Critical(errDiff.Error())
}
} else {
textdiff, errDiff = diff(filepath.Join(opt.Workdir, prevFileName), newFile.Name())
if errDiff != nil {
return checkers.Critical(errDiff.Error())
}
}
err = os.Rename(newFile.Name(), filepath.Join(opt.Workdir, prevFileName))
if err != nil {
return checkers.Critical(err.Error())
}
if textdiff == "" {
msg, err := buildNoDifferenceMsg(filepath.Join(opt.Workdir, prevFileName))
if err != nil {
return checkers.Critical(err.Error())
}
return checkers.Ok(msg)
}
diffMsg := buildDiffMsg(textdiff)
if opt.Warn {
return checkers.Warning(diffMsg)
}
return checkers.Critical(diffMsg)
}