-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
72 lines (59 loc) · 1.24 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
63
64
65
66
67
68
69
70
71
72
/*
@Time : 2024/8/4 下午4:35
@Author : ljn
@File : utils
@Software: GoLand
*/
package main
import (
"fmt"
"github.com/spf13/cobra"
"io"
"os"
"os/exec"
)
// MustCheck panics when the error is not nil
func MustCheck(err error) {
if err != nil {
panic(err)
}
}
// CloseFile attempts to close the passed file
// or panics with the actual er ror
func CloseFile(f *os.File) {
err := f.Close()
MustCheck(err)
}
// WriteToFile creates a file and writes content to it
func WriteToFile(filename, content string) {
f, err := os.Create(filename)
MustCheck(err)
defer CloseFile(f)
_, err = f.WriteString(content)
MustCheck(err)
}
func ExecuteCommand(name string, subname string, args ...string) error {
args = append([]string{subname}, args...)
cmd := exec.Command(name, args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
if err := cmd.Wait(); err != nil {
return err
}
return nil
}
func Error(cmd *cobra.Command, args []string, err error) {
fmt.Fprintf(os.Stderr, "execute %s args:%v error:%v\n", cmd.Name(), args, err)
os.Exit(1)
}