util.go 1.9 KB

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