gen.go 1.3 KB

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