此脚本并排打开文件的最后 N 个修订版本。
#!/usr/bin/env python
import os, sys, tempfile
from shutil import rmtree
from subprocess import call, Popen, PIPE
from optparse import OptionParser
from traceback import print_exc
COMMAND = 'vim -d'
def vcall(cmd, **kwargs):
if options.verbose:
print ' '.join(cmd)
return call(' '.join(cmd) if sys.platform == 'darwin' else cmd,
**kwargs)
parser = OptionParser('usage: %s [-n <number of revisions>] filename' %
sys.argv[0])
parser.add_option('-n', '--num', dest='N', type='int',
help='number of revisions', default=3)
parser.add_option('-v', '--verbose', dest='verbose',
help='be verbose', default=False, action='store_true')
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error('incorrect number of arguments')
filename = args[0]
if vcall('git rev-parse'.split()) != 0:
sys.exit(1)
try:
cmd = 'git rev-list HEAD --'.split() + [filename]
if options.verbose:
print ' '.join(cmd)
pipe = Popen(' '.join(cmd) if sys.platform == 'darwin' else cmd,
stdout=PIPE).stdout
revs = []
for i, line in enumerate(pipe):
if i == options.N:
break
revs.append(line.rstrip())
except:
print_exc()
N = len(revs)
if N == 0:
sys.exit('fatal: ambiguous argument %s: path not in the working tree' %
filename)
elif N < options.N:
sys.stderr.write('%s has only %d revision%s' %
(filename, N, 's' if N > 1 else ''))
tempdir = ''
try:
tempdir = tempfile.mkdtemp()
head, tail = os.path.split(filename)
tempfiles = []
for i in xrange(N):
tempfiles.append(tail + ('.%d' % i if i else ''))
for i, f in enumerate(tempfiles):
with open(os.sep.join((tempdir, f)), 'w') as fout:
vcall(['git', 'show', '%s:./%s' % (revs[i], filename)], stdout=fout)
vcall(COMMAND.split() + list(reversed(tempfiles)), shell=True, cwd=tempdir)
except:
print_exc()
finally:
try:
if tempdir and os.path.isdir(tempdir):
rmtree(tempdir)
except:
print_exc()
笔记:
Vimdiff 有一个限制,只能在 4 个(第一个)缓冲区中突出显示差异,但至于并排显示 - 显示所有文件修订版(例如 N=20 效果很好)。为了避免 N>4 的警告,请使用COMMAND = 'vim -O'
并排查看版本,根本没有任何差异。
对于 SO 风格来说,脚本已经变得太大了,但它现在已经非常安全了——但对于有经验的人来说足够简单。