command/execute.go
2023-04-09 22:56:24 +08:00

86 lines
1.9 KiB
Go

// Package command ...
//
// Description : command ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-05-20 21:48
package command
import (
"errors"
"os"
"os/exec"
"time"
"git.zhangdeman.cn/zhangdeman/command/define"
)
// Execute 执行系统命令
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 21:49 2022/5/20
func Execute(workDir string, command string, param []string) *define.Result {
//执行命令
result := &define.Result{
WorkDir: workDir,
Param: param,
Error: nil,
Output: nil,
StartTime: time.Now().UnixNano(),
FinishTime: 0,
}
defer func() {
result.FinishTime = time.Now().UnixNano()
}()
if len(workDir) == 0 {
// 默认为项目根目录
result.WorkDir, result.Error = os.Getwd()
}
if nil != result.Error {
return result
}
var (
fileInfo os.FileInfo
)
if fileInfo, result.Error = os.Stat(result.WorkDir); nil != result.Error {
if !os.IsExist(result.Error) {
return result
}
// 目录已存在
result.Error = nil
}
if !fileInfo.IsDir() {
result.Error = errors.New(result.WorkDir + " 工作目录不存在")
}
if result.CmdPath, result.Error = Check(command); nil != result.Error {
return result
}
cmdInstance := exec.Command(command, param...)
cmdInstance.Dir = result.WorkDir
result.Output, result.Error = cmdInstance.CombinedOutput()
if len(result.Output) >= 2 {
if string(result.Output[len(result.Output)-1]) == "n" && string(result.Output[len(result.Output)-2]) == "\\" {
result.Output = result.Output[0 : len(result.Output)-2]
}
}
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
}
}