Skip to content

Instantly share code, notes, and snippets.

@kedare
Last active May 8, 2016 18:28
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 kedare/22eca7b28c239d471f9c1afbe5c396af to your computer and use it in GitHub Desktop.
Save kedare/22eca7b28c239d471f9c1afbe5c396af to your computer and use it in GitHub Desktop.
package main
import (
"crypto/sha256"
"encoding/hex"
"io/ioutil"
"os"
"sync"
"github.com/fatih/color"
)
var wg sync.WaitGroup
// HashResult represents the result of a single file checksum
type HashResult struct {
Result string
Error error
}
// PrintFileHash get the checksum of the fileName file
// and show it's result or the related error
func PrintFileHash(fileName string, c chan HashResult) HashResult {
defer wg.Done()
green := color.New(color.FgGreen)
red := color.New(color.FgRed)
hasher := sha256.New()
fileContent, err := ioutil.ReadFile(fileName)
result := HashResult{}
if err != nil {
result = HashResult{Result: "", Error: err}
c <- result
} else {
hasher.Write(fileContent)
result = HashResult{Result: hex.EncodeToString(hasher.Sum(nil)), Error: nil}
}
if result.Error != nil {
red.Println("KO > " + fileName + " - " + result.Error.Error())
} else {
green.Println("OK > " + fileName + " - " + result.Result)
}
c <- result
return result
}
// HashAll analyze a directory and start a checksum of all the files resursively (if resursive is true)
// When the basePath is a file, only the file hash is computed
func HashAll(basePath string, recursive bool) {
basePathInfo, _ := os.Stat(basePath)
if basePathInfo.IsDir() {
files, _ := ioutil.ReadDir(basePath)
for _, file := range files {
fullPath := basePath + "/" + file.Name()
if !file.IsDir() && recursive {
c := make(chan HashResult, 1)
wg.Add(1)
go PrintFileHash(fullPath, c)
} else {
HashAll(fullPath, false)
}
}
} else {
c := make(chan HashResult, 1)
wg.Add(1)
go PrintFileHash(basePath, c)
}
}
func main() {
HashAll(os.Args[1], true)
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment