package main import ( "fmt" "os" "path/filepath" "regexp" "strings" "time" ccfg "git.wecise.com/wecise/common/matrix/cfg" clog "git.wecise.com/wecise/common/matrix/logger" "git.wecise.com/wecise/util/filewalker" ) var config = ccfg.MConfig() var logger = clog.New() // 同步指定文件夹中的内容 func PrintUsage() { println(`Usage: sync `) } var option = struct { Debug bool }{ Debug: false, } func main() { var frompath string = "" var topath string = "" for _, arg := range os.Args[1:] { if strings.HasPrefix(arg, "-") { switch arg { case "-debug": option.Debug = true } } else if arg != "" { if frompath == "" { frompath = arg } else if topath == "" { topath = arg } } } switch { case frompath != "" && topath != "": fmt.Println("sync from", frompath, "to", topath) // err := filepath.Walk(frompath, func(path string, info fs.FileInfo, err error) error { // fmt.Println(path) // if err != nil { // fmt.Println(err) // } // if info != nil { // fmt.Println(path, info.Size(), info.ModTime()) // } // return nil // }) // if err != nil { // println(err.Error()) // os.Exit(1) // } for { err := sync(frompath, topath) if err != nil { println(err.Error()) os.Exit(1) } time.Sleep(5 * time.Second) } default: PrintUsage() os.Exit(1) } } func sync(frompath, topath string) (err error) { fw, e := filewalker.NewFileWalker([]string{frompath}, `^[^\.].*`) // orderby: dirfirst, filefirst, fullpath if e != nil { return e } count := 0 e = fw.List(func(basedir, fpath string) bool { absbasedir, e := filepath.Abs(basedir) if e != nil { err = e return false } abstopath, e := filepath.Abs(topath) if e != nil { err = e return false } hiddenpath := fmt.Sprintf(`.*\%c\..*`, os.PathSeparator) if regexp.MustCompile(`^[^\.].*`).MatchString(fpath) && !regexp.MustCompile(hiddenpath).MatchString(fpath) { fromfile := filepath.Join(absbasedir, fpath) tofile := filepath.Join(abstopath, fpath) if option.Debug { fmt.Println(time.Now().Format("2006-01-02 15:04:05"), fromfile, " ==> ", tofile) } todir := filepath.Dir(tofile) e = os.MkdirAll(todir, os.ModePerm) if e != nil { err = fmt.Errorf("to dir %v", e) return false } fromfi, e := os.Stat(fromfile) if e != nil { err = fmt.Errorf("from file %v", e) return false } tofi, e := os.Stat(tofile) if e != nil && !os.IsNotExist(e) { err = fmt.Errorf("to file %v", e) return false } if tofi != nil && fromfi.Size() == tofi.Size() && fromfi.ModTime() == tofi.ModTime() { return true } fmt.Println(fromfile, " ==> ", tofile) frombs, e := os.ReadFile(fromfile) if e != nil { err = fmt.Errorf("from file %v", e) return false } e = os.WriteFile(tofile, frombs, os.ModePerm) if e != nil { err = fmt.Errorf("to file %v", e) return false } e = os.Chtimes(tofile, fromfi.ModTime(), fromfi.ModTime()) if e != nil { err = fmt.Errorf("to file %v", e) return false } count++ } return true }) if e != nil { return e } if err != nil { return } if count > 0 || option.Debug { fmt.Println(time.Now().Format("2006-01-02 15:04:05"), count, "files copied") } return }