Skip to content

Instantly share code, notes, and snippets.

@Miguel-Dorta
Last active May 21, 2019 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Miguel-Dorta/6555eecf54a13ce87c9f1b345070a679 to your computer and use it in GitHub Desktop.
Save Miguel-Dorta/6555eecf54a13ce87c9f1b345070a679 to your computer and use it in GitHub Desktop.
Get the MD5 hash of a directory's content (recursively)
// MIT License <https://opensource.org/licenses/MIT> - Copyright (c) 2019 Miguel Dorta
package main
import (
"crypto/md5"
"fmt"
"io"
"os"
"path/filepath"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: %s <path>\n", os.Args[0])
os.Exit(1)
}
listDirRecursive(os.Args[1])
}
func listDir(path string) ([]os.FileInfo, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return f.Readdir(-1)
}
func listDirRecursive(path string) {
list, err := listDir(path)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading %s: %s\n", path, err.Error())
return
}
for _, element := range list {
eMode := element.Mode()
ePath := filepath.Join(path, element.Name())
if eMode.IsDir() {
listDirRecursive(ePath)
} else if eMode.IsRegular() {
h, err := hashFile(ePath)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading %s: %s\n", ePath, err.Error())
continue
}
fmt.Printf("%x %s\n", h, ePath)
} else {
fmt.Fprintf(os.Stderr, "error reading %s: type not supported\n", ePath)
continue
}
}
}
func hashFile(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
return nil, err
}
return h.Sum(nil), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment