util.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 ClearAndOpenFile(fpath string) (*os.File, error) {
  25. f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_TRUNC, 0600)
  26. if err != nil {
  27. return nil, err
  28. }
  29. _, err = f.WriteString("")
  30. if err != nil {
  31. return nil, err
  32. }
  33. return f, nil
  34. }
  35. func WrapErr(err error, message string) error {
  36. return errors.New(message + ", " + err.Error())
  37. }
  38. func Copy(src, dst string) (int64, error) {
  39. sourceFileStat, err := os.Stat(src)
  40. if err != nil {
  41. return 0, err
  42. }
  43. if !sourceFileStat.Mode().IsRegular() {
  44. return 0, fmt.Errorf("%s is not a regular file", src)
  45. }
  46. source, err := os.Open(src)
  47. if err != nil {
  48. return 0, err
  49. }
  50. defer source.Close()
  51. destination, err := os.Create(dst)
  52. if err != nil {
  53. return 0, err
  54. }
  55. defer destination.Close()
  56. nBytes, err := io.Copy(destination, source)
  57. return nBytes, err
  58. }
  59. func ComponentName(api *spec.ApiSpec) string {
  60. name := api.Service.Name
  61. if strings.HasSuffix(name, "-api") {
  62. return name[:len(name)-4] + "Components"
  63. }
  64. return name + "Components"
  65. }
  66. func WriteIndent(writer io.Writer, indent int) {
  67. for i := 0; i < indent; i++ {
  68. fmt.Fprint(writer, "\t")
  69. }
  70. }
  71. func RemoveComment(line string) string {
  72. var commentIdx = strings.Index(line, "//")
  73. if commentIdx >= 0 {
  74. return strings.TrimSpace(line[:commentIdx])
  75. }
  76. return strings.TrimSpace(line)
  77. }