19f5f034763a348668811891a892b8480b8c8511
   1#!/usr/bin/python
   2#
   3# p4-fast-export.py
   4#
   5# Author: Simon Hausmann <hausmann@kde.org>
   6# License: MIT <http://www.opensource.org/licenses/mit-license.php>
   7#
   8# TODO:
   9#       - support integrations (at least p4i)
  10#       - support p4 submit (hah!)
  11#
  12import os, string, sys, time
  13import marshal, popen2
  14
  15if len(sys.argv) != 2:
  16    print "usage: %s //depot/path[@revRange]" % sys.argv[0]
  17    print "\n    example:"
  18    print "    %s //depot/my/project/ -- to import everything"
  19    print "    %s //depot/my/project/@1,6 -- to import only from revision 1 to 6"
  20    print ""
  21    print "    (a ... is not needed in the path p4 specification, it's added implicitly)"
  22    print ""
  23    sys.exit(1)
  24
  25branch = "refs/heads/p4"
  26prefix = sys.argv[1]
  27changeRange = ""
  28revision = ""
  29users = {}
  30initialParent = ""
  31
  32if prefix.find("@") != -1:
  33    atIdx = prefix.index("@")
  34    changeRange = prefix[atIdx:]
  35    if changeRange.find(",") == -1:
  36        revision = changeRange
  37        changeRange = ""
  38    prefix = prefix[0:atIdx]
  39elif prefix.find("#") != -1:
  40    hashIdx = prefix.index("#")
  41    revision = prefix[hashIdx:]
  42    prefix = prefix[0:hashIdx]
  43
  44if prefix.endswith("..."):
  45    prefix = prefix[:-3]
  46
  47if not prefix.endswith("/"):
  48    prefix += "/"
  49
  50def p4CmdList(cmd):
  51    pipe = os.popen("p4 -G %s" % cmd, "rb")
  52    result = []
  53    try:
  54        while True:
  55            entry = marshal.load(pipe)
  56            result.append(entry)
  57    except EOFError:
  58        pass
  59    pipe.close()
  60    return result
  61
  62def p4Cmd(cmd):
  63    list = p4CmdList(cmd)
  64    result = {}
  65    for entry in list:
  66        result.update(entry)
  67    return result;
  68
  69def commit(details):
  70    global initialParent
  71    global users
  72
  73    epoch = details["time"]
  74    author = details["user"]
  75
  76    gitStream.write("commit %s\n" % branch)
  77    committer = ""
  78    if author in users:
  79        committer = "%s %s %s" % (users[author], epoch, tz)
  80    else:
  81        committer = "%s <a@b> %s %s" % (author, epoch, tz)
  82
  83    gitStream.write("committer %s\n" % committer)
  84
  85    gitStream.write("data <<EOT\n")
  86    gitStream.write(details["desc"])
  87    gitStream.write("\n[ imported from %s; change %s ]\n" % (prefix, details["change"]))
  88    gitStream.write("EOT\n\n")
  89
  90    if len(initialParent) > 0:
  91        gitStream.write("merge %s\n" % initialParent)
  92        initialParent = ""
  93
  94    fnum = 0
  95    while details.has_key("depotFile%s" % fnum):
  96        path = details["depotFile%s" % fnum]
  97        if not path.startswith(prefix):
  98            print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, prefix, change)
  99            fnum = fnum + 1
 100            continue
 101
 102        rev = details["rev%s" % fnum]
 103        depotPath = path + "#" + rev
 104        relPath = path[len(prefix):]
 105        action = details["action%s" % fnum]
 106
 107        if action == "delete":
 108            gitStream.write("D %s\n" % relPath)
 109        else:
 110            mode = 644
 111            if details["type%s" % fnum].startswith("x"):
 112                mode = 755
 113
 114            data = os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
 115
 116            gitStream.write("M %s inline %s\n" % (mode, relPath))
 117            gitStream.write("data %s\n" % len(data))
 118            gitStream.write(data)
 119            gitStream.write("\n")
 120
 121        fnum = fnum + 1
 122
 123    gitStream.write("\n")
 124
 125    gitStream.write("tag p4/%s\n" % details["change"])
 126    gitStream.write("from %s\n" % branch);
 127    gitStream.write("tagger %s\n" % committer);
 128    gitStream.write("data 0\n\n")
 129
 130
 131def getUserMap():
 132    users = {}
 133
 134    for output in p4CmdList("users"):
 135        if not output.has_key("User"):
 136            continue
 137        users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
 138    return users
 139
 140users = getUserMap()
 141
 142if len(changeRange) == 0:
 143    try:
 144        sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
 145        output = sout.read()
 146        tagIdx = output.index(" tags/p4/")
 147        caretIdx = output.index("^")
 148        rev = int(output[tagIdx + 9 : caretIdx]) + 1
 149        changeRange = "@%s,#head" % rev
 150        initialParent = os.popen("git-rev-parse %s" % branch).read()[:-1]
 151    except:
 152        pass
 153
 154sys.stderr.write("\n")
 155
 156tz = - time.timezone / 36
 157
 158if len(revision) > 0:
 159    print "Doing initial import of %s from revision %s" % (prefix, revision)
 160
 161    details = { "user" : "git perforce import user", "time" : int(time.time()) }
 162    details["desc"] = "Initial import of %s from the state at revision %s" % (prefix, revision)
 163    details["change"] = revision
 164    newestRevision = 0
 165
 166    fileCnt = 0
 167    for info in p4CmdList("files %s...%s" % (prefix, revision)):
 168        if info["action"] == "delete":
 169            continue
 170        for prop in [ "depotFile", "rev", "action", "type" ]:
 171            details["%s%s" % (prop, fileCnt)] = info[prop]
 172
 173        change = info["change"]
 174        if change > newestRevision:
 175            newestRevision = change
 176
 177        fileCnt = fileCnt + 1
 178
 179    details["change"] = newestRevision
 180
 181    gitOutput, gitStream, gitError = popen2.popen3("git-fast-import")
 182    commit(details)
 183
 184    gitStream.close()
 185    gitOutput.close()
 186    gitError.close()
 187else:
 188    output = os.popen("p4 changes %s...%s" % (prefix, changeRange)).readlines()
 189
 190    changes = []
 191    for line in output:
 192        changeNum = line.split(" ")[1]
 193        changes.append(changeNum)
 194
 195    changes.reverse()
 196
 197    if len(changes) == 0:
 198        print "no changes to import!"
 199        sys.exit(1)
 200
 201    gitOutput, gitStream, gitError = popen2.popen3("git-fast-import")
 202
 203    cnt = 1
 204    for change in changes:
 205        description = p4Cmd("describe %s" % change)
 206
 207        sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
 208        sys.stdout.flush()
 209        cnt = cnt + 1
 210
 211        commit(description)
 212
 213    gitStream.close()
 214    gitOutput.close()
 215    gitError.close()
 216
 217print ""