mod.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package migrate
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "time"
  7. "github.com/zeromicro/go-zero/core/stringx"
  8. "github.com/zeromicro/go-zero/tools/goctl/rpc/execx"
  9. "github.com/zeromicro/go-zero/tools/goctl/util/console"
  10. "github.com/zeromicro/go-zero/tools/goctl/util/ctx"
  11. )
  12. const deprecatedGoZeroMod = "github.com/zeromicro/go-zero"
  13. const goZeroMod = "github.com/zeromicro/go-zero"
  14. var errInvalidGoMod = errors.New("it's only working for go module")
  15. func editMod(version string, verbose bool) error {
  16. wd, err := os.Getwd()
  17. if err != nil {
  18. return err
  19. }
  20. isGoMod, _ := ctx.IsGoMod(wd)
  21. if !isGoMod {
  22. return nil
  23. }
  24. latest, err := getLatest(goZeroMod, verbose)
  25. if err != nil {
  26. return err
  27. }
  28. if !stringx.Contains(latest, version) {
  29. return fmt.Errorf("release version %q is not found", version)
  30. }
  31. mod := fmt.Sprintf("%s@%s", goZeroMod, version)
  32. err = removeRequire(deprecatedGoZeroMod, verbose)
  33. if err != nil {
  34. return err
  35. }
  36. return addRequire(mod, verbose)
  37. }
  38. func addRequire(mod string, verbose bool) error {
  39. if verbose {
  40. console.Info("adding require %s ...", mod)
  41. time.Sleep(200 * time.Millisecond)
  42. }
  43. wd, err := os.Getwd()
  44. if err != nil {
  45. return err
  46. }
  47. isGoMod, _ := ctx.IsGoMod(wd)
  48. if !isGoMod {
  49. return errInvalidGoMod
  50. }
  51. _, err = execx.Run("go mod edit -require "+mod, wd)
  52. return err
  53. }
  54. func removeRequire(mod string, verbose bool) error {
  55. if verbose {
  56. console.Info("remove require %s ...", mod)
  57. time.Sleep(200 * time.Millisecond)
  58. }
  59. wd, err := os.Getwd()
  60. if err != nil {
  61. return err
  62. }
  63. _, err = execx.Run("go mod edit -droprequire "+mod, wd)
  64. return err
  65. }
  66. func tidy(verbose bool) error {
  67. if verbose {
  68. console.Info("go mod tidy ...")
  69. time.Sleep(200 * time.Millisecond)
  70. }
  71. wd, err := os.Getwd()
  72. if err != nil {
  73. return err
  74. }
  75. isGoMod, _ := ctx.IsGoMod(wd)
  76. if !isGoMod {
  77. return nil
  78. }
  79. _, err = execx.Run("go mod tidy", wd)
  80. return err
  81. }