1#!/usr/bin/python
2
3import os, sys, subprocess
4
5def main():
6    from optparse import OptionParser, OptionGroup
7    parser = OptionParser("usage: %prog [options] <repo> <revision>")
8    parser.add_option("", "--branch", dest="branch",
9                      help="Ref for the branch to search [%default]",
10                      action="store", default="git-svn")
11    (opts, args) = parser.parse_args()
12
13    if len(args) != 2:
14        parser.error("invalid number of arguments")
15
16    repo,rev = args
17
18    try:
19        rev = int(rev)
20    except:
21        parser.error("invalid revision argument (not an integer)")
22
23    os.chdir(repo)
24    p = subprocess.Popen(['git', 'rev-list', opts.branch, '--pretty'],
25                         stdout=subprocess.PIPE)
26
27    bestRev = bestCommit = None
28    lastCommit = None
29    for ln in p.stdout:
30        if ln.startswith('commit '):
31            lastCommit = ln.split(' ',2)[1]
32        elif ln.startswith('    git-svn-id: '):
33            _,repo,_ = ln.strip().split(' ')
34            _,lrev = repo.rsplit('@',1)
35            lrev = int(lrev)
36            if lrev<=rev:
37                if bestRev is None or lrev>bestRev:
38                    assert lastCommit
39                    bestCommit = lastCommit
40                    bestRev = lrev
41                    if lrev == rev:
42                        break
43
44    if bestCommit is not None:
45        print bestCommit
46        sys.exit(0)
47    sys.exit(1)
48
49if __name__=='__main__':
50    main()
51