首页 > 代码库 > go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变

go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变

package main

import (
	"fmt"
	"time"

	"os/exec"

	"strings"

	"io/ioutil"

	"os"

	"github.com/howeyc/fsnotify"
)

const filePath = "/home/ubuntu/GzhuOJ/public"

var watcher *fsnotify.Watcher

func Print(args ...interface{}) {
	fmt.Println(time.Now(), args)
}
func isDir(path string) bool {
	fileInfo, err := os.Stat(path)
	if err != nil {
		Print("error:", err.Error())
		return false
	}
	return fileInfo.IsDir()
}
func watchPath(filePath string) {
	Print("watchPath:", filePath)
	err := watcher.Watch(filePath)
	if err != nil {
		Print(err.Error())
		return
	}
}
func broweDir(path string) {
	Print("broweDir:", path)
	dir, err := os.Open(path)
	if err != nil {
		Print("error:", err.Error())
		return
	}
	defer dir.Close()
	names, err := dir.Readdirnames(-1)
	if err != nil {
		Print("error:", err.Error())
		return
	}
	for _, name := range names {
		dirPath := path + "/" + name
		if !isDir(dirPath) {
			continue
		}
		watchPath(dirPath)
		broweDir(dirPath)
	}
}

func main() {
	var err error
	watcher, err = fsnotify.NewWatcher()
	if err != nil {
		panic(err)
	}
	defer watcher.Close()
	broweDir(filePath)
	watchPath(filePath)
	dealWatch()
}
func dealWatch() {
	for {
		select {
		case event := <-watcher.Event:
			Print("event: ", event)
			if !event.IsModify() && !event.IsCreate() {
				break
			}
			cmd := exec.Command("scp", "-r", "-P 23456", filePath+strings.TrimPrefix(event.Name, filePath), "root@emb.mobi:/home/public")
			Print("cmd:", cmd.Args)
			stderr, err := cmd.StderrPipe()
			if err != nil {
				Print(err.Error())
				break
			}
			stdout, err := cmd.StdoutPipe()
			if err != nil {
				Print(err.Error())
				break
			}
			if err = cmd.Start(); err != nil {
				Print(err.Error())
				break
			}
			errBytes, err := ioutil.ReadAll(stderr)
			if err != nil {
				Print(err.Error())
				break
			}
			outBytes, err := ioutil.ReadAll(stdout)
			if err != nil {
				Print(err.Error())
				break
			}
			if len(errBytes) != 0 {
				Print("errors:", string(errBytes))
			}
			if len(outBytes) != 0 {
				Print("output:", string(outBytes))
			}
		case err := <-watcher.Error:
			Print("error: ", err.Error())
		}
	}
}

  

要注意的是一个fsnotify.Watcher能watch多个文件和文件夹

go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变