diff --git a/cmd/define.go b/cmd/define.go new file mode 100644 index 0000000..40679f8 --- /dev/null +++ b/cmd/define.go @@ -0,0 +1,42 @@ +// Package cmd... +// +// Description : cmd... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2021-11-12 2:18 下午 +package cmd + +// Config 配置 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2:19 下午 2021/11/12 +type Config struct { + WorkDir string `json:"work_dir"` // 工作目录 + Command string `json:"command"` // 指令 + Script string `json:"script"` // 脚本 + ParameterList []Parameter `json:"parameter_list"` // 参数列表 +} + +// Parameter ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2:21 下午 2021/11/12 +type Parameter struct { + Key string `json:"key"` + Value string `json:"value"` +} + +// Result ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 4:25 下午 2021/11/12 +type Result struct { + WorkDir string `json:"work_dir"` + Err error `json:"err"` + Output []byte `json:"output"` + ExecuteCommand string `json:"execute_command"` +} diff --git a/cmd/execute.go b/cmd/execute.go new file mode 100644 index 0000000..70de0f7 --- /dev/null +++ b/cmd/execute.go @@ -0,0 +1,58 @@ +// Package cmd... +// +// Description : cmd... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2021-11-12 2:21 下午 +package cmd + +import ( + "os/exec" + "strings" + + "git.zhangdeman.cn/zhangdeman/gopkg/util" +) + +// Execute 执行指令 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2:22 下午 2021/11/12 +func Execute(cmdConfig Config) *Result { + if len(cmdConfig.WorkDir) == 0 { + cmdConfig.WorkDir, _ = util.GetProjectPath() + } + paramList := buildCmdParameter(cmdConfig.Script, cmdConfig.ParameterList) + cmdInstance := exec.Command(cmdConfig.Command, paramList...) + // 设置指令的工作目录 + cmdInstance.Dir = cmdConfig.WorkDir + result := &Result{ + Err: nil, + Output: nil, + WorkDir: cmdConfig.WorkDir, + ExecuteCommand: cmdConfig.Command + " " + strings.Join(paramList, " "), + } + result.Output, result.Err = cmdInstance.CombinedOutput() + return result +} + +// buildCmdParameter 构建参数列表 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2:53 下午 2021/11/12 +func buildCmdParameter(script string, parameterList []Parameter) []string { + paramList := make([]string, 0) + if len(script) > 0 { + paramList = append(paramList, script) + } + for _, item := range parameterList { + if len(item.Key) == 0 { + paramList = append(paramList, item.Value) + continue + } + paramList = append(paramList, item.Key+"="+item.Value) + } + return paramList +}