Skip to content

Instantly share code, notes, and snippets.

@imkaka
Created August 11, 2019 11:27
Show Gist options
  • Save imkaka/bad2e97e040bbece70a05603edbe31a5 to your computer and use it in GitHub Desktop.
Save imkaka/bad2e97e040bbece70a05603edbe31a5 to your computer and use it in GitHub Desktop.
A simple scrpit to automate the file recovering from git history, if you need to do that(in case).
import os
import re
import sys
from subprocess import Popen, PIPE
ROOT_FILES_PATH = '/home/<username>/path/to/your/file'
# REgex
STATIC_REGEX = re.compile(r'mobile/(.*?)(\.css|\.js|\.svg|\.less|\.png|\.jpg|\.woff|\.ttf|\.eot|\.txt|\.scss)')
def recover_static(file_path):
"""
Recover Static files in given file from git history, which are deleted.
"""
with open(file_path, 'r') as f:
contents = f.read()
to_urls_iter = re.finditer(STATIC_REGEX, contents)
to_urls = [urls.group() for urls in to_urls_iter]
print("Found urls: ")
print(to_urls)
print()
# get log and commit_id of deleted files
print("Run following git commands to recover files:")
for url in to_urls:
git_command = ['/usr/bin/git', 'rev-list', '-n', '1', 'HEAD', '--']
static_url = 'static/' + url
git_command.extend([static_url])
repository = os.path.dirname('/home/<username>/path/to/project/root/dir/')
git_query = Popen(git_command, cwd=repository, stdout=PIPE, stderr=PIPE)
for line in git_query.stdout:
final_command = f'git checkout {line.decode().strip()}^ -- {static_url}'
print(final_command)
if __name__ == '__main__':
if len(sys.argv) <= 1:
print("Please give filename as command line argument..")
else:
filename = sys.argv[1]
file_path = os.path.join(ROOT_FILES_PATH, filename)
print(f'Recovering starts for : {file_path}...')
recover_static(file_path)
print('\nDone!')
# Tasks:
# 1. We want to take full path of file at cmd argument -- [Done]
# 2. Read the file -- [Done]
# 3. Find full path of static files -- [Regex] -- [Done]
# 4. Run git commands to get commit_id of each file. [Use subprocess] [Done]
# 5. Print command to recover the static files. [Done]
# 6. subprocess for running commands. [Done]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment