file.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package util
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "go/format"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "text/template"
  12. "time"
  13. "github.com/logrusorgru/aurora"
  14. "github.com/tal-tech/go-zero/core/logx"
  15. )
  16. func CreateIfNotExist(file string) (*os.File, error) {
  17. _, err := os.Stat(file)
  18. if !os.IsNotExist(err) {
  19. return nil, fmt.Errorf("%s already exist", file)
  20. }
  21. return os.Create(file)
  22. }
  23. func RemoveIfExist(filename string) error {
  24. if !FileExists(filename) {
  25. return nil
  26. }
  27. return os.Remove(filename)
  28. }
  29. func RemoveOrQuit(filename string) error {
  30. if !FileExists(filename) {
  31. return nil
  32. }
  33. fmt.Printf("%s exists, overwrite it?\nEnter to overwrite or Ctrl-C to cancel...",
  34. aurora.BgRed(aurora.Bold(filename)))
  35. bufio.NewReader(os.Stdin).ReadBytes('\n')
  36. return os.Remove(filename)
  37. }
  38. func FileExists(file string) bool {
  39. _, err := os.Stat(file)
  40. return err == nil
  41. }
  42. func FileNameWithoutExt(file string) string {
  43. return strings.TrimSuffix(file, filepath.Ext(file))
  44. }
  45. func CreateTemplateAndExecute(filename, text string, arg map[string]interface{}, forceUpdate bool, disableFormatCodeArgs ...bool) error {
  46. if FileExists(filename) && !forceUpdate {
  47. return nil
  48. }
  49. var buffer = new(bytes.Buffer)
  50. templateName := fmt.Sprintf("%d", time.Now().UnixNano())
  51. t, err := template.New(templateName).Parse(text)
  52. if err != nil {
  53. return err
  54. }
  55. err = t.Execute(buffer, arg)
  56. if err != nil {
  57. return err
  58. }
  59. var disableFormatCode bool
  60. for _, f := range disableFormatCodeArgs {
  61. disableFormatCode = f
  62. }
  63. var bts = buffer.Bytes()
  64. s := buffer.String()
  65. logx.Info(s)
  66. if !disableFormatCode {
  67. bts, err = format.Source(buffer.Bytes())
  68. if err != nil {
  69. return err
  70. }
  71. }
  72. return ioutil.WriteFile(filename, bts, os.ModePerm)
  73. }
  74. func FormatCodeAndWrite(filename string, code []byte) error {
  75. if FileExists(filename) {
  76. return nil
  77. }
  78. bts, err := format.Source(code)
  79. if err != nil {
  80. return err
  81. }
  82. return ioutil.WriteFile(filename, bts, os.ModePerm)
  83. }