package main import ( "fmt" "io" "os" ) func CopyFile(dstName, srcName string) (written int64, err error) { if dstName == srcName { return } src, err := os.Open(srcName) if err != nil { fmt.Println("copy file " + srcName + " error") return } defer src.Close() os.Remove(dstName) dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644) if err != nil { fmt.Println("open file " + dstName + " error") return } defer dst.Close() return io.Copy(dst, src) } func copyDir(srcPath string, destPath string) { os.MkdirAll(destPath, 0777) dir, err := os.ReadDir(srcPath) if err != nil { return } for _, fi := range dir { if fi.IsDir() { // 忽略目录 outPath := destPath + PthSep + fi.Name() copyDir(srcPath+PthSep+fi.Name(), outPath) } else { srcFile := srcPath + PthSep + fi.Name() destFile := destPath + PthSep + fi.Name() CopyFile(destFile, srcFile) } } } func isFileEqual(file1 string, file2 string) bool { // 打开文件 dat1, err1 := os.ReadFile(file1) if err1 != nil { return false } dat2, err2 := os.ReadFile(file2) if err2 != nil { return false } byteData1 := []byte(dat1) dataLen1 := len(byteData1) byteData2 := []byte(dat2) dataLen2 := len(byteData2) if dataLen1 != dataLen2 { return false } //fmt.Println(fmt.Errorf("EncodePicFile %s len = %d", srcFile, dataLen)) for i := 0; i < dataLen1; i++ { if byteData1[i] != byteData2[i] { return false } } return true } func doCompareFolder(srcPath string, destPath string, outputPath string) int { diffCount := 0 dir, err := os.ReadDir(srcPath) if err != nil { return diffCount } for _, fi := range dir { if fi.IsDir() { // 忽略目录 diffCount += doCompareFolder(srcPath+PthSep+fi.Name(), destPath+PthSep+fi.Name(), outputPath+PthSep+fi.Name()) } else { //fmt.Println(dirPth + PthSep + fi.Name()) srcFile := srcPath + PthSep + fi.Name() destFile := destPath + PthSep + fi.Name() outFile := outputPath + PthSep + fi.Name() //func(src, dest, outName, outPath string) { if !isFileEqual(srcFile, destFile) { os.MkdirAll(outputPath, 0777) CopyFile(outFile, srcFile) diffCount++ } //}(srcFile, destFile, outFile, outputPath) } } return diffCount } func isDeltaEmpty(srcPath string) bool { dir, err := os.ReadDir(srcPath) if err != nil { return true } fileCount := 0 for _, fi := range dir { if fi.IsDir() { // 忽略目录 return false } else { fileCount++ } } return fileCount <= 2 } func compareFolder(srcPath string, destPath string, outputPath string) { fmt.Printf("compareFolder %v:%v to %v\n", srcPath, destPath, outputPath) if doCompareFolder(srcPath, destPath, outputPath) <= 2 { // 只有版本文件不一样,删除目录 fmt.Printf("Removing delta folder %v\n", outputPath) os.RemoveAll(outputPath) } }