go, 监控git是否更新, 并且自动构建

使用方式 ./command -p [git 目录] -s [每s秒查看一次git版本变化,默认60]

package main

import (
	"bytes"
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"
	"sync"
	"time"
)

var gitVersion = ""
var wg sync.WaitGroup
var path string
var sleepTime int

func ExecCommand(command string, params []string, dir string) string{
	cmd := exec.Command(command, params...)

	if dir != "" {
		cmd.Dir = dir
	}

	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal("error   ", err)
	}

	return out.String()
}

func InitArgs() {
	flag.StringVar(&path, "p", "", "git路径")
	flag.IntVar(&sleepTime, "s", 60, "每多少秒检查一次git version")
	flag.Parse()
}

func dirExists(p string) bool{
	fi, err := os.Stat(p)
	if err != nil {
		return false
	}

	return fi.IsDir()
}

func getVerson(vChan chan <- string){
	for {
		ExecCommand("git", []string{"pull"}, path)
		out := ExecCommand("git", []string{ "log", "-1"}, path)
		lines := strings.Split(out, "\n")
		vChan <- strings.Split(lines[0], " ")[1]
		time.Sleep( time.Second * time.Duration(sleepTime) )
	}

	wg.Done()
}


func do(vChan <- chan string){
	for{
		_v := <- vChan
		if _v != gitVersion {
			fmt.Println("获取到新版本,开始更新...")
			gitVersion = _v

			res2 := ExecCommand("yarn", []string{}, path)
			res3 := ExecCommand("yarn", []string{"build"}, path)
			fmt.Println("已经构建完成:", res2, res3)

			fmt.Println("当前版本为:"+gitVersion)
		}
	}

}

func main() {
	InitArgs()

	if path == "" {
		log.Fatal("路径参数不能为空")
	}

	if !dirExists(path)  {
		log.Fatal("目录不存在:" + path)
	}

	fmt.Println("开始监控目录:",path)

	vChan := make(chan string, 1)

	wg.Add(2)
	go getVerson(vChan)
	go do(vChan)
	wg.Wait()
}
此条目发表在go分类目录,贴了标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

看不清?