Created
July 12, 2013 00:44
-
-
Save jvehent/5980525 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Get all the MD5 from a dir | |
jvehent - ulfr - 2013 | |
example: | |
$ go run md5dir.go /home/ulfr/Code/ | |
using path'/home/ulfr/Code/' | |
2204ab698668813742535320d6b11692 /home/ulfr/Code//md5dir.go | |
fbca743b51a503ced1aa29d3933123c7 /home/ulfr/Code//john-1.7.9-jumbo-7.tar.gz | |
*/ | |
package main | |
import( | |
"bufio" | |
"crypto/md5" | |
"flag" | |
"fmt" | |
"io" | |
"os" | |
) | |
var DEBUG bool = false | |
var VERBOSE bool = true | |
func GetFileMD5(fp string) (hexhash string){ | |
if DEBUG { | |
fmt.Printf("GetFileMD5: computing hash for '%s'\n", fp) | |
} | |
h := md5.New() | |
fd, err := os.Open(fp) | |
if err != nil { | |
fmt.Printf("GetFileMD5: can't get MD5 for %s: %s", fp, err) | |
} | |
defer func() { | |
if err := fd.Close(); err != nil { | |
panic(err) | |
} | |
}() | |
reader := bufio.NewReader(fd) | |
buf := make([]byte, 64) | |
for { | |
block, err := reader.Read(buf) | |
if err != nil && err != io.EOF { panic(err) } | |
if block == 0 { break } | |
h.Write(buf[:block]) | |
} | |
hexhash = fmt.Sprintf("%x %s", h.Sum(nil), fp) | |
return | |
} | |
func GetDownThatPath(path string) (error) { | |
var SubDirs []string | |
/* Non-recursive directory walk-through. Read the content of dir stored | |
in 'path', put all sub-directories in the SubDirs slice, and call | |
the inspection function for all files | |
*/ | |
cdir, err := os.Open(path) | |
defer func() { | |
if err := cdir.Close(); err != nil { | |
panic(err) | |
} | |
}() | |
if err != nil { panic(err) } | |
dircontent, err := cdir.Readdir(-1) | |
if err != nil { panic(err) } | |
for _, entry := range dircontent { | |
epath := path + "/" + entry.Name() | |
if entry.IsDir() { | |
SubDirs = append(SubDirs, epath) | |
} | |
if entry.Mode().IsRegular() { | |
fmt.Println(GetFileMD5(epath)) | |
} | |
} | |
for _, dir := range SubDirs { | |
GetDownThatPath(dir) | |
} | |
return nil | |
} | |
func main() { | |
if DEBUG { VERBOSE = true } | |
flag.Parse() | |
for i := 0; flag.Arg(i) != ""; i++ { | |
if VERBOSE { | |
fmt.Printf("using path'%s'\n", flag.Arg(i)) | |
} | |
GetDownThatPath(flag.Arg(i)) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment