Skip to content

Instantly share code, notes, and snippets.

@SmilyOrg
Last active June 8, 2016 20:59
Show Gist options
  • Save SmilyOrg/90472c653acb9d705254e78e429f6a76 to your computer and use it in GitHub Desktop.
Save SmilyOrg/90472c653acb9d705254e78e429f6a76 to your computer and use it in GitHub Desktop.
Find closest commit in a repo to a working dir without history
#!/usr/bin/env python
import subprocess
import shlex
import sys
import os
import posixpath
import operator
# original by unutbu: http://stackoverflow.com/a/7779979
# revised by Miha Lunar
print sys.argv[1]
gitdir,workdir=map(os.path.abspath,sys.argv[1:3])
print gitdir, workdir
os.chdir(gitdir)
proc=subprocess.Popen(shlex.split('git rev-list --all'),stdout=subprocess.PIPE)
shas,err=proc.communicate()
shas=shas.split()
head=shas[0]
data={}
for sha1 in shas:
subprocess.Popen(shlex.split('git checkout {s}'.format(s=sha1))).wait()
diffcmd = 'diff "{g}" "{w}"'.format(g=gitdir,w=workdir)
print diffcmd
proc=subprocess.Popen(shlex.split(diffcmd),
stdout=subprocess.PIPE)
out,err=proc.communicate()
distance=len(out)
data[sha1]=distance
answer=min(data.items(),key=operator.itemgetter(1))[0]
print('{current} closest: {closest}'.format(current=sha1, closest=answer))
subprocess.Popen(shlex.split('git checkout {h}'.format(h=head))).wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment