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.

93 lines
2.7 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. #!/usr/bin/python
  2. import sqlite3
  3. import functools
  4. from imohash import hashfile as _imohash
  5. def hash_file(path,hash_if_less,sample):
  6. return _imohash(path,hash_if_less,sample)
  7. def hashify(top,hashfunc):
  8. old_dir = os.getcwd()
  9. os.chdir(top)
  10. ret = []
  11. for root,dirs,files in os.walk('.'):
  12. try:
  13. for file in files:
  14. filepath = os.path.join(root,file)
  15. hash = hashfunc(filepath)
  16. ret.append(
  17. (
  18. filepath,
  19. hash
  20. )
  21. )
  22. except PermissionError:
  23. print('Access denied:',root)
  24. except Exception as e:
  25. print(e,file)
  26. os.chdir(old_dir)
  27. return ret
  28. def __init_database__(con):
  29. cur = con.cursor()
  30. cur.execute('''CREATE TABLE IF NOT EXISTS `PATHS` (
  31. `PATH` TEXT,
  32. `HASH` BLOB,
  33. `ID` INTEGER)''')
  34. cur.execute('''CREATE TABLE IF NOT EXISTS `BACKUPS` (
  35. `ID` INTEGER,
  36. `HASH_THRESHOLD` INTEGER,
  37. `SAMPLE_SIZE` INTEGER)''')
  38. con.commit()
  39. class fs:
  40. def __init__(self,top,db_path=None,hash_threshold=1024**2,sample_size=128*1024,id=None):
  41. self.top=top
  42. self.hash_threshold=hash_threshold
  43. self.sample_size=sample_size
  44. self.hash_files = {}
  45. self.hashfunc = functools.partial(
  46. hash_file,
  47. hash_if_less=self.hash_threshold,
  48. sample=self.sample_size
  49. )
  50. if db_path is None:
  51. self.db_path = 'fs.db'
  52. else:
  53. self.db_path=db_path
  54. self.con = sqlite3.connect(self.db_path)
  55. __init_database__(self.con)
  56. self.cur = self.con.cursor()
  57. if id is None:
  58. self.cur.execute('SELECT MAX(id) FROM backups')
  59. id=self.cur.fetchone()
  60. if id[0] is None:
  61. self.id = 0
  62. else:
  63. self.id = id[0]+1
  64. else:
  65. self.id = id
  66. def write_to_db(self):
  67. '''stores self.hash_files in database, along with a backup id and hash_func parameters'''
  68. for hash,files in self.hash_files.items():
  69. for file in files:
  70. self.cur.execute('INSERT INTO paths VALUES (?,?,?)',[hash,file,self.id])
  71. self.con.commit()
  72. def morph(self,other):
  73. '''renames/copies all files in self.top to match other'''
  74. pass
  75. def backup(self):
  76. '''fills in self.hash_file {hash:[filepaths]}'''
  77. paths = hashify(self.top,self.hashfunc)
  78. for filepath,hash in paths:
  79. self.hash_files.setdefault(hash,[]).append(filepath)
  80. if __name__ == "__main__":
  81. import os
  82. test = fs(os.getcwd())
  83. test.backup()
  84. test.write_to_db()