gen.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package docgen
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/tal-tech/go-zero/tools/goctl/api/parser"
  9. "github.com/tal-tech/go-zero/tools/goctl/util"
  10. "github.com/urfave/cli"
  11. )
  12. func DocCommand(c *cli.Context) error {
  13. dir := c.String("dir")
  14. if len(dir) == 0 {
  15. return errors.New("missing -dir")
  16. }
  17. outputDir := c.String("o")
  18. if len(outputDir) == 0 {
  19. var err error
  20. outputDir, err = os.Getwd()
  21. if err != nil {
  22. return err
  23. }
  24. }
  25. if !util.FileExists(dir) {
  26. return errors.New(fmt.Sprintf("dir %s not exsit", dir))
  27. }
  28. dir, err := filepath.Abs(dir)
  29. if err != nil {
  30. return err
  31. }
  32. files, err := filePathWalkDir(dir)
  33. if err != nil {
  34. return err
  35. }
  36. for _, path := range files {
  37. api, err := parser.Parse(path)
  38. if err != nil {
  39. return fmt.Errorf("parse file: %s, err: %s", path, err.Error())
  40. }
  41. err = genDoc(api, filepath.Dir(filepath.Join(outputDir, path[len(dir):])),
  42. strings.Replace(path[len(filepath.Dir(path)):], ".api", ".md", 1))
  43. if err != nil {
  44. return err
  45. }
  46. }
  47. return nil
  48. }
  49. func filePathWalkDir(root string) ([]string, error) {
  50. var files []string
  51. err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
  52. if !info.IsDir() && strings.HasSuffix(path, ".api") {
  53. files = append(files, path)
  54. }
  55. return nil
  56. })
  57. return files, err
  58. }