d1faa7c29040407fd80a8724f5c1e565ca00d24b
   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, getopt
  14
  15branch = "refs/heads/p4"
  16prefix = previousDepotPath = os.popen("git-repo-config --get p4.depotpath").read()
  17if len(prefix) != 0:
  18    prefix = prefix[:-1]
  19
  20try:
  21    opts, args = getopt.getopt(sys.argv[1:], "", [ "branch=" ])
  22except getopt.GetoptError:
  23    print "fixme, syntax error"
  24    sys.exit(1)
  25
  26for o, a in opts:
  27    if o == "--branch":
  28        branch = "refs/heads/" + a
  29
  30if len(args) == 0 and len(prefix) != 0:
  31    print "[using previously specified depot path %s]" % prefix
  32elif len(args) != 1:
  33    print "usage: %s //depot/path[@revRange]" % sys.argv[0]
  34    print "\n    example:"
  35    print "    %s //depot/my/project/ -- to import the current head"
  36    print "    %s //depot/my/project/@all -- to import everything"
  37    print "    %s //depot/my/project/@1,6 -- to import only from revision 1 to 6"
  38    print ""
  39    print "    (a ... is not needed in the path p4 specification, it's added implicitly)"
  40    print ""
  41    sys.exit(1)
  42else:
  43    if len(prefix) != 0 and prefix != args[0]:
  44        print "previous import used depot path %s and now %s was specified. this doesn't work!" % (prefix, args[0])
  45        sys.exit(1)
  46    prefix = args[0]
  47
  48changeRange = ""
  49revision = ""
  50users = {}
  51initialParent = ""
  52
  53if prefix.find("@") != -1:
  54    atIdx = prefix.index("@")
  55    changeRange = prefix[atIdx:]
  56    if changeRange == "@all":
  57        changeRange = ""
  58    elif changeRange.find(",") == -1:
  59        revision = changeRange
  60        changeRange = ""
  61    prefix = prefix[0:atIdx]
  62elif prefix.find("#") != -1:
  63    hashIdx = prefix.index("#")
  64    revision = prefix[hashIdx:]
  65    prefix = prefix[0:hashIdx]
  66elif len(previousDepotPath) == 0:
  67    revision = "#head"
  68
  69if prefix.endswith("..."):
  70    prefix = prefix[:-3]
  71
  72if not prefix.endswith("/"):
  73    prefix += "/"
  74
  75def p4CmdList(cmd):
  76    pipe = os.popen("p4 -G %s" % cmd, "rb")
  77    result = []
  78    try:
  79        while True:
  80            entry = marshal.load(pipe)
  81            result.append(entry)
  82    except EOFError:
  83        pass
  84    pipe.close()
  85    return result
  86
  87def p4Cmd(cmd):
  88    list = p4CmdList(cmd)
  89    result = {}
  90    for entry in list:
  91        result.update(entry)
  92    return result;
  93
  94def commit(details):
  95    global initialParent
  96    global users
  97
  98    epoch = details["time"]
  99    author = details["user"]
 100
 101    gitStream.write("commit %s\n" % branch)
 102    committer = ""
 103    if author in users:
 104        committer = "%s %s %s" % (users[author], epoch, tz)
 105    else:
 106        committer = "%s <a@b> %s %s" % (author, epoch, tz)
 107
 108    gitStream.write("committer %s\n" % committer)
 109
 110    gitStream.write("data <<EOT\n")
 111    gitStream.write(details["desc"])
 112    gitStream.write("\n[ imported from %s; change %s ]\n" % (prefix, details["change"]))
 113    gitStream.write("EOT\n\n")
 114
 115    if len(initialParent) > 0:
 116        gitStream.write("from %s\n" % initialParent)
 117        initialParent = ""
 118
 119    fnum = 0
 120    while details.has_key("depotFile%s" % fnum):
 121        path = details["depotFile%s" % fnum]
 122        if not path.startswith(prefix):
 123            print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, prefix, change)
 124            fnum = fnum + 1
 125            continue
 126
 127        rev = details["rev%s" % fnum]
 128        depotPath = path + "#" + rev
 129        relPath = path[len(prefix):]
 130        action = details["action%s" % fnum]
 131
 132        if action == "delete":
 133            gitStream.write("D %s\n" % relPath)
 134        else:
 135            mode = 644
 136            if details["type%s" % fnum].startswith("x"):
 137                mode = 755
 138
 139            data = os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
 140
 141            gitStream.write("M %s inline %s\n" % (mode, relPath))
 142            gitStream.write("data %s\n" % len(data))
 143            gitStream.write(data)
 144            gitStream.write("\n")
 145
 146        fnum = fnum + 1
 147
 148    gitStream.write("\n")
 149
 150    gitStream.write("tag p4/%s\n" % details["change"])
 151    gitStream.write("from %s\n" % branch);
 152    gitStream.write("tagger %s\n" % committer);
 153    gitStream.write("data 0\n\n")
 154
 155
 156def getUserMap():
 157    users = {}
 158
 159    for output in p4CmdList("users"):
 160        if not output.has_key("User"):
 161            continue
 162        users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
 163    return users
 164
 165users = getUserMap()
 166
 167if len(changeRange) == 0:
 168    try:
 169        sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
 170        output = sout.read()
 171        tagIdx = output.index(" tags/p4/")
 172        caretIdx = output.index("^")
 173        rev = int(output[tagIdx + 9 : caretIdx]) + 1
 174        changeRange = "@%s,#head" % rev
 175        initialParent = os.popen("git-rev-parse %s" % branch).read()[:-1]
 176    except:
 177        pass
 178
 179sys.stderr.write("\n")
 180
 181tz = - time.timezone / 36
 182tzsign = ("%s" % tz)[0]
 183if tzsign != '+' and tzsign != '-':
 184    tz = "+" + ("%s" % tz)
 185
 186gitOutput, gitStream, gitError = popen2.popen3("git-fast-import")
 187
 188if len(revision) > 0:
 189    print "Doing initial import of %s from revision %s" % (prefix, revision)
 190
 191    details = { "user" : "git perforce import user", "time" : int(time.time()) }
 192    details["desc"] = "Initial import of %s from the state at revision %s" % (prefix, revision)
 193    details["change"] = revision
 194    newestRevision = 0
 195
 196    fileCnt = 0
 197    for info in p4CmdList("files %s...%s" % (prefix, revision)):
 198        change = int(info["change"])
 199        if change > newestRevision:
 200            newestRevision = change
 201
 202        if info["action"] == "delete":
 203            continue
 204
 205        for prop in [ "depotFile", "rev", "action", "type" ]:
 206            details["%s%s" % (prop, fileCnt)] = info[prop]
 207
 208        fileCnt = fileCnt + 1
 209
 210    details["change"] = newestRevision
 211
 212    try:
 213        commit(details)
 214    except:
 215        print gitError.read()
 216
 217else:
 218    output = os.popen("p4 changes %s...%s" % (prefix, changeRange)).readlines()
 219
 220    changes = []
 221    for line in output:
 222        changeNum = line.split(" ")[1]
 223        changes.append(changeNum)
 224
 225    changes.reverse()
 226
 227    if len(changes) == 0:
 228        print "no changes to import!"
 229        sys.exit(1)
 230
 231    cnt = 1
 232    for change in changes:
 233        description = p4Cmd("describe %s" % change)
 234
 235        sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
 236        sys.stdout.flush()
 237        cnt = cnt + 1
 238
 239        try:
 240            commit(description)
 241        except:
 242            print gitError.read()
 243            sys.exit(1)
 244
 245print ""
 246
 247gitStream.close()
 248gitOutput.close()
 249gitError.close()
 250
 251os.popen("git-repo-config p4.depotpath %s" % prefix).read()
 252
 253sys.exit(0)