github.com/samcsf/daily-go@v0.0.0-20190829154117-7da5420f3392/pkg/prune/prune.go (about) 1 /* 2 受TJ大神node-prune启发写个简单的go-prune,清除vendor中不必要的文件 3 */ 4 package prune 5 6 import ( 7 "io/ioutil" 8 "log" 9 "os" 10 "path" 11 "regexp" 12 ) 13 14 var PruneList = []string{ 15 `^\..*`, 16 `.*\.md`, 17 `.*\.markdown`, 18 `makefile`, 19 `dockerfile`, 20 `AUTHORS`, 21 `LICENSE`, 22 `CONTRIBUTORS`, 23 `PATENTS`, 24 } 25 26 var totalCleanSize int64 27 var totalCleanCount int 28 29 func chkErr(err error) { 30 if err != nil { 31 log.Fatal(err) 32 panic(err) 33 } 34 } 35 36 func Prune(root string) { 37 // find root/vendor folder 38 target := path.Join(root, "vendor") 39 // walk throught the folder 40 // regexp test and remove 41 walk(target, handle) 42 log.Println("Total", totalCleanCount, "files cleaned") 43 log.Println("Saved", totalCleanSize, "bytes") 44 } 45 46 func handle(baseDir string, info os.FileInfo) { 47 fullPath := path.Join(baseDir, info.Name()) 48 // log.Println(fullPath, info.Size(), "bytes") 49 for _, pattern := range PruneList { 50 isMatch, err := regexp.MatchString("(?i)"+pattern, info.Name()) 51 chkErr(err) 52 if isMatch { 53 log.Println("X", fullPath) 54 err = os.Remove(fullPath) 55 chkErr(err) 56 totalCleanCount++ 57 totalCleanSize += info.Size() 58 break 59 } 60 } 61 } 62 63 func walk(filePath string, fn func(string, os.FileInfo)) { 64 log.Println("Start to scan from ", filePath) 65 files, err := ioutil.ReadDir(filePath) 66 chkErr(err) 67 for _, file := range files { 68 fullPath := path.Join(filePath, file.Name()) 69 if file.IsDir() { 70 walk(fullPath, fn) 71 } else { 72 fn(filePath, file) 73 } 74 } 75 }