From d05729399e23f3acd5215786c4b03f3430a52d82 Mon Sep 17 00:00:00 2001 From: Xin Date: Thu, 16 Mar 2023 13:03:05 +0800 Subject: [PATCH] fix: change the working directory of the command (#2560) * fix: change the working directory of the command Refs #2519 * fix: change the working directory by kratos run --work=xxxxx --- cmd/kratos/internal/run/run.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/cmd/kratos/internal/run/run.go b/cmd/kratos/internal/run/run.go index ac229bab2..005c832af 100644 --- a/cmd/kratos/internal/run/run.go +++ b/cmd/kratos/internal/run/run.go @@ -19,6 +19,11 @@ var CmdRun = &cobra.Command{ Long: "Run project. Example: kratos run", Run: Run, } +var targetDir string + +func init() { + CmdRun.Flags().StringVarP(&targetDir, "work", "w", "", "target working directory") +} // Run run project. func Run(cmd *cobra.Command, args []string) { @@ -64,10 +69,11 @@ func Run(cmd *cobra.Command, args []string) { dir = cmdPath[dir] } } - fd := exec.Command("go", append([]string{"run", "."}, programArgs...)...) + fd := exec.Command("go", append([]string{"run", dir}, programArgs...)...) fd.Stdout = os.Stdout fd.Stderr = os.Stderr fd.Dir = dir + changeWorkingDirectory(fd, targetDir) if err := fd.Run(); err != nil { fmt.Fprintf(os.Stderr, "\033[31mERROR: %s\033[m\n", err.Error()) return @@ -131,3 +137,10 @@ func findCMD(base string) (map[string]string, error) { } return map[string]string{"": base}, nil } + +func changeWorkingDirectory(cmd *exec.Cmd, targetDir string) { + targetDir = strings.TrimSpace(targetDir) + if targetDir != "" { + cmd.Dir = targetDir + } +}