backup_blends.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # (c) J.Y.Amihud 2022
  2. # This program is Free Software under the terms of
  3. # GNU General Public License version 3 ( GPL3 ) or
  4. # any later version of the program.
  5. # THIS PROGRAM HAS ABSOLUTELY NO WARRANTY. USE AT
  6. # YOUR OWN RISK. SEE LICENSE FOR DETAILS.
  7. # License could be found in full text on gnu.org/licenses
  8. import os
  9. import json
  10. import sys
  11. import time
  12. import hashlib
  13. # We need to know what folder to backup.
  14. if len(sys.argv) > 1:
  15. project = sys.argv[1]
  16. else:
  17. project = input("Project: ")
  18. # To compare changes in files the best way is to look at their
  19. # hashes. They are relatively fast to get. But they will be drastically
  20. # different if the files have at least some differences.
  21. def hash_file(f):
  22. try:
  23. BLOCKSIZE = 65536
  24. hasher = hashlib.md5()
  25. with open(f, 'rb') as afile:
  26. buf = afile.read(BLOCKSIZE)
  27. while len(buf) > 0:
  28. hasher.update(buf)
  29. buf = afile.read(BLOCKSIZE)
  30. return str(hasher.hexdigest())
  31. except:
  32. return "FOLDER"
  33. # This function walks ( recursively ) through the folder of the project,
  34. # finds every un-backed up blend-file. And backs it up.
  35. def main():
  36. for i in os.walk(project):
  37. for b in i[2]:
  38. if b.endswith(".blend") and "_backup" not in b:
  39. HASH = hash_file(i[0]+"/"+b)
  40. F = open(i[0]+"/"+b, "rb")
  41. F = F.read()
  42. if not F:
  43. print(b, "from", i[0].replace(project, ""), " seems corrupted! Skipping!")
  44. continue
  45. BACKNAME = b[:-6]+"_backup.blend"
  46. if os.path.exists(i[0]+"/"+BACKNAME):
  47. BACKHASH = hash_file(i[0]+"/"+BACKNAME)
  48. else:
  49. BACKHASH = "NO FILE"
  50. if BACKHASH != HASH:
  51. print("Backing up:", b, "from", i[0].replace(project, ""), "...")
  52. #F = open(i[0]+"/"+b, "rb")
  53. S = open(i[0]+"/"+BACKNAME, "wb")
  54. S.write(F)
  55. S.close()
  56. # Main loop ( 30 seconds intervals )
  57. while True:
  58. try:
  59. with open(project+"/backup_data.json") as f:
  60. backup_data = json.load(f)
  61. except:
  62. backup_data = {}
  63. backup_data["lastcheck"] = int(time.time())
  64. with open(project+"/backup_data.json", "w") as f:
  65. json.dump(backup_data, f, indent=4)
  66. print("Counting another 30 seconds...")
  67. time.sleep(30)
  68. print("Checking for changed files...")
  69. main()