2022-05-21 11:35:01 +08:00
|
|
|
// Package command ...
|
2022-05-20 22:23:40 +08:00
|
|
|
//
|
|
|
|
// Description : command ...
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 2022-05-20 21:48
|
|
|
|
package command
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2022-05-21 17:54:53 +08:00
|
|
|
"os"
|
2022-05-20 22:23:40 +08:00
|
|
|
"os/exec"
|
|
|
|
"time"
|
2022-05-21 11:35:01 +08:00
|
|
|
|
|
|
|
"git.zhangdeman.cn/zhangdeman/command/define"
|
2022-05-20 22:23:40 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Execute 执行系统命令
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 21:49 2022/5/20
|
|
|
|
func Execute(workDir string, command string, param []string) define.Result {
|
2022-05-21 19:06:06 +08:00
|
|
|
|
2022-05-20 22:23:40 +08:00
|
|
|
//执行命令
|
|
|
|
result := define.Result{
|
2022-05-20 22:31:29 +08:00
|
|
|
WorkDir: workDir,
|
2022-05-21 11:35:01 +08:00
|
|
|
Error: nil,
|
2022-05-20 22:23:40 +08:00
|
|
|
Output: nil,
|
|
|
|
StartTime: time.Now().UnixNano(),
|
|
|
|
FinishTime: 0,
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
result.FinishTime = time.Now().UnixNano()
|
|
|
|
}()
|
2022-05-21 19:06:06 +08:00
|
|
|
if len(workDir) == 0 {
|
|
|
|
// 默认为项目根目录
|
|
|
|
result.WorkDir, result.Error = os.Getwd()
|
|
|
|
}
|
|
|
|
if nil != result.Error {
|
|
|
|
return result
|
|
|
|
}
|
2022-05-21 17:54:53 +08:00
|
|
|
var (
|
|
|
|
fileInfo os.FileInfo
|
|
|
|
)
|
2022-05-21 19:40:33 +08:00
|
|
|
if fileInfo, result.Error = os.Stat(result.WorkDir); nil != result.Error {
|
2022-05-21 17:54:53 +08:00
|
|
|
if !os.IsExist(result.Error) {
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
// 目录已存在
|
|
|
|
result.Error = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if !fileInfo.IsDir() {
|
2022-05-21 19:40:33 +08:00
|
|
|
result.Error = errors.New(result.WorkDir + " 工作目录不存在")
|
2022-05-21 17:54:53 +08:00
|
|
|
}
|
|
|
|
|
2022-05-21 11:35:01 +08:00
|
|
|
if result.CmdPath, result.Error = Check(command); nil != result.Error {
|
2022-05-20 22:31:29 +08:00
|
|
|
return result
|
|
|
|
}
|
2022-05-20 22:23:40 +08:00
|
|
|
cmdInstance := exec.Command(command, param...)
|
2022-05-21 19:40:33 +08:00
|
|
|
cmdInstance.Dir = result.WorkDir
|
2022-05-21 11:35:01 +08:00
|
|
|
result.Output, result.Error = cmdInstance.CombinedOutput()
|
2022-05-20 22:23:40 +08:00
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check 检测命令
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 21:57 2022/5/20
|
|
|
|
func Check(command string) (string, error) {
|
|
|
|
if path, err := exec.LookPath(command); err != nil {
|
|
|
|
return "", errors.New(command + " 命令不存在 : " + err.Error())
|
|
|
|
} else {
|
|
|
|
return path, nil
|
|
|
|
}
|
|
|
|
}
|