GoHash.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package main
  2. import (
  3. "bufio"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "os"
  12. "path/filepath"
  13. "runtime"
  14. "sync"
  15. "time"
  16. "code.cloudfoundry.org/bytefmt"
  17. flag "github.com/spf13/pflag"
  18. )
  19. // Fdhashes struct for holding all informations about one folder.
  20. type Fdhashes struct {
  21. Path string
  22. Hashes map[string]string
  23. Times map[string]time.Time
  24. Dirty bool
  25. }
  26. var hashes map[string]Fdhashes
  27. var mu sync.RWMutex
  28. var driveLetter string
  29. var rewrite bool
  30. var prune bool
  31. var cleanup bool
  32. var report string
  33. func init() {
  34. flag.BoolVarP(&rewrite, "rewrite", "r", false, "rewrite all fhhashes files.")
  35. flag.StringVarP(&report, "equals", "e", "", "compare all file hashes and writing a equlatity report.")
  36. flag.BoolVarP(&prune, "prune", "p", false, "checking all fhhashes files.")
  37. flag.BoolVarP(&cleanup, "clean", "c", false, "cleanup files.")
  38. }
  39. func main() {
  40. log.Println("starting GoHash")
  41. hashes = make(map[string]Fdhashes)
  42. flag.Parse()
  43. myFile := flag.Arg(0)
  44. file, err := os.Stat(myFile)
  45. if os.IsNotExist(err) {
  46. log.Fatalln("File does not exists:", myFile)
  47. }
  48. if file.IsDir() {
  49. log.Println("start with folder:", myFile)
  50. driveLetter = ""
  51. if runtime.GOOS == "windows" {
  52. driveLetter = filepath.VolumeName(myFile) + "/"
  53. }
  54. if report != "" {
  55. compareFolder(myFile)
  56. } else {
  57. processFolder(myFile)
  58. saveAllHashFiles()
  59. }
  60. } else {
  61. log.Printf("file %s has hash %s\n", myFile, getSha256Hash(myFile))
  62. }
  63. log.Println("done")
  64. }
  65. func getSha256Hash(fileStr string) string {
  66. f, err := os.Open(fileStr)
  67. if err != nil {
  68. log.Fatal(err)
  69. }
  70. defer f.Close()
  71. h := sha256.New()
  72. if _, err := io.Copy(h, f); err != nil {
  73. log.Fatal(err)
  74. }
  75. return hex.EncodeToString(h.Sum(nil))
  76. }
  77. var lock1 = sync.RWMutex{}
  78. var lock2 = sync.RWMutex{}
  79. func outputHash(fileStr string) {
  80. var hashFile Fdhashes
  81. doHash := true
  82. dir, fileName := filepath.Split(fileStr)
  83. if fileName == ".fdhashes3" {
  84. return
  85. }
  86. // checking if hash is present
  87. mu.Lock()
  88. hashFile, ok := hashes[dir]
  89. if !ok {
  90. _, err := os.Stat(dir + ".fdhashes3")
  91. if os.IsNotExist(err) {
  92. hashFile = Fdhashes{Path: dir, Hashes: make(map[string]string), Times: make(map[string]time.Time), Dirty: true}
  93. } else {
  94. hashFile = loadHashfile(dir + ".fdhashes3")
  95. }
  96. hashes[dir] = hashFile
  97. }
  98. lock1.RLock()
  99. _, ok = hashFile.Hashes[fileName]
  100. lock1.RUnlock()
  101. mu.Unlock()
  102. doHash = !ok
  103. // checking if dattime is identically
  104. file, _ := os.Stat(fileStr)
  105. time := file.ModTime()
  106. lock2.RLock()
  107. savedTime, ok := hashFile.Times[fileName]
  108. lock2.RUnlock()
  109. if !time.Equal(savedTime) || !ok {
  110. doHash = true
  111. }
  112. if doHash {
  113. log.Printf("starting %s\n", fileStr)
  114. hash := getSha256Hash(fileStr)
  115. log.Printf("ready %s\n", fileStr)
  116. mu.Lock()
  117. lock1.Lock()
  118. hashFile.Hashes[fileName] = hash
  119. lock1.Unlock()
  120. lock2.Lock()
  121. hashFile.Times[fileName] = time
  122. lock2.Unlock()
  123. dirtyHashfile(&hashFile)
  124. hashes[dir] = hashFile
  125. mu.Unlock()
  126. log.Printf("file \"%s\" has hash \"%s\"\n", fileStr, hash)
  127. }
  128. }
  129. var count int
  130. var addWork int
  131. var startTime time.Time
  132. func processFolder(folder string) {
  133. startTime = time.Now()
  134. count = 0
  135. addWork = 0
  136. err := filepath.Walk(folder, func(path string, info os.FileInfo, err error) error {
  137. count++
  138. if (count % 100) == 0 {
  139. fmt.Print(".")
  140. }
  141. if (count % 10000) == 0 {
  142. fmt.Println()
  143. }
  144. filename := info.Name()
  145. if filename[0:1] != "." {
  146. if info.IsDir() {
  147. fmt.Println(path)
  148. if prune {
  149. pruneHash(path)
  150. }
  151. }
  152. if !info.IsDir() {
  153. addWork++
  154. outputHash(path)
  155. if time.Since(startTime).Seconds() > 10.0 {
  156. startTime = time.Now()
  157. saveAllHashFiles()
  158. addWork = 0
  159. }
  160. }
  161. }
  162. return nil
  163. })
  164. if err != nil {
  165. panic(err)
  166. }
  167. }
  168. func pruneHash(dir string) {
  169. _, err := os.Stat(dir + "/.fdhashes3")
  170. if !os.IsNotExist(err) {
  171. hashFile := loadHashfile(dir + "/.fdhashes3")
  172. for filename := range hashFile.Hashes {
  173. _, err := os.Stat(dir + "/" + filename)
  174. if os.IsNotExist(err) {
  175. delete(hashFile.Hashes, filename)
  176. delete(hashFile.Times, filename)
  177. hashFile.Dirty = true
  178. }
  179. }
  180. for filename := range hashFile.Times {
  181. _, err := os.Stat(dir + "/" + filename)
  182. if os.IsNotExist(err) {
  183. delete(hashFile.Hashes, filename)
  184. delete(hashFile.Times, filename)
  185. hashFile.Dirty = true
  186. }
  187. }
  188. saveHashfile(&hashFile)
  189. }
  190. }
  191. func dirtyHashfile(hashFile *Fdhashes) {
  192. hashFile.Dirty = true
  193. }
  194. func saveAllHashFiles() {
  195. hashList := make([]Fdhashes, 0)
  196. for _, hashFile := range hashes {
  197. if hashFile.Dirty {
  198. saveHashfile(&hashFile)
  199. hashList = append(hashList, hashFile)
  200. }
  201. }
  202. hashes = make(map[string]Fdhashes)
  203. for _, hashFile := range hashList {
  204. hashes[hashFile.Path] = hashFile
  205. }
  206. }
  207. func saveHashfile(hashFile *Fdhashes) {
  208. if hashFile.Dirty {
  209. hashFile.Dirty = false
  210. b, err := json.Marshal(hashFile)
  211. if err != nil {
  212. fmt.Println(err)
  213. return
  214. }
  215. err = ioutil.WriteFile(hashFile.Path+"/.fdhashes3", b, 0644)
  216. if err != nil {
  217. panic(err)
  218. }
  219. }
  220. }
  221. func loadHashfile(fileStr string) Fdhashes {
  222. dir, _ := filepath.Split(fileStr)
  223. dir = filepath.ToSlash(filepath.Clean(dir))
  224. data := Fdhashes{Path: dir, Hashes: make(map[string]string), Times: make(map[string]time.Time), Dirty: false}
  225. if !rewrite {
  226. file, err := ioutil.ReadFile(fileStr)
  227. if err != nil {
  228. panic(err)
  229. }
  230. err = json.Unmarshal([]byte(file), &data)
  231. if err != nil {
  232. log.Printf("can't read file %s", fileStr)
  233. }
  234. }
  235. if data.Path != dir {
  236. data.Path = dir
  237. data.Dirty = true
  238. }
  239. return data
  240. }
  241. func compareFolder(folder string) {
  242. loadAllHashFiles(folder)
  243. index := make(map[string][]string)
  244. for _, hashFile := range hashes {
  245. for filename, hash := range hashFile.Hashes {
  246. values := index[hash]
  247. if values == nil {
  248. values = make([]string, 0)
  249. }
  250. values = append(values, fmt.Sprintf("%s/%s", hashFile.Path, filename))
  251. index[hash] = values
  252. }
  253. }
  254. size := len(index)
  255. f, err := os.Create(report)
  256. check(err)
  257. w := bufio.NewWriter(f)
  258. count := 0
  259. var filesize int64
  260. fileCount := 0
  261. for _, values := range index {
  262. count++
  263. if count%100 == 0 {
  264. fmt.Printf("%d (%d) checking\n", count, size)
  265. }
  266. if len(values) > 1 {
  267. info, err := os.Stat(values[0])
  268. if err == nil {
  269. w.WriteString(fmt.Sprintf("found identically hash: size: %d\n", info.Size()))
  270. filesize += int64(len(values)-1) * info.Size()
  271. }
  272. fileCount += len(values) - 1
  273. for _, filename := range values {
  274. w.WriteString(fmt.Sprintf(" %s\n", filename))
  275. }
  276. w.Flush()
  277. }
  278. }
  279. w.WriteString(fmt.Sprintf("can save up to %s on %d files\n", bytefmt.ByteSize(uint64(filesize)), fileCount))
  280. w.Flush()
  281. }
  282. func compareFolder2(folder string) {
  283. loadAllHashFiles(folder)
  284. size := len(hashes)
  285. f, err := os.Create("report.txt")
  286. check(err)
  287. w := bufio.NewWriter(f)
  288. count := 0
  289. for _, hashFile := range hashes {
  290. count++
  291. fmt.Printf("%d (%d) checking: %s\n", count, size, hashFile.Path)
  292. // fmt.Printf("checking: %s\n", hashFile.Path)
  293. for filename, hash := range hashFile.Hashes {
  294. if value, found := search(hash, filename, hashFile.Path); found {
  295. w.WriteString("found identically hash\n")
  296. w.WriteString(fmt.Sprintf(" src: %s/%s\n", hashFile.Path, filename))
  297. w.WriteString(fmt.Sprintf(" dest: %s\n", value))
  298. w.Flush()
  299. }
  300. }
  301. }
  302. }
  303. func search(srcHash string, exFilename string, exFilepath string) (value string, found bool) {
  304. for _, hashFile := range hashes {
  305. for filename, hash := range hashFile.Hashes {
  306. if (filename != exFilename) && (hashFile.Path != exFilepath) {
  307. if hash == srcHash {
  308. value += fmt.Sprintf("%s/%s;", hashFile.Path, filename)
  309. found = true
  310. }
  311. }
  312. }
  313. }
  314. return
  315. }
  316. func loadAllHashFiles(folder string) {
  317. count = 0
  318. addWork = 0
  319. err := filepath.Walk(folder, func(path string, info os.FileInfo, err error) error {
  320. if info != nil {
  321. if info.IsDir() {
  322. fmt.Print(".")
  323. hashFile, ok := hashes[path]
  324. if !ok {
  325. _, err := os.Stat(path + "/.fdhashes3")
  326. if os.IsNotExist(err) {
  327. hashFile = Fdhashes{Path: path, Hashes: make(map[string]string), Times: make(map[string]time.Time), Dirty: true}
  328. } else {
  329. hashFile = loadHashfile(path + "/.fdhashes3")
  330. }
  331. hashes[path] = hashFile
  332. }
  333. }
  334. }
  335. return nil
  336. })
  337. if err != nil {
  338. panic(err)
  339. }
  340. fmt.Printf("\nfound %d hash files.\n", len(hashes))
  341. }
  342. func check(e error) {
  343. if e != nil {
  344. panic(e)
  345. }
  346. }