xref: /aosp_15_r20/external/bazelbuild-rules_go/go/tools/builders/md5sum.go (revision 9bb1b549b6a84214c53be0924760be030e66b93a)
1// Copyright 2017 The Bazel Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// md5sum replicates the equivalent functionality of the unix tool of the same name.
16package main
17
18import (
19	"crypto/md5"
20	"flag"
21	"fmt"
22	"io"
23	"log"
24	"os"
25	"path/filepath"
26)
27
28func md5SumFile(filename string) ([]byte, error) {
29	var result []byte
30	f, err := os.Open(filename)
31	if err != nil {
32		return result, err
33	}
34	defer f.Close()
35	hash := md5.New()
36	if _, err := io.Copy(hash, f); err != nil {
37		return nil, err
38	}
39	return hash.Sum(result), nil
40}
41
42func run(args []string) error {
43	// Prepare our flags
44	flags := flag.NewFlagSet("md5sum", flag.ExitOnError)
45	output := flags.String("output", "", "If set, write the results to this file, instead of stdout.")
46	if err := flags.Parse(args); err != nil {
47		return err
48	}
49	// print the outputs if we need not
50	to := os.Stdout
51	if *output != "" {
52		f, err := os.Create(*output)
53		if err != nil {
54			return err
55		}
56		defer f.Close()
57		to = f
58	}
59	for _, path := range flags.Args() {
60		walkFn := func(path string, info os.FileInfo, err error) error {
61			if err != nil {
62				return err
63			}
64			if info.IsDir() {
65				return nil
66			}
67
68			if b, err := md5SumFile(path); err != nil {
69				return err
70			} else {
71				fmt.Fprintf(to, "%s  %x\n", path, b)
72			}
73			return nil
74		}
75
76		if err := filepath.Walk(path, walkFn); err != nil {
77			return err
78		}
79	}
80	return nil
81}
82
83func main() {
84	log.SetFlags(0)
85	log.SetPrefix("GoMd5sum: ")
86	if err := run(os.Args[1:]); err != nil {
87		log.Fatal(err)
88	}
89}
90