util.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package util
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path"
  8. "strings"
  9. "github.com/tal-tech/go-zero/core/logx"
  10. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  11. "github.com/tal-tech/go-zero/tools/goctl/util"
  12. )
  13. func MaybeCreateFile(dir, subdir, file string) (fp *os.File, created bool, err error) {
  14. logx.Must(util.MkdirIfNotExist(path.Join(dir, subdir)))
  15. fpath := path.Join(dir, subdir, file)
  16. if util.FileExists(fpath) {
  17. fmt.Printf("%s exists, ignored generation\n", fpath)
  18. return nil, false, nil
  19. }
  20. fp, err = util.CreateIfNotExist(fpath)
  21. created = err == nil
  22. return
  23. }
  24. func WrapErr(err error, message string) error {
  25. return errors.New(message + ", " + err.Error())
  26. }
  27. func Copy(src, dst string) (int64, error) {
  28. sourceFileStat, err := os.Stat(src)
  29. if err != nil {
  30. return 0, err
  31. }
  32. if !sourceFileStat.Mode().IsRegular() {
  33. return 0, fmt.Errorf("%s is not a regular file", src)
  34. }
  35. source, err := os.Open(src)
  36. if err != nil {
  37. return 0, err
  38. }
  39. defer source.Close()
  40. destination, err := os.Create(dst)
  41. if err != nil {
  42. return 0, err
  43. }
  44. defer destination.Close()
  45. nBytes, err := io.Copy(destination, source)
  46. return nBytes, err
  47. }
  48. func ComponentName(api *spec.ApiSpec) string {
  49. name := api.Service.Name
  50. if strings.HasSuffix(name, "-api") {
  51. return name[:len(name)-4] + "Components"
  52. }
  53. return name + "Components"
  54. }
  55. func WriteIndent(writer io.Writer, indent int) {
  56. for i := 0; i < indent; i++ {
  57. fmt.Fprint(writer, "\t")
  58. }
  59. }
  60. func RemoveComment(line string) string {
  61. var commentIdx = strings.Index(line, "//")
  62. if commentIdx >= 0 {
  63. return strings.TrimSpace(line[:commentIdx])
  64. }
  65. return strings.TrimSpace(line)
  66. }