07d6e53852c2d76b0b16b91450eeec0c5e2d9cde
   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/master"
  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 = ""
  52lastChange = ""
  53initialTag = ""
  54
  55if prefix.find("@") != -1:
  56    atIdx = prefix.index("@")
  57    changeRange = prefix[atIdx:]
  58    if changeRange == "@all":
  59        changeRange = ""
  60    elif changeRange.find(",") == -1:
  61        revision = changeRange
  62        changeRange = ""
  63    prefix = prefix[0:atIdx]
  64elif prefix.find("#") != -1:
  65    hashIdx = prefix.index("#")
  66    revision = prefix[hashIdx:]
  67    prefix = prefix[0:hashIdx]
  68elif len(previousDepotPath) == 0:
  69    revision = "#head"
  70
  71if prefix.endswith("..."):
  72    prefix = prefix[:-3]
  73
  74if not prefix.endswith("/"):
  75    prefix += "/"
  76
  77def p4CmdList(cmd):
  78    pipe = os.popen("p4 -G %s" % cmd, "rb")
  79    result = []
  80    try:
  81        while True:
  82            entry = marshal.load(pipe)
  83            result.append(entry)
  84    except EOFError:
  85        pass
  86    pipe.close()
  87    return result
  88
  89def p4Cmd(cmd):
  90    list = p4CmdList(cmd)
  91    result = {}
  92    for entry in list:
  93        result.update(entry)
  94    return result;
  95
  96def extractFilesFromCommit(commit):
  97    files = []
  98    fnum = 0
  99    while commit.has_key("depotFile%s" % fnum):
 100        file = {}
 101        file["path"] = commit["depotFile%s" % fnum]
 102        file["rev"] = commit["rev%s" % fnum]
 103        file["action"] = commit["action%s" % fnum]
 104        file["type"] = commit["type%s" % fnum]
 105        files.append(file)
 106        fnum = fnum + 1
 107    return files
 108
 109def commit(details, files, branch):
 110    global initialParent
 111    global users
 112    global lastChange
 113
 114    epoch = details["time"]
 115    author = details["user"]
 116
 117    gitStream.write("commit %s\n" % branch)
 118    committer = ""
 119    if author in users:
 120        committer = "%s %s %s" % (users[author], epoch, tz)
 121    else:
 122        committer = "%s <a@b> %s %s" % (author, epoch, tz)
 123
 124    gitStream.write("committer %s\n" % committer)
 125
 126    gitStream.write("data <<EOT\n")
 127    gitStream.write(details["desc"])
 128    gitStream.write("\n[ imported from %s; change %s ]\n" % (prefix, details["change"]))
 129    gitStream.write("EOT\n\n")
 130
 131    if len(initialParent) > 0:
 132        gitStream.write("from %s\n" % initialParent)
 133        initialParent = ""
 134
 135    for file in files:
 136        path = file["path"]
 137        if not path.startswith(prefix):
 138            print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, prefix, change)
 139            continue
 140
 141        rev = file["rev"]
 142        depotPath = path + "#" + rev
 143        relPath = path[len(prefix):]
 144        action = file["action"]
 145
 146        if action == "delete":
 147            gitStream.write("D %s\n" % relPath)
 148        else:
 149            mode = 644
 150            if file["type"].startswith("x"):
 151                mode = 755
 152
 153            data = os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
 154
 155            gitStream.write("M %s inline %s\n" % (mode, relPath))
 156            gitStream.write("data %s\n" % len(data))
 157            gitStream.write(data)
 158            gitStream.write("\n")
 159
 160    gitStream.write("\n")
 161
 162    lastChange = details["change"]
 163
 164def getUserMap():
 165    users = {}
 166
 167    for output in p4CmdList("users"):
 168        if not output.has_key("User"):
 169            continue
 170        users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
 171    return users
 172
 173users = getUserMap()
 174
 175if len(changeRange) == 0:
 176    try:
 177        sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
 178        output = sout.read()
 179        if output.endswith("\n"):
 180            output = output[:-1]
 181        tagIdx = output.index(" tags/p4/")
 182        caretIdx = output.find("^")
 183        endPos = len(output)
 184        if caretIdx != -1:
 185            endPos = caretIdx
 186        rev = int(output[tagIdx + 9 : endPos]) + 1
 187        changeRange = "@%s,#head" % rev
 188        initialParent = os.popen("git-rev-parse %s" % branch).read()[:-1]
 189        initialTag = "p4/%s" % (int(rev) - 1)
 190    except:
 191        pass
 192
 193sys.stderr.write("\n")
 194
 195tz = - time.timezone / 36
 196tzsign = ("%s" % tz)[0]
 197if tzsign != '+' and tzsign != '-':
 198    tz = "+" + ("%s" % tz)
 199
 200gitOutput, gitStream, gitError = popen2.popen3("git-fast-import")
 201
 202if len(revision) > 0:
 203    print "Doing initial import of %s from revision %s" % (prefix, revision)
 204
 205    details = { "user" : "git perforce import user", "time" : int(time.time()) }
 206    details["desc"] = "Initial import of %s from the state at revision %s" % (prefix, revision)
 207    details["change"] = revision
 208    newestRevision = 0
 209
 210    fileCnt = 0
 211    for info in p4CmdList("files %s...%s" % (prefix, revision)):
 212        change = int(info["change"])
 213        if change > newestRevision:
 214            newestRevision = change
 215
 216        if info["action"] == "delete":
 217            continue
 218
 219        for prop in [ "depotFile", "rev", "action", "type" ]:
 220            details["%s%s" % (prop, fileCnt)] = info[prop]
 221
 222        fileCnt = fileCnt + 1
 223
 224    details["change"] = newestRevision
 225
 226    try:
 227        commit(details, extractFilesFromCommit(details), branch)
 228    except:
 229        print gitError.read()
 230
 231else:
 232    output = os.popen("p4 changes %s...%s" % (prefix, changeRange)).readlines()
 233
 234    changes = []
 235    for line in output:
 236        changeNum = line.split(" ")[1]
 237        changes.append(changeNum)
 238
 239    changes.reverse()
 240
 241    if len(changes) == 0:
 242        print "no changes to import!"
 243        sys.exit(1)
 244
 245    cnt = 1
 246    for change in changes:
 247        description = p4Cmd("describe %s" % change)
 248
 249        sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
 250        sys.stdout.flush()
 251        cnt = cnt + 1
 252
 253        try:
 254            commit(description, extractFilesFromCommit(description), branch)
 255        except:
 256            print gitError.read()
 257            sys.exit(1)
 258
 259print ""
 260
 261gitStream.write("reset refs/tags/p4/%s\n" % lastChange)
 262gitStream.write("from %s\n\n" % branch);
 263
 264
 265gitStream.close()
 266gitOutput.close()
 267gitError.close()
 268
 269os.popen("git-repo-config p4.depotpath %s" % prefix).read()
 270if len(initialTag) > 0:
 271    os.popen("git tag -d %s" % initialTag).read()
 272
 273sys.exit(0)