md5r.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. // +build ignore
  16. package main
  17. import (
  18. "crypto/md5"
  19. "flag"
  20. "fmt"
  21. "io"
  22. "os"
  23. "path/filepath"
  24. )
  25. var (
  26. long bool
  27. dirs bool
  28. )
  29. func main() {
  30. flag.BoolVar(&long, "l", false, "Long output")
  31. flag.BoolVar(&dirs, "d", false, "Check dirs")
  32. flag.Parse()
  33. args := flag.Args()
  34. if len(args) == 0 {
  35. args = []string{"."}
  36. }
  37. for _, path := range args {
  38. err := filepath.Walk(path, walker)
  39. if err != nil {
  40. fmt.Fprintln(os.Stderr, err)
  41. os.Exit(1)
  42. }
  43. }
  44. }
  45. func walker(path string, info os.FileInfo, err error) error {
  46. if err != nil {
  47. return err
  48. }
  49. if dirs && info.IsDir() {
  50. fmt.Printf("%s %s 0%03o %d\n", "-", path, info.Mode(), info.ModTime().Unix())
  51. } else if !info.IsDir() {
  52. sum, err := md5file(path)
  53. if err != nil {
  54. return err
  55. }
  56. if long {
  57. fmt.Printf("%s %s 0%03o %d\n", sum, path, info.Mode(), info.ModTime().Unix())
  58. } else {
  59. fmt.Printf("%s %s\n", sum, path)
  60. }
  61. }
  62. return nil
  63. }
  64. func md5file(fname string) (hash string, err error) {
  65. f, err := os.Open(fname)
  66. if err != nil {
  67. return
  68. }
  69. defer f.Close()
  70. h := md5.New()
  71. io.Copy(h, f)
  72. hb := h.Sum(nil)
  73. hash = fmt.Sprintf("%x", hb)
  74. return
  75. }