Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get checksum of a directory in golang

Tags:

go

tar

Is there a way to generate a checksum of an entire directory and its contents in golang?

I know how that one can tar the directory and then grab the checksum of that, but I would like to avoid that if possible.

like image 800
loonyuni Avatar asked Dec 07 '25 20:12

loonyuni


1 Answers

Check the Parallel digestion example from the https://blog.golang.org/pipelines, starting from the Digesting a tree section, probably can give you some ideas.

So you can go from:

// MD5All reads all the files in the file tree rooted at root and returns a map
// from file path to the MD5 sum of the file's contents.  If the directory walk
// fails or any read operation fails, MD5All returns an error.
func MD5All(root string) (map[string][md5.Size]byte, error) {
    m := make(map[string][md5.Size]byte)
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if !info.Mode().IsRegular() {
            return nil
        }
        data, err := ioutil.ReadFile(path)
        if err != nil {
            return err
        }
        m[path] = md5.Sum(data)
        return nil
    })
    if err != nil {
        return nil, err
    }
    return m, nil
}

To the parallel version: https://blog.golang.org/pipelines/parallel.go

like image 116
nbari Avatar answered Dec 10 '25 19:12

nbari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!