contrib / fast-import / p4-fast-export.pyon commit Split up the cache commandline options into (command) cache and data cache. (4fe2ca1)
   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#       - emulate p4's delete behavior: if a directory becomes empty delete it. continue
  12#         with parent dir until non-empty dir is found.
  13#
  14import os, string, sys, time, os.path
  15import marshal, popen2, getopt, sha
  16from sets import Set;
  17
  18dataCache = False
  19commandCache = False
  20
  21silent = False
  22knownBranches = Set()
  23createdBranches = Set()
  24committedChanges = Set()
  25branch = "refs/heads/master"
  26globalPrefix = previousDepotPath = os.popen("git-repo-config --get p4.depotpath").read()
  27detectBranches = False
  28changesFile = ""
  29if len(globalPrefix) != 0:
  30    globalPrefix = globalPrefix[:-1]
  31
  32try:
  33    opts, args = getopt.getopt(sys.argv[1:], "", [ "branch=", "detect-branches", "changesfile=", "silent", "known-branches=",
  34                                                   "cache", "command-cache" ])
  35except getopt.GetoptError:
  36    print "fixme, syntax error"
  37    sys.exit(1)
  38
  39for o, a in opts:
  40    if o == "--branch":
  41        branch = "refs/heads/" + a
  42    elif o == "--detect-branches":
  43        detectBranches = True
  44    elif o == "--changesfile":
  45        changesFile = a
  46    elif o == "--silent":
  47        silent= True
  48    elif o == "--known-branches":
  49        for branch in open(a).readlines():
  50            knownBranches.add(branch[:-1])
  51    elif o == "--cache":
  52        dataCache = True
  53        commandCache = True
  54    elif o == "--command-cache":
  55        commandCache = True
  56
  57if len(args) == 0 and len(globalPrefix) != 0:
  58    if not silent:
  59        print "[using previously specified depot path %s]" % globalPrefix
  60elif len(args) != 1:
  61    print "usage: %s //depot/path[@revRange]" % sys.argv[0]
  62    print "\n    example:"
  63    print "    %s //depot/my/project/ -- to import the current head"
  64    print "    %s //depot/my/project/@all -- to import everything"
  65    print "    %s //depot/my/project/@1,6 -- to import only from revision 1 to 6"
  66    print ""
  67    print "    (a ... is not needed in the path p4 specification, it's added implicitly)"
  68    print ""
  69    sys.exit(1)
  70else:
  71    if len(globalPrefix) != 0 and globalPrefix != args[0]:
  72        print "previous import used depot path %s and now %s was specified. this doesn't work!" % (globalPrefix, args[0])
  73        sys.exit(1)
  74    globalPrefix = args[0]
  75
  76changeRange = ""
  77revision = ""
  78users = {}
  79initialParent = ""
  80lastChange = 0
  81initialTag = ""
  82
  83if globalPrefix.find("@") != -1:
  84    atIdx = globalPrefix.index("@")
  85    changeRange = globalPrefix[atIdx:]
  86    if changeRange == "@all":
  87        changeRange = ""
  88    elif changeRange.find(",") == -1:
  89        revision = changeRange
  90        changeRange = ""
  91    globalPrefix = globalPrefix[0:atIdx]
  92elif globalPrefix.find("#") != -1:
  93    hashIdx = globalPrefix.index("#")
  94    revision = globalPrefix[hashIdx:]
  95    globalPrefix = globalPrefix[0:hashIdx]
  96elif len(previousDepotPath) == 0:
  97    revision = "#head"
  98
  99if globalPrefix.endswith("..."):
 100    globalPrefix = globalPrefix[:-3]
 101
 102if not globalPrefix.endswith("/"):
 103    globalPrefix += "/"
 104
 105def p4File(depotPath):
 106    cacheKey = "/tmp/p4cache/data-" + sha.new(depotPath).hexdigest()
 107
 108    data = 0
 109    try:
 110        if not dataCache:
 111            raise
 112        data = open(cacheKey, "rb").read()
 113    except:
 114        data = os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
 115        if dataCache:
 116            open(cacheKey, "wb").write(data)
 117
 118    return data
 119
 120def p4CmdList(cmd):
 121    fullCmd = "p4 -G %s" % cmd;
 122
 123    cacheKey = sha.new(fullCmd).hexdigest()
 124    cacheKey = "/tmp/p4cache/cmd-" + cacheKey
 125
 126    cached = True
 127    pipe = 0
 128    try:
 129        if not commandCache:
 130            raise
 131        pipe = open(cacheKey, "rb")
 132    except:
 133        cached = False
 134        pipe = os.popen(fullCmd, "rb")
 135
 136    result = []
 137    try:
 138        while True:
 139            entry = marshal.load(pipe)
 140            result.append(entry)
 141    except EOFError:
 142        pass
 143    pipe.close()
 144
 145    if not cached and commandCache:
 146        pipe = open(cacheKey, "wb")
 147        for r in result:
 148            marshal.dump(r, pipe)
 149        pipe.close()
 150
 151    return result
 152
 153def p4Cmd(cmd):
 154    list = p4CmdList(cmd)
 155    result = {}
 156    for entry in list:
 157        result.update(entry)
 158    return result;
 159
 160def extractFilesFromCommit(commit):
 161    files = []
 162    fnum = 0
 163    while commit.has_key("depotFile%s" % fnum):
 164        path =  commit["depotFile%s" % fnum]
 165        if not path.startswith(globalPrefix):
 166#            if not silent:
 167#                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, globalPrefix, change)
 168            fnum = fnum + 1
 169            continue
 170
 171        file = {}
 172        file["path"] = path
 173        file["rev"] = commit["rev%s" % fnum]
 174        file["action"] = commit["action%s" % fnum]
 175        file["type"] = commit["type%s" % fnum]
 176        files.append(file)
 177        fnum = fnum + 1
 178    return files
 179
 180def isSubPathOf(first, second):
 181    if not first.startswith(second):
 182        return False
 183    if first == second:
 184        return True
 185    return first[len(second)] == "/"
 186
 187def branchesForCommit(files):
 188    global knownBranches
 189    branches = Set()
 190
 191    for file in files:
 192        relativePath = file["path"][len(globalPrefix):]
 193        # strip off the filename
 194        relativePath = relativePath[0:relativePath.rfind("/")]
 195
 196#        if len(branches) == 0:
 197#            branches.add(relativePath)
 198#            knownBranches.add(relativePath)
 199#            continue
 200
 201        ###### this needs more testing :)
 202        knownBranch = False
 203        for branch in branches:
 204            if relativePath == branch:
 205                knownBranch = True
 206                break
 207#            if relativePath.startswith(branch):
 208            if isSubPathOf(relativePath, branch):
 209                knownBranch = True
 210                break
 211#            if branch.startswith(relativePath):
 212            if isSubPathOf(branch, relativePath):
 213                branches.remove(branch)
 214                break
 215
 216        if knownBranch:
 217            continue
 218
 219        for branch in knownBranches:
 220            #if relativePath.startswith(branch):
 221            if isSubPathOf(relativePath, branch):
 222                if len(branches) == 0:
 223                    relativePath = branch
 224                else:
 225                    knownBranch = True
 226                break
 227
 228        if knownBranch:
 229            continue
 230
 231        branches.add(relativePath)
 232        knownBranches.add(relativePath)
 233
 234    return branches
 235
 236def findBranchParent(branchPrefix, files):
 237    for file in files:
 238        path = file["path"]
 239        if not path.startswith(branchPrefix):
 240            continue
 241        action = file["action"]
 242        if action != "integrate" and action != "branch":
 243            continue
 244        rev = file["rev"]
 245        depotPath = path + "#" + rev
 246
 247        log = p4CmdList("filelog \"%s\"" % depotPath)
 248        if len(log) != 1:
 249            print "eek! I got confused by the filelog of %s" % depotPath
 250            sys.exit(1);
 251
 252        log = log[0]
 253        if log["action0"] != action:
 254            print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
 255            sys.exit(1);
 256
 257        branchAction = log["how0,0"]
 258#        if branchAction == "branch into" or branchAction == "ignored":
 259#            continue # ignore for branching
 260
 261        if not branchAction.endswith(" from"):
 262            continue # ignore for branching
 263#            print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
 264#            sys.exit(1);
 265
 266        source = log["file0,0"]
 267        if source.startswith(branchPrefix):
 268            continue
 269
 270        lastSourceRev = log["erev0,0"]
 271
 272        sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
 273        if len(sourceLog) != 1:
 274            print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
 275            sys.exit(1);
 276        sourceLog = sourceLog[0]
 277
 278        relPath = source[len(globalPrefix):]
 279        # strip off the filename
 280        relPath = relPath[0:relPath.rfind("/")]
 281
 282        for branch in knownBranches:
 283            if isSubPathOf(relPath, branch):
 284#                print "determined parent branch branch %s due to change in file %s" % (branch, source)
 285                return branch
 286#            else:
 287#                print "%s is not a subpath of branch %s" % (relPath, branch)
 288
 289    return ""
 290
 291def commit(details, files, branch, branchPrefix, parent, merged = ""):
 292    global users
 293    global lastChange
 294    global committedChanges
 295
 296    epoch = details["time"]
 297    author = details["user"]
 298
 299    gitStream.write("commit %s\n" % branch)
 300#    gitStream.write("mark :%s\n" % details["change"])
 301    committedChanges.add(int(details["change"]))
 302    committer = ""
 303    if author in users:
 304        committer = "%s %s %s" % (users[author], epoch, tz)
 305    else:
 306        committer = "%s <a@b> %s %s" % (author, epoch, tz)
 307
 308    gitStream.write("committer %s\n" % committer)
 309
 310    gitStream.write("data <<EOT\n")
 311    gitStream.write(details["desc"])
 312    gitStream.write("\n[ imported from %s; change %s ]\n" % (branchPrefix, details["change"]))
 313    gitStream.write("EOT\n\n")
 314
 315    if len(parent) > 0:
 316        gitStream.write("from %s\n" % parent)
 317
 318    if len(merged) > 0:
 319        gitStream.write("merge %s\n" % merged)
 320
 321    for file in files:
 322        path = file["path"]
 323        if not path.startswith(branchPrefix):
 324#            if not silent:
 325#                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
 326            continue
 327        rev = file["rev"]
 328        depotPath = path + "#" + rev
 329        relPath = path[len(branchPrefix):]
 330        action = file["action"]
 331
 332        if action == "delete":
 333            gitStream.write("D %s\n" % relPath)
 334        else:
 335            mode = 644
 336            if file["type"].startswith("x"):
 337                mode = 755
 338
 339            data = p4File(depotPath)
 340
 341            gitStream.write("M %s inline %s\n" % (mode, relPath))
 342            gitStream.write("data %s\n" % len(data))
 343            gitStream.write(data)
 344            gitStream.write("\n")
 345
 346    gitStream.write("\n")
 347
 348    lastChange = int(details["change"])
 349
 350def extractFilesInCommitToBranch(files, branchPrefix):
 351    newFiles = []
 352
 353    for file in files:
 354        path = file["path"]
 355        if path.startswith(branchPrefix):
 356            newFiles.append(file)
 357
 358    return newFiles
 359
 360def findBranchSourceHeuristic(files, branch, branchPrefix):
 361    for file in files:
 362        action = file["action"]
 363        if action != "integrate" and action != "branch":
 364            continue
 365        path = file["path"]
 366        rev = file["rev"]
 367        depotPath = path + "#" + rev
 368
 369        log = p4CmdList("filelog \"%s\"" % depotPath)
 370        if len(log) != 1:
 371            print "eek! I got confused by the filelog of %s" % depotPath
 372            sys.exit(1);
 373
 374        log = log[0]
 375        if log["action0"] != action:
 376            print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
 377            sys.exit(1);
 378
 379        branchAction = log["how0,0"]
 380
 381        if not branchAction.endswith(" from"):
 382            continue # ignore for branching
 383#            print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
 384#            sys.exit(1);
 385
 386        source = log["file0,0"]
 387        if source.startswith(branchPrefix):
 388            continue
 389
 390        lastSourceRev = log["erev0,0"]
 391
 392        sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
 393        if len(sourceLog) != 1:
 394            print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
 395            sys.exit(1);
 396        sourceLog = sourceLog[0]
 397
 398        relPath = source[len(globalPrefix):]
 399        # strip off the filename
 400        relPath = relPath[0:relPath.rfind("/")]
 401
 402        for candidate in knownBranches:
 403            if isSubPathOf(relPath, candidate) and candidate != branch:
 404                return candidate
 405
 406    return ""
 407
 408def changeIsBranchMerge(sourceBranch, destinationBranch, change):
 409    sourceFiles = {}
 410    for file in p4CmdList("files %s...@%s" % (globalPrefix + sourceBranch + "/", change)):
 411        if file["action"] == "delete":
 412            continue
 413        sourceFiles[file["depotFile"]] = file
 414
 415    destinationFiles = {}
 416    for file in p4CmdList("files %s...@%s" % (globalPrefix + destinationBranch + "/", change)):
 417        destinationFiles[file["depotFile"]] = file
 418
 419    for fileName in sourceFiles.keys():
 420        integrations = []
 421        deleted = False
 422        integrationCount = 0
 423        for integration in p4CmdList("integrated \"%s\"" % fileName):
 424            toFile = integration["fromFile"] # yes, it's true, it's fromFile
 425            if not toFile in destinationFiles:
 426                continue
 427            destFile = destinationFiles[toFile]
 428            if destFile["action"] == "delete":
 429#                print "file %s has been deleted in %s" % (fileName, toFile)
 430                deleted = True
 431                break
 432            integrationCount += 1
 433            if integration["how"] == "branch from":
 434                continue
 435
 436            if int(integration["change"]) == change:
 437                integrations.append(integration)
 438                continue
 439            if int(integration["change"]) > change:
 440                continue
 441
 442            destRev = int(destFile["rev"])
 443
 444            startRev = integration["startFromRev"][1:]
 445            if startRev == "none":
 446                startRev = 0
 447            else:
 448                startRev = int(startRev)
 449
 450            endRev = integration["endFromRev"][1:]
 451            if endRev == "none":
 452                endRev = 0
 453            else:
 454                endRev = int(endRev)
 455
 456            initialBranch = (destRev == 1 and integration["how"] != "branch into")
 457            inRange = (destRev >= startRev and destRev <= endRev)
 458            newer = (destRev > startRev and destRev > endRev)
 459
 460            if initialBranch or inRange or newer:
 461                integrations.append(integration)
 462
 463        if deleted:
 464            continue
 465
 466        if len(integrations) == 0 and integrationCount > 1:
 467            print "file %s was not integrated from %s into %s" % (fileName, sourceBranch, destinationBranch)
 468            return False
 469
 470    return True
 471
 472def getUserMap():
 473    users = {}
 474
 475    for output in p4CmdList("users"):
 476        if not output.has_key("User"):
 477            continue
 478        users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
 479    return users
 480
 481users = getUserMap()
 482
 483if len(changeRange) == 0:
 484    try:
 485        sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
 486        output = sout.read()
 487        if output.endswith("\n"):
 488            output = output[:-1]
 489        tagIdx = output.index(" tags/p4/")
 490        caretIdx = output.find("^")
 491        endPos = len(output)
 492        if caretIdx != -1:
 493            endPos = caretIdx
 494        rev = int(output[tagIdx + 9 : endPos]) + 1
 495        changeRange = "@%s,#head" % rev
 496        initialParent = os.popen("git-rev-parse %s" % branch).read()[:-1]
 497        initialTag = "p4/%s" % (int(rev) - 1)
 498    except:
 499        pass
 500
 501tz = - time.timezone / 36
 502tzsign = ("%s" % tz)[0]
 503if tzsign != '+' and tzsign != '-':
 504    tz = "+" + ("%s" % tz)
 505
 506gitOutput, gitStream, gitError = popen2.popen3("git-fast-import")
 507
 508if len(revision) > 0:
 509    print "Doing initial import of %s from revision %s" % (globalPrefix, revision)
 510
 511    details = { "user" : "git perforce import user", "time" : int(time.time()) }
 512    details["desc"] = "Initial import of %s from the state at revision %s" % (globalPrefix, revision)
 513    details["change"] = revision
 514    newestRevision = 0
 515
 516    fileCnt = 0
 517    for info in p4CmdList("files %s...%s" % (globalPrefix, revision)):
 518        change = int(info["change"])
 519        if change > newestRevision:
 520            newestRevision = change
 521
 522        if info["action"] == "delete":
 523            continue
 524
 525        for prop in [ "depotFile", "rev", "action", "type" ]:
 526            details["%s%s" % (prop, fileCnt)] = info[prop]
 527
 528        fileCnt = fileCnt + 1
 529
 530    details["change"] = newestRevision
 531
 532    try:
 533        commit(details, extractFilesFromCommit(details), branch, globalPrefix)
 534    except:
 535        print gitError.read()
 536
 537else:
 538    changes = []
 539
 540    if len(changesFile) > 0:
 541        output = open(changesFile).readlines()
 542        changeSet = Set()
 543        for line in output:
 544            changeSet.add(int(line))
 545
 546        for change in changeSet:
 547            changes.append(change)
 548
 549        changes.sort()
 550    else:
 551        output = os.popen("p4 changes %s...%s" % (globalPrefix, changeRange)).readlines()
 552
 553        for line in output:
 554            changeNum = line.split(" ")[1]
 555            changes.append(changeNum)
 556
 557        changes.reverse()
 558
 559    if len(changes) == 0:
 560        if not silent:
 561            print "no changes to import!"
 562        sys.exit(1)
 563
 564    cnt = 1
 565    for change in changes:
 566        description = p4Cmd("describe %s" % change)
 567
 568        if not silent:
 569            sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
 570            sys.stdout.flush()
 571        cnt = cnt + 1
 572
 573        try:
 574            files = extractFilesFromCommit(description)
 575            if detectBranches:
 576                for branch in branchesForCommit(files):
 577                    knownBranches.add(branch)
 578                    branchPrefix = globalPrefix + branch + "/"
 579
 580                    filesForCommit = extractFilesInCommitToBranch(files, branchPrefix)
 581
 582                    merged = ""
 583                    parent = ""
 584                    ########### remove cnt!!!
 585                    if branch not in createdBranches and cnt > 2:
 586                        createdBranches.add(branch)
 587                        parent = findBranchParent(branchPrefix, files)
 588                        if parent == branch:
 589                            parent = ""
 590    #                    elif len(parent) > 0:
 591    #                        print "%s branched off of %s" % (branch, parent)
 592
 593                    if len(parent) == 0:
 594                        merged = findBranchSourceHeuristic(filesForCommit, branch, branchPrefix)
 595                        if len(merged) > 0:
 596                            print "change %s could be a merge from %s into %s" % (description["change"], merged, branch)
 597                            if not changeIsBranchMerge(merged, branch, int(description["change"])):
 598                                merged = ""
 599
 600                    branch = "refs/heads/" + branch
 601                    if len(parent) > 0:
 602                        parent = "refs/heads/" + parent
 603                    if len(merged) > 0:
 604                        merged = "refs/heads/" + merged
 605                    commit(description, files, branch, branchPrefix, parent, merged)
 606            else:
 607                commit(description, filesForCommit, branch, globalPrefix, initialParent)
 608                initialParent = ""
 609        except IOError:
 610            print gitError.read()
 611            sys.exit(1)
 612
 613if not silent:
 614    print ""
 615
 616gitStream.write("reset refs/tags/p4/%s\n" % lastChange)
 617gitStream.write("from %s\n\n" % branch);
 618
 619
 620gitStream.close()
 621gitOutput.close()
 622gitError.close()
 623
 624os.popen("git-repo-config p4.depotpath %s" % globalPrefix).read()
 625if len(initialTag) > 0:
 626    os.popen("git tag -d %s" % initialTag).read()
 627
 628sys.exit(0)