Last active
January 25, 2020 18:36
-
-
Save duke79/c8eec6deebc0c379a2f54bd26996913a to your computer and use it in GitHub Desktop.
git utils
This file contains hidden or 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/python3 | |
from subprocess import Popen, PIPE, CalledProcessError | |
def execute(cmd, with_type=False): | |
""" | |
:param cmd: | |
:param with_type: Yield output type as well | |
:return: | |
""" | |
# print("cmd: " + cmd) | |
cmd = str(cmd).split(" ") | |
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=False) | |
for line in iter(proc.stderr.readline, ""): | |
if len(line) == 0: | |
break | |
line = line.decode('utf-8') | |
if with_type: | |
yield {"type": "error", "value": line} | |
else: | |
yield line | |
proc.stderr.close() | |
for line in iter(proc.stdout.readline, ""): | |
if len(line) == 0: | |
break | |
line = line.decode('utf-8') | |
if with_type: | |
yield {"type": "output", "value": line} | |
else: | |
yield line | |
proc.stdout.close() | |
return_code = proc.wait() | |
if return_code: | |
raise Exception(return_code) | |
def recover(query=None, showdiff=False, lookindiff=False): | |
import re | |
def dangling_commits(): | |
cmd = "git fsck --no-reflog" | |
for line in execute(cmd): | |
match = re.match("^dangling commit (.*)", line) | |
if match: | |
commit_hash = match.groups()[0] | |
yield commit_hash | |
commits_res = [] | |
for commit in dangling_commits(): | |
if lookindiff: | |
cmd = f"git show {commit}" | |
else: | |
cmd = f"git show --name-only {commit}" | |
try: | |
for line in execute(cmd): | |
if query.lower() in line.lower(): | |
commits_res.append(commit) | |
except Exception as e: | |
print(f'cmd {cmd} failed') | |
for idx, commit in enumerate(commits_res): | |
print(f'Commit:({idx+1})', commit) | |
if showdiff: | |
cmd = f"git show {commit}" | |
else: | |
cmd = f"git show --name-only {commit}" | |
for line in execute(cmd): | |
print(line) | |
print("\n\n-------\n\n") | |
if __name__ == "__main__": | |
import sys | |
recover(sys.argv[1] if len(sys.argv) else None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To find lost commits or stashes with keyword 'redux' -
python3 path/to/git_recover.py redux