Last active
September 7, 2022 17:07
-
-
Save cebtenzzre/6e64650f34f5b7b9dd2de237e6cd7729 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import json | |
import os | |
import shutil | |
with open('rmlint.json') as f: | |
doc = json.load(f) | |
doc = doc[1:-1] # strip header/footer | |
# collect originals of deleted files | |
originals = {} | |
for file in doc: | |
if file['type'] == 'duplicate_file' and file['is_original']: | |
if 'checksum' in file: | |
originals[file['checksum']] = file['path'] | |
else: | |
print('WARNING: skipping original with no checksum: {}'.format(file['path'])) | |
files_restored = 0 | |
for file in doc: | |
typ, path, mtime = file['type'], file['path'], float(file['mtime']) | |
if typ == 'duplicate_file' and file['is_original']: | |
continue # skip originals | |
if os.path.exists(path): | |
print('WARNING: file already exists: {}'.format(path)) | |
continue | |
if typ == 'duplicate_file': | |
if 'checksum' not in file: | |
print('WARNING: skipping dupe with no checksum: {}'.format(path)) | |
continue | |
orig = originals[file['checksum']] | |
print('restoring {!r} -> {!r}'.format(orig, path)) | |
shutil.copyfile(orig, path) | |
shutil.copystat(orig, path) | |
elif typ == 'emptyfile': | |
print('restoring empty file: {}'.format(path)) | |
with open(path, 'w'): | |
pass | |
elif typ == 'emptydir': | |
print('restoring empty directory: {}'.format(path)) | |
os.makedirs(path, exist_ok=True) | |
else: | |
print('WARNING: cannot restore {}: {}'.format(typ, path)) | |
continue | |
os.utime(path, (mtime, mtime)) # restore file timestamps | |
files_restored += 1 | |
print('\nSuccessfully restored {} files.'.format(files_restored)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment