util.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package util
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path"
  8. "strings"
  9. "zero/tools/goctl/api/spec"
  10. "zero/core/lang"
  11. "zero/tools/goctl/util"
  12. )
  13. func MaybeCreateFile(dir, subdir, file string) (fp *os.File, created bool, err error) {
  14. lang.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. _, err = f.WriteString("")
  27. if err != nil {
  28. return nil, err
  29. }
  30. return f, nil
  31. }
  32. func WrapErr(err error, message string) error {
  33. return errors.New(message + ", " + err.Error())
  34. }
  35. func Copy(src, dst string) (int64, error) {
  36. sourceFileStat, err := os.Stat(src)
  37. if err != nil {
  38. return 0, err
  39. }
  40. if !sourceFileStat.Mode().IsRegular() {
  41. return 0, fmt.Errorf("%s is not a regular file", src)
  42. }
  43. source, err := os.Open(src)
  44. if err != nil {
  45. return 0, err
  46. }
  47. defer source.Close()
  48. destination, err := os.Create(dst)
  49. if err != nil {
  50. return 0, err
  51. }
  52. defer destination.Close()
  53. nBytes, err := io.Copy(destination, source)
  54. return nBytes, err
  55. }
  56. func ComponentName(api *spec.ApiSpec) string {
  57. name := api.Service.Name
  58. if strings.HasSuffix(name, "-api") {
  59. return name[:len(name)-4] + "Components"
  60. }
  61. return name + "Components"
  62. }