123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package main
- import (
- "bytes"
- "context"
- "fmt"
- "io/ioutil"
- "os"
- "os/exec"
- "path"
- "regexp"
- "strings"
- "time"
- )
- func main() {
- goPath := strings.TrimSpace(os.Getenv("GOPATH"))
- if goPath == "" {
- println("GOPATH not set")
- return
- }
- pattern, _ := regexp.Compile("[:|;]")
- goPathArr := pattern.Split(goPath, -1)
- for _, item := range goPathArr {
- srcPath := path.Join(item, "src")
- println("Walk in src path", srcPath)
- walk(srcPath)
- }
- }
- // 目录遍历
- func walk(dir string) {
- rd, err := ioutil.ReadDir(dir)
- if nil != err {
- fmt.Printf("ioutil.ReadDir() in walk() returned %v\n", err)
- return
- }
- for _, f := range rd {
- if f == nil {
- println("walk() returned nil FileInfo object")
- return
- }
- if f.IsDir() && strings.Index(f.Name(), ".") != 0 { // 非隐藏目录
- name := path.Join(dir, f.Name())
- if exists(path.Join(name, ".git")) { // 当是git目录时,拉代码更新
- println(name)
- pull(name)
- }
- walk(name) // 递归子目录
- }
- }
- }
- // 判断文件或目录是否存在
- func exists(path string) bool {
- _, err := os.Stat(path)
- if err != nil {
- if os.IsExist(err) {
- return true
- }
- return false
- }
- return true
- }
- // 更新库
- func pull(name string) {
- c := fmt.Sprintf("cd %s && git pull", name)
- ctxt, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
- defer cancel()
- var stdout, stderr bytes.Buffer
- cmd := exec.CommandContext(ctxt, "sh", "-c", c)
- cmd.Stdout = &stdout
- cmd.Stderr = &stderr
- err := cmd.Start()
- if nil != err {
- fmt.Printf("cmd.Start() in pull() returned %v\n", err)
- return
- }
- err = cmd.Wait()
- if nil != err {
- fmt.Printf("cmd.Wait() in pull() returned %v\n", err)
- return
- }
- fmt.Println(stdout.String(), stderr.String())
- }
|