aboutsummaryrefslogtreecommitdiff
path: root/go/tools/builders/md5sum.go
blob: 834eb272cf89caf72a3af80e1e71838ca508fff1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// md5sum replicates the equivalent functionality of the unix tool of the same name.
package main

import (
	"crypto/md5"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
)

func md5SumFile(filename string) ([]byte, error) {
	var result []byte
	f, err := os.Open(filename)
	if err != nil {
		return result, err
	}
	defer f.Close()
	hash := md5.New()
	if _, err := io.Copy(hash, f); err != nil {
		return nil, err
	}
	return hash.Sum(result), nil
}

func run(args []string) error {
	// Prepare our flags
	flags := flag.NewFlagSet("md5sum", flag.ExitOnError)
	output := flags.String("output", "", "If set, write the results to this file, instead of stdout.")
	if err := flags.Parse(args); err != nil {
		return err
	}
	// print the outputs if we need not
	to := os.Stdout
	if *output != "" {
		f, err := os.Create(*output)
		if err != nil {
			return err
		}
		defer f.Close()
		to = f
	}
	for _, path := range flags.Args() {
		walkFn := func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if info.IsDir() {
				return nil
			}

			if b, err := md5SumFile(path); err != nil {
				return err
			} else {
				fmt.Fprintf(to, "%s  %x\n", path, b)
			}
			return nil
		}

		if err := filepath.Walk(path, walkFn); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	log.SetFlags(0)
	log.SetPrefix("GoMd5sum: ")
	if err := run(os.Args[1:]); err != nil {
		log.Fatal(err)
	}
}