kratos run command support to find the cmd directory from the parent directory (#1146)

* feat(cmd): kratos run command support to find the cmd directory from the parent directory

Co-authored-by: chenzhihui <zhihui_chen@foxmail.com>
pull/1147/head
包子 4 years ago committed by GitHub
parent 70e3692698
commit a2bb5de1bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 57
      cmd/kratos/internal/run/run.go

@ -34,7 +34,7 @@ func Run(cmd *cobra.Command, args []string) {
}
if dir == "" {
// find the directory containing the cmd/*
cmdDir, err := findCMD()
cmdDir, cmdPath, err := findCMD(base)
if err != nil {
fmt.Fprintf(os.Stderr, "\033[31mERROR: %s\033[m\n", err)
return
@ -43,14 +43,14 @@ func Run(cmd *cobra.Command, args []string) {
fmt.Fprintf(os.Stderr, "\033[31mERROR: %s\033[m\n", "The cmd directory cannot be found in the current directory")
return
} else if len(cmdDir) == 1 {
dir = path.Join(base, cmdDir[0])
dir = path.Join(cmdDir, cmdPath[0])
} else {
prompt := &survey.Select{
Message: "Which directory do you want to run?",
Options: cmdDir,
Options: cmdPath,
}
survey.AskOne(prompt, &dir)
dir = path.Join(base, dir)
dir = path.Join(cmdDir, dir)
}
}
fd := exec.Command("go", "run", ".")
@ -64,26 +64,41 @@ func Run(cmd *cobra.Command, args []string) {
return
}
func findCMD() ([]string, error) {
var hasCMDPaths []string
err := filepath.Walk(".", func(walkPath string, info os.FileInfo, err error) error {
// multi level directory is not allowed under the cmd directory, so it is judged that the path ends with cmd.
if strings.HasSuffix(walkPath, "cmd") {
paths, err := ioutil.ReadDir(walkPath)
if err != nil {
return err
}
for _, fileInfo := range paths {
if fileInfo.IsDir() {
hasCMDPaths = append(hasCMDPaths, path.Join(walkPath, fileInfo.Name()))
func findCMD(base string) (string, []string, error) {
next := func(dir string) (string, []string, error) {
var (
cmdDir string
cmdPath []string
)
err := filepath.Walk(dir, func(walkPath string, info os.FileInfo, err error) error {
// multi level directory is not allowed under the cmd directory, so it is judged that the path ends with cmd.
if strings.HasSuffix(walkPath, "cmd") {
paths, err := ioutil.ReadDir(walkPath)
if err != nil {
return err
}
for _, fileInfo := range paths {
if fileInfo.IsDir() {
cmdPath = append(cmdPath, path.Join("cmd", fileInfo.Name()))
}
}
cmdDir, _ = path.Split(walkPath)
return nil
}
return nil
})
return cmdDir, cmdPath, err
}
for i := 0; i < 5; i++ {
base = path.Clean(base)
cmdDir, res, err := next(base)
if err != nil {
return "", nil, err
}
return nil
})
if err != nil {
return []string{}, err
if len(res) > 0 {
return cmdDir, res, nil
}
base, _ = path.Split(base)
}
return hasCMDPaths, err
return "", []string{base}, nil
}

Loading…
Cancel
Save