util.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. }