|
| 1 | +## File by _baku89 on twitter |
| 2 | +## Source: https://gist.github.com/baku89/615a15228e5747d4e83fa579796009fe |
| 3 | + |
| 4 | +## Modified & Added to toolset by: Paul Ambrosiussen |
| 5 | + |
| 6 | +import hou |
| 7 | +import glob, os, re |
| 8 | +from stat import ST_MTIME |
| 9 | +from datetime import datetime |
| 10 | + |
| 11 | +def recoverFile(): |
| 12 | + # Get a filename of the most recent opened file |
| 13 | + userPrefDir = hou.getenv('HOUDINI_USER_PREF_DIR') |
| 14 | + historyPath = os.path.join(userPrefDir, 'file.history') |
| 15 | + |
| 16 | + destPath = None |
| 17 | + filename = None |
| 18 | + |
| 19 | + if not os.path.exists(historyPath): |
| 20 | + return False |
| 21 | + |
| 22 | + |
| 23 | + with open(historyPath, 'r') as file: |
| 24 | + txt = file.read() |
| 25 | + result = re.search(r'^HIP\n{\n((?:[^\n]*(\n+))+?)}', txt) |
| 26 | + |
| 27 | + if not result: |
| 28 | + return False |
| 29 | + |
| 30 | + recentFiles = [path for path in result.groups()[0].split('\n') if path] |
| 31 | + |
| 32 | + if len(recentFiles) == 0: |
| 33 | + return False |
| 34 | + |
| 35 | + destPath = recentFiles[-1] |
| 36 | + filename = os.path.basename(destPath) |
| 37 | + |
| 38 | + # Get the backup file |
| 39 | + tempDir = hou.getenv('HOUDINI_TEMP_DIR') |
| 40 | + |
| 41 | + os.chdir(tempDir) |
| 42 | + |
| 43 | + bakPattern = r"^crash\.%s\.(.*)\%s" % os.path.splitext(filename) |
| 44 | + entries = [name for name in glob.glob('*.hip*') if re.match(bakPattern, name)] |
| 45 | + entries = [(os.stat(path)[ST_MTIME], path) for path in entries] |
| 46 | + |
| 47 | + if len(entries) == 0: |
| 48 | + hou.ui.displayMessage('No backup file for %s has found' % filename) |
| 49 | + return False |
| 50 | + |
| 51 | + bakDate, bakFile = sorted(entries, reverse=True)[0] |
| 52 | + bakPath = os.path.join(tempDir, bakFile) |
| 53 | + |
| 54 | + bakDate = datetime.fromtimestamp(int(bakDate)) |
| 55 | + bakDate = bakDate.strftime("%m/%d/%Y, %H:%M:%S") |
| 56 | + |
| 57 | + |
| 58 | + # Ask whether restore or not |
| 59 | + msg = "The backup of the most recent opened file has found. Do you want to restore it?" |
| 60 | + details = ( |
| 61 | + "Location: " + os.path.dirname(destPath) + "\n" |
| 62 | + "Original: " + filename + "\n" |
| 63 | + "Backup: " + bakFile + " (" + bakDate + ")") |
| 64 | + options = ('Yes', 'Cancel') |
| 65 | + |
| 66 | + if hou.ui.displayMessage(msg, options, close_choice=1, details=details, details_expanded=True) == 1: |
| 67 | + return False |
| 68 | + |
| 69 | + prefix, ext = os.path.splitext(destPath) |
| 70 | + os.rename(destPath, prefix + '_copy' + ext) |
| 71 | + os.rename(bakPath, destPath) |
| 72 | + |
| 73 | + if hou.ui.displayMessage('Do you want to open the file?', ('Yes', 'Cancel'), close_choice=1): |
| 74 | + hou.hipFile.load(destPath) |
| 75 | + |
0 commit comments