github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/apps/md5/main.go (about) 1 // Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "crypto/md5" 9 "fmt" 10 "io/ioutil" 11 "os" 12 "path/filepath" 13 "sort" 14 ) 15 16 func main() { 17 // Calculate the MD5 sum of all files under the specified directory, 18 // then print the results sorted by path name. 19 m, err := MD5All(os.Args[1]) 20 if err != nil { 21 fmt.Println(err) 22 return 23 } 24 var paths []string 25 for path := range m { 26 paths = append(paths, path) 27 } 28 sort.Strings(paths) 29 for _, path := range paths { 30 fmt.Printf("%x %s\n", m[path], path) 31 } 32 } 33 34 // MD5All reads all the files in the file tree rooted at root and returns a map 35 // from file path to the MD5 sum of the file's contents. If the directory walk 36 // fails or any read operation fails, MD5All returns an error. 37 func MD5All(root string) (map[string][md5.Size]byte, error) { 38 m := make(map[string][md5.Size]byte) 39 err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { 40 if err != nil { 41 return err 42 } 43 if info.IsDir() { 44 return nil 45 } 46 data, err := ioutil.ReadFile(path) 47 if err != nil { 48 return err 49 } 50 m[path] = md5.Sum(data) 51 return nil 52 }) 53 if err != nil { 54 return nil, err 55 } 56 return m, nil 57 }