GoHash.go 9.6 KB

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