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