PackageManager just because
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

128 lines
2.0 KiB

  1. package Filesystem
  2. import (
  3. "PackageManager/Client/Database"
  4. "crypto/md5"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. )
  11. func HashFile(path string) (string, error) {
  12. var (
  13. Md5Hash string
  14. hashBytes [16]byte
  15. file *os.File
  16. e error
  17. )
  18. file, e = os.Open(path)
  19. if e != nil {
  20. panic(e)
  21. }
  22. defer file.Close()
  23. body, e := ioutil.ReadAll(file)
  24. if e != nil {
  25. panic(e)
  26. }
  27. //Get the 16 bytes hash
  28. hashBytes = md5.Sum(body)
  29. //Convert the bytes to a string
  30. Md5Hash = fmt.Sprintf("%x", hashBytes)
  31. return Md5Hash, nil
  32. }
  33. func UpdateFilesystemHash() error {
  34. var (
  35. fileHash string
  36. rows []Database.FilesystemHashRow
  37. e error
  38. )
  39. e = filepath.Walk(".", func(path string, info os.FileInfo, e error) error {
  40. if e != nil {
  41. return e
  42. }
  43. // Ignore hidden files
  44. if strings.HasPrefix(info.Name(), ".") || strings.HasPrefix(path, ".") {
  45. return nil
  46. }
  47. // Ignore directories
  48. if info.IsDir() {
  49. return nil
  50. }
  51. fileHash, e = HashFile(path)
  52. if e != nil {
  53. return e
  54. }
  55. rows = append(rows, Database.FilesystemHashRow{
  56. Path: path,
  57. Hash: fileHash,
  58. UpdatedAt: info.ModTime(),
  59. })
  60. // TODO: If len(rows) > x, update the db and clear out rows, and continue
  61. return nil
  62. })
  63. if e != nil {
  64. panic(e)
  65. }
  66. return Database.FindOrCreateFileHash(rows)
  67. }
  68. func GetFilesystemDiff() error {
  69. var (
  70. fileHash string
  71. hashes []string = []string{}
  72. e error
  73. )
  74. e = filepath.Walk(".", func(path string, info os.FileInfo, e error) error {
  75. if e != nil {
  76. return e
  77. }
  78. // Ignore hidden files
  79. if strings.HasPrefix(info.Name(), ".") || strings.HasPrefix(path, ".") {
  80. return nil
  81. }
  82. // Ignore directories
  83. if info.IsDir() {
  84. return nil
  85. }
  86. fileHash, e = HashFile(path)
  87. if e != nil {
  88. return e
  89. }
  90. hashes = append(hashes, fileHash)
  91. // TODO: If len(rows) > x, update the db and clear out rows, and continue
  92. return nil
  93. })
  94. dirty, e := Database.FindModifiedFiles(hashes)
  95. fmt.Println(dirty)
  96. return e
  97. }