update_gopath.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "regexp"
  11. "strings"
  12. "time"
  13. )
  14. func main() {
  15. goPath := strings.TrimSpace(os.Getenv("GOPATH"))
  16. if goPath == "" {
  17. println("GOPATH not set")
  18. return
  19. }
  20. pattern, _ := regexp.Compile("[:|;]")
  21. goPathArr := pattern.Split(goPath, -1)
  22. for _, item := range goPathArr {
  23. srcPath := path.Join(item, "src")
  24. println("Walk in src path", srcPath)
  25. walk(srcPath)
  26. }
  27. }
  28. // 目录遍历
  29. func walk(dir string) {
  30. rd, err := ioutil.ReadDir(dir)
  31. if nil != err {
  32. fmt.Printf("ioutil.ReadDir() in walk() returned %v\n", err)
  33. return
  34. }
  35. for _, f := range rd {
  36. if f == nil {
  37. println("walk() returned nil FileInfo object")
  38. return
  39. }
  40. if f.IsDir() && strings.Index(f.Name(), ".") != 0 { // 非隐藏目录
  41. name := path.Join(dir, f.Name())
  42. if exists(path.Join(name, ".git")) { // 当是git目录时,拉代码更新
  43. println(name)
  44. pull(name)
  45. }
  46. walk(name) // 递归子目录
  47. }
  48. }
  49. }
  50. // 判断文件或目录是否存在
  51. func exists(path string) bool {
  52. _, err := os.Stat(path)
  53. if err != nil {
  54. if os.IsExist(err) {
  55. return true
  56. }
  57. return false
  58. }
  59. return true
  60. }
  61. // 更新库
  62. func pull(name string) {
  63. c := fmt.Sprintf("cd %s && git pull", name)
  64. ctxt, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
  65. defer cancel()
  66. var stdout, stderr bytes.Buffer
  67. cmd := exec.CommandContext(ctxt, "sh", "-c", c)
  68. cmd.Stdout = &stdout
  69. cmd.Stderr = &stderr
  70. err := cmd.Start()
  71. if nil != err {
  72. fmt.Printf("cmd.Start() in pull() returned %v\n", err)
  73. return
  74. }
  75. err = cmd.Wait()
  76. if nil != err {
  77. fmt.Printf("cmd.Wait() in pull() returned %v\n", err)
  78. return
  79. }
  80. fmt.Println(stdout.String(), stderr.String())
  81. }