Skip to content

Instantly share code, notes, and snippets.

@posoo
Last active September 16, 2021 22:23
Show Gist options
  • Save posoo/7c1e6483c790847dda4aca7092b39e1e to your computer and use it in GitHub Desktop.
Save posoo/7c1e6483c790847dda4aca7092b39e1e to your computer and use it in GitHub Desktop.
Recover original files from `.bak` files. Search in directories recursively.
# A progra conducted file conversion and made a copy of the original file as .bak file
# .bak files have name convention of <original_file_name>.<timestamp>.bak
# This simple program help to reverse such conversion.
import os
import click
def get_sub_files_and_dirs(parent_dir):
files_in_dir = []
dirs_in_dir = []
entities_in_dir = os.listdir(parent_dir)
for e in entities_in_dir:
entity_path = os.path.join(parent_dir, e)
if os.path.isdir(entity_path):
dirs_in_dir.append(e)
elif os.path.isfile(entity_path):
files_in_dir.append(e)
else:
print(f'Unknown entity type: {entity_path}')
return files_in_dir, dirs_in_dir
def check_and_recover_file(file_name, parent_dir, files_in_parent_dir):
if not file_name.endswith('.bak'):
return
bak_file_path = os.path.join(parent_dir, file_name)
ori_file_name = '.'.join(file_name.split('.')[:-2])
ori_file_path = os.path.join(parent_dir, ori_file_name)
if ori_file_name in files_in_parent_dir:
os.remove(ori_file_path)
print(f'Removed converted file: {ori_file_path}')
else:
print(f'[Warning] cannot find converted file of :{bak_file_path}')
os.rename(bak_file_path, ori_file_path)
print(f'Recovered converted file: {ori_file_path}')
def entity_recursor(entity_name, parent_dir, files_in_parent_dir):
entity_path = os.path.join(parent_dir, entity_name)
if os.path.isfile(entity_path):
if not files_in_parent_dir:
files_in_parent_dir = os.listdir(parent_dir)
check_and_recover_file(entity_name, parent_dir, files_in_parent_dir)
return
elif os.path.isdir(entity_path):
sub_entities = os.listdir(entity_path)
sub_files = [se for se in sub_entities if os.path.isfile(os.path.join(entity_path, se))]
for e in sub_entities:
entity_recursor(e, entity_path, sub_files)
return
else:
print(f'Unsupported entity path: {entity_path}')
@click.command()
@click.argument('entity_path', type=click.Path(exists=True))
def main(entity_path):
entity_parent, entity_name = os.path.split(entity_path)
entity_recursor(entity_name, entity_parent, None)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment