github.com/oweisse/u-root@v0.0.0-20181109060735-d005ad25fef1/cmds/md5sum/md5sum.go (about)

     1  // Copyright 2018 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"crypto/md5"
     9  	"fmt"
    10  	"io"
    11  	"io/ioutil"
    12  	"log"
    13  	"os"
    14  
    15  	"github.com/spf13/pflag"
    16  )
    17  
    18  func getInput() (input []byte, err error) {
    19  
    20  	return ioutil.ReadAll(os.Stdin)
    21  }
    22  
    23  func helpPrinter() {
    24  
    25  	fmt.Printf("Usage:\nmd5sum <File Name>\n")
    26  	pflag.PrintDefaults()
    27  	os.Exit(0)
    28  }
    29  
    30  func versionPrinter() {
    31  	fmt.Println("md5sum utility, URoot Version.")
    32  	os.Exit(0)
    33  }
    34  
    35  func calculateMd5Sum(fileName string, data []byte) string {
    36  	if len(data) > 0 {
    37  		return fmt.Sprintf("%x", md5.Sum(data))
    38  	}
    39  
    40  	fileDesc, err := os.Open(fileName)
    41  	if err != nil {
    42  		log.Fatal(err)
    43  	}
    44  	defer fileDesc.Close()
    45  
    46  	md5Generator := md5.New()
    47  	if _, err := io.Copy(md5Generator, fileDesc); err != nil {
    48  		log.Fatal(err)
    49  	}
    50  
    51  	md5Sum := fmt.Sprintf("%x", md5Generator.Sum(nil))
    52  	return md5Sum
    53  }
    54  
    55  func main() {
    56  	var (
    57  		help    bool
    58  		version bool
    59  		input   []byte
    60  		err     error
    61  	)
    62  	cliArgs := ""
    63  	pflag.BoolVarP(&help, "help", "h", false, "Show this help and exit")
    64  	pflag.BoolVarP(&version, "version", "v", false, "Print Version")
    65  	pflag.Parse()
    66  
    67  	if help {
    68  		helpPrinter()
    69  	}
    70  
    71  	if version {
    72  		versionPrinter()
    73  	}
    74  
    75  	if len(os.Args) >= 2 {
    76  		cliArgs = os.Args[1]
    77  	}
    78  	if cliArgs == "" {
    79  		input, err = getInput()
    80  		if err != nil {
    81  			fmt.Println("Error getting input.")
    82  			os.Exit(-1)
    83  		}
    84  	}
    85  	fmt.Printf("%s ", calculateMd5Sum(cliArgs, input))
    86  	if cliArgs == "" {
    87  		fmt.Printf(" -\n")
    88  	} else {
    89  		fmt.Printf(" %s\n", cliArgs)
    90  	}
    91  	os.Exit(0)
    92  }