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