contrib / fast-import / git-p4on commit Make --with-origin the default for syncing. (0126510)
   1#!/usr/bin/env python
   2#
   3# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
   4#
   5# Author: Simon Hausmann <hausmann@kde.org>
   6# Copyright: 2007 Simon Hausmann <hausmann@kde.org>
   7#            2007 Trolltech ASA
   8# License: MIT <http://www.opensource.org/licenses/mit-license.php>
   9#
  10# TODO: * Consider making --with-origin the default, assuming that the git
  11#         protocol is always more efficient. (needs manual testing first :)
  12#
  13
  14import optparse, sys, os, marshal, popen2, subprocess, shelve
  15import tempfile, getopt, sha, os.path, time, platform
  16from sets import Set;
  17
  18gitdir = os.environ.get("GIT_DIR", "")
  19
  20def mypopen(command):
  21    return os.popen(command, "rb");
  22
  23def p4CmdList(cmd):
  24    cmd = "p4 -G %s" % cmd
  25    pipe = os.popen(cmd, "rb")
  26
  27    result = []
  28    try:
  29        while True:
  30            entry = marshal.load(pipe)
  31            result.append(entry)
  32    except EOFError:
  33        pass
  34    exitCode = pipe.close()
  35    if exitCode != None:
  36        entry = {}
  37        entry["p4ExitCode"] = exitCode
  38        result.append(entry)
  39
  40    return result
  41
  42def p4Cmd(cmd):
  43    list = p4CmdList(cmd)
  44    result = {}
  45    for entry in list:
  46        result.update(entry)
  47    return result;
  48
  49def p4Where(depotPath):
  50    if not depotPath.endswith("/"):
  51        depotPath += "/"
  52    output = p4Cmd("where %s..." % depotPath)
  53    if output["code"] == "error":
  54        return ""
  55    clientPath = ""
  56    if "path" in output:
  57        clientPath = output.get("path")
  58    elif "data" in output:
  59        data = output.get("data")
  60        lastSpace = data.rfind(" ")
  61        clientPath = data[lastSpace + 1:]
  62
  63    if clientPath.endswith("..."):
  64        clientPath = clientPath[:-3]
  65    return clientPath
  66
  67def die(msg):
  68    sys.stderr.write(msg + "\n")
  69    sys.exit(1)
  70
  71def currentGitBranch():
  72    return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
  73
  74def isValidGitDir(path):
  75    if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
  76        return True;
  77    return False
  78
  79def parseRevision(ref):
  80    return mypopen("git rev-parse %s" % ref).read()[:-1]
  81
  82def system(cmd):
  83    if os.system(cmd) != 0:
  84        die("command failed: %s" % cmd)
  85
  86def extractLogMessageFromGitCommit(commit):
  87    logMessage = ""
  88    foundTitle = False
  89    for log in mypopen("git cat-file commit %s" % commit).readlines():
  90       if not foundTitle:
  91           if len(log) == 1:
  92               foundTitle = True
  93           continue
  94
  95       logMessage += log
  96    return logMessage
  97
  98def extractDepotPathAndChangeFromGitLog(log):
  99    values = {}
 100    for line in log.split("\n"):
 101        line = line.strip()
 102        if line.startswith("[git-p4:") and line.endswith("]"):
 103            line = line[8:-1].strip()
 104            for assignment in line.split(":"):
 105                variable = assignment.strip()
 106                value = ""
 107                equalPos = assignment.find("=")
 108                if equalPos != -1:
 109                    variable = assignment[:equalPos].strip()
 110                    value = assignment[equalPos + 1:].strip()
 111                    if value.startswith("\"") and value.endswith("\""):
 112                        value = value[1:-1]
 113                values[variable] = value
 114
 115    return values.get("depot-path"), values.get("change")
 116
 117def gitBranchExists(branch):
 118    proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
 119    return proc.wait() == 0;
 120
 121def gitConfig(key):
 122    return mypopen("git config %s" % key).read()[:-1]
 123
 124class Command:
 125    def __init__(self):
 126        self.usage = "usage: %prog [options]"
 127        self.needsGit = True
 128
 129class P4Debug(Command):
 130    def __init__(self):
 131        Command.__init__(self)
 132        self.options = [
 133        ]
 134        self.description = "A tool to debug the output of p4 -G."
 135        self.needsGit = False
 136
 137    def run(self, args):
 138        for output in p4CmdList(" ".join(args)):
 139            print output
 140        return True
 141
 142class P4RollBack(Command):
 143    def __init__(self):
 144        Command.__init__(self)
 145        self.options = [
 146            optparse.make_option("--verbose", dest="verbose", action="store_true"),
 147            optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
 148        ]
 149        self.description = "A tool to debug the multi-branch import. Don't use :)"
 150        self.verbose = False
 151        self.rollbackLocalBranches = False
 152
 153    def run(self, args):
 154        if len(args) != 1:
 155            return False
 156        maxChange = int(args[0])
 157
 158        if "p4ExitCode" in p4Cmd("changes -m 1"):
 159            die("Problems executing p4");
 160
 161        if self.rollbackLocalBranches:
 162            refPrefix = "refs/heads/"
 163            lines = mypopen("git rev-parse --symbolic --branches").readlines()
 164        else:
 165            refPrefix = "refs/remotes/"
 166            lines = mypopen("git rev-parse --symbolic --remotes").readlines()
 167
 168        for line in lines:
 169            if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
 170                ref = refPrefix + line[:-1]
 171                log = extractLogMessageFromGitCommit(ref)
 172                depotPath, change = extractDepotPathAndChangeFromGitLog(log)
 173                changed = False
 174
 175                if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
 176                    print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
 177                    system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
 178                    continue
 179
 180                while len(change) > 0 and int(change) > maxChange:
 181                    changed = True
 182                    if self.verbose:
 183                        print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
 184                    system("git update-ref %s \"%s^\"" % (ref, ref))
 185                    log = extractLogMessageFromGitCommit(ref)
 186                    depotPath, change = extractDepotPathAndChangeFromGitLog(log)
 187
 188                if changed:
 189                    print "%s rewound to %s" % (ref, change)
 190
 191        return True
 192
 193class P4Submit(Command):
 194    def __init__(self):
 195        Command.__init__(self)
 196        self.options = [
 197                optparse.make_option("--continue", action="store_false", dest="firstTime"),
 198                optparse.make_option("--origin", dest="origin"),
 199                optparse.make_option("--reset", action="store_true", dest="reset"),
 200                optparse.make_option("--log-substitutions", dest="substFile"),
 201                optparse.make_option("--noninteractive", action="store_false"),
 202                optparse.make_option("--dry-run", action="store_true"),
 203                optparse.make_option("--direct", dest="directSubmit", action="store_true"),
 204        ]
 205        self.description = "Submit changes from git to the perforce depot."
 206        self.usage += " [name of git branch to submit into perforce depot]"
 207        self.firstTime = True
 208        self.reset = False
 209        self.interactive = True
 210        self.dryRun = False
 211        self.substFile = ""
 212        self.firstTime = True
 213        self.origin = ""
 214        self.directSubmit = False
 215
 216        self.logSubstitutions = {}
 217        self.logSubstitutions["<enter description here>"] = "%log%"
 218        self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
 219
 220    def check(self):
 221        if len(p4CmdList("opened ...")) > 0:
 222            die("You have files opened with perforce! Close them before starting the sync.")
 223
 224    def start(self):
 225        if len(self.config) > 0 and not self.reset:
 226            die("Cannot start sync. Previous sync config found at %s\nIf you want to start submitting again from scratch maybe you want to call git-p4 submit --reset" % self.configFile)
 227
 228        commits = []
 229        if self.directSubmit:
 230            commits.append("0")
 231        else:
 232            for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
 233                commits.append(line[:-1])
 234            commits.reverse()
 235
 236        self.config["commits"] = commits
 237
 238    def prepareLogMessage(self, template, message):
 239        result = ""
 240
 241        for line in template.split("\n"):
 242            if line.startswith("#"):
 243                result += line + "\n"
 244                continue
 245
 246            substituted = False
 247            for key in self.logSubstitutions.keys():
 248                if line.find(key) != -1:
 249                    value = self.logSubstitutions[key]
 250                    value = value.replace("%log%", message)
 251                    if value != "@remove@":
 252                        result += line.replace(key, value) + "\n"
 253                    substituted = True
 254                    break
 255
 256            if not substituted:
 257                result += line + "\n"
 258
 259        return result
 260
 261    def apply(self, id):
 262        if self.directSubmit:
 263            print "Applying local change in working directory/index"
 264            diff = self.diffStatus
 265        else:
 266            print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
 267            diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
 268        filesToAdd = set()
 269        filesToDelete = set()
 270        editedFiles = set()
 271        for line in diff:
 272            modifier = line[0]
 273            path = line[1:].strip()
 274            if modifier == "M":
 275                system("p4 edit \"%s\"" % path)
 276                editedFiles.add(path)
 277            elif modifier == "A":
 278                filesToAdd.add(path)
 279                if path in filesToDelete:
 280                    filesToDelete.remove(path)
 281            elif modifier == "D":
 282                filesToDelete.add(path)
 283                if path in filesToAdd:
 284                    filesToAdd.remove(path)
 285            else:
 286                die("unknown modifier %s for %s" % (modifier, path))
 287
 288        if self.directSubmit:
 289            diffcmd = "cat \"%s\"" % self.diffFile
 290        else:
 291            diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
 292        patchcmd = diffcmd + " | git apply "
 293        tryPatchCmd = patchcmd + "--check -"
 294        applyPatchCmd = patchcmd + "--check --apply -"
 295
 296        if os.system(tryPatchCmd) != 0:
 297            print "Unfortunately applying the change failed!"
 298            print "What do you want to do?"
 299            response = "x"
 300            while response != "s" and response != "a" and response != "w":
 301                response = raw_input("[s]kip this patch / [a]pply the patch forcibly and with .rej files / [w]rite the patch to a file (patch.txt) ")
 302            if response == "s":
 303                print "Skipping! Good luck with the next patches..."
 304                return
 305            elif response == "a":
 306                os.system(applyPatchCmd)
 307                if len(filesToAdd) > 0:
 308                    print "You may also want to call p4 add on the following files:"
 309                    print " ".join(filesToAdd)
 310                if len(filesToDelete):
 311                    print "The following files should be scheduled for deletion with p4 delete:"
 312                    print " ".join(filesToDelete)
 313                die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
 314            elif response == "w":
 315                system(diffcmd + " > patch.txt")
 316                print "Patch saved to patch.txt in %s !" % self.clientPath
 317                die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
 318
 319        system(applyPatchCmd)
 320
 321        for f in filesToAdd:
 322            system("p4 add %s" % f)
 323        for f in filesToDelete:
 324            system("p4 revert %s" % f)
 325            system("p4 delete %s" % f)
 326
 327        logMessage = ""
 328        if not self.directSubmit:
 329            logMessage = extractLogMessageFromGitCommit(id)
 330            logMessage = logMessage.replace("\n", "\n\t")
 331            logMessage = logMessage[:-1]
 332
 333        template = mypopen("p4 change -o").read()
 334
 335        if self.interactive:
 336            submitTemplate = self.prepareLogMessage(template, logMessage)
 337            diff = mypopen("p4 diff -du ...").read()
 338
 339            for newFile in filesToAdd:
 340                diff += "==== new file ====\n"
 341                diff += "--- /dev/null\n"
 342                diff += "+++ %s\n" % newFile
 343                f = open(newFile, "r")
 344                for line in f.readlines():
 345                    diff += "+" + line
 346                f.close()
 347
 348            separatorLine = "######## everything below this line is just the diff #######"
 349            if platform.system() == "Windows":
 350                separatorLine += "\r"
 351            separatorLine += "\n"
 352
 353            response = "e"
 354            firstIteration = True
 355            while response == "e":
 356                if not firstIteration:
 357                    response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
 358                firstIteration = False
 359                if response == "e":
 360                    [handle, fileName] = tempfile.mkstemp()
 361                    tmpFile = os.fdopen(handle, "w+")
 362                    tmpFile.write(submitTemplate + separatorLine + diff)
 363                    tmpFile.close()
 364                    defaultEditor = "vi"
 365                    if platform.system() == "Windows":
 366                        defaultEditor = "notepad"
 367                    editor = os.environ.get("EDITOR", defaultEditor);
 368                    system(editor + " " + fileName)
 369                    tmpFile = open(fileName, "rb")
 370                    message = tmpFile.read()
 371                    tmpFile.close()
 372                    os.remove(fileName)
 373                    submitTemplate = message[:message.index(separatorLine)]
 374
 375            if response == "y" or response == "yes":
 376               if self.dryRun:
 377                   print submitTemplate
 378                   raw_input("Press return to continue...")
 379               else:
 380                   if self.directSubmit:
 381                       print "Submitting to git first"
 382                       os.chdir(self.oldWorkingDirectory)
 383                       pipe = os.popen("git commit -a -F -", "wb")
 384                       pipe.write(submitTemplate)
 385                       pipe.close()
 386                       os.chdir(self.clientPath)
 387
 388                   pipe = os.popen("p4 submit -i", "wb")
 389                   pipe.write(submitTemplate)
 390                   pipe.close()
 391            elif response == "s":
 392                for f in editedFiles:
 393                    system("p4 revert \"%s\"" % f);
 394                for f in filesToAdd:
 395                    system("p4 revert \"%s\"" % f);
 396                    system("rm %s" %f)
 397                for f in filesToDelete:
 398                    system("p4 delete \"%s\"" % f);
 399                return
 400            else:
 401                print "Not submitting!"
 402                self.interactive = False
 403        else:
 404            fileName = "submit.txt"
 405            file = open(fileName, "w+")
 406            file.write(self.prepareLogMessage(template, logMessage))
 407            file.close()
 408            print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
 409
 410    def run(self, args):
 411        global gitdir
 412        # make gitdir absolute so we can cd out into the perforce checkout
 413        gitdir = os.path.abspath(gitdir)
 414        os.environ["GIT_DIR"] = gitdir
 415
 416        if len(args) == 0:
 417            self.master = currentGitBranch()
 418            if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
 419                die("Detecting current git branch failed!")
 420        elif len(args) == 1:
 421            self.master = args[0]
 422        else:
 423            return False
 424
 425        depotPath = ""
 426        if gitBranchExists("p4"):
 427            [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
 428        if len(depotPath) == 0 and gitBranchExists("origin"):
 429            [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
 430
 431        if len(depotPath) == 0:
 432            print "Internal error: cannot locate perforce depot path from existing branches"
 433            sys.exit(128)
 434
 435        self.clientPath = p4Where(depotPath)
 436
 437        if len(self.clientPath) == 0:
 438            print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
 439            sys.exit(128)
 440
 441        print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
 442        self.oldWorkingDirectory = os.getcwd()
 443
 444        if self.directSubmit:
 445            self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
 446            if len(self.diffStatus) == 0:
 447                print "No changes in working directory to submit."
 448                return True
 449            patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
 450            self.diffFile = gitdir + "/p4-git-diff"
 451            f = open(self.diffFile, "wb")
 452            f.write(patch)
 453            f.close();
 454
 455        os.chdir(self.clientPath)
 456        response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
 457        if response == "y" or response == "yes":
 458            system("p4 sync ...")
 459
 460        if len(self.origin) == 0:
 461            if gitBranchExists("p4"):
 462                self.origin = "p4"
 463            else:
 464                self.origin = "origin"
 465
 466        if self.reset:
 467            self.firstTime = True
 468
 469        if len(self.substFile) > 0:
 470            for line in open(self.substFile, "r").readlines():
 471                tokens = line[:-1].split("=")
 472                self.logSubstitutions[tokens[0]] = tokens[1]
 473
 474        self.check()
 475        self.configFile = gitdir + "/p4-git-sync.cfg"
 476        self.config = shelve.open(self.configFile, writeback=True)
 477
 478        if self.firstTime:
 479            self.start()
 480
 481        commits = self.config.get("commits", [])
 482
 483        while len(commits) > 0:
 484            self.firstTime = False
 485            commit = commits[0]
 486            commits = commits[1:]
 487            self.config["commits"] = commits
 488            self.apply(commit)
 489            if not self.interactive:
 490                break
 491
 492        self.config.close()
 493
 494        if self.directSubmit:
 495            os.remove(self.diffFile)
 496
 497        if len(commits) == 0:
 498            if self.firstTime:
 499                print "No changes found to apply between %s and current HEAD" % self.origin
 500            else:
 501                print "All changes applied!"
 502                os.chdir(self.oldWorkingDirectory)
 503                response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
 504                if response == "y" or response == "yes":
 505                    rebase = P4Rebase()
 506                    rebase.run([])
 507            os.remove(self.configFile)
 508
 509        return True
 510
 511class P4Sync(Command):
 512    def __init__(self):
 513        Command.__init__(self)
 514        self.options = [
 515                optparse.make_option("--branch", dest="branch"),
 516                optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
 517                optparse.make_option("--changesfile", dest="changesFile"),
 518                optparse.make_option("--silent", dest="silent", action="store_true"),
 519                optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
 520                optparse.make_option("--verbose", dest="verbose", action="store_true"),
 521                optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
 522                optparse.make_option("--max-changes", dest="maxChanges")
 523        ]
 524        self.description = """Imports from Perforce into a git repository.\n
 525    example:
 526    //depot/my/project/ -- to import the current head
 527    //depot/my/project/@all -- to import everything
 528    //depot/my/project/@1,6 -- to import only from revision 1 to 6
 529
 530    (a ... is not needed in the path p4 specification, it's added implicitly)"""
 531
 532        self.usage += " //depot/path[@revRange]"
 533
 534        self.silent = False
 535        self.createdBranches = Set()
 536        self.committedChanges = Set()
 537        self.branch = ""
 538        self.detectBranches = False
 539        self.detectLabels = False
 540        self.changesFile = ""
 541        self.syncWithOrigin = True
 542        self.verbose = False
 543        self.importIntoRemotes = True
 544        self.maxChanges = ""
 545        self.isWindows = (platform.system() == "Windows")
 546
 547        if gitConfig("git-p4.syncFromOrigin") == "false":
 548            self.syncWithOrigin = False
 549
 550    def p4File(self, depotPath):
 551        return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
 552
 553    def extractFilesFromCommit(self, commit):
 554        files = []
 555        fnum = 0
 556        while commit.has_key("depotFile%s" % fnum):
 557            path =  commit["depotFile%s" % fnum]
 558            if not path.startswith(self.depotPath):
 559    #            if not self.silent:
 560    #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
 561                fnum = fnum + 1
 562                continue
 563
 564            file = {}
 565            file["path"] = path
 566            file["rev"] = commit["rev%s" % fnum]
 567            file["action"] = commit["action%s" % fnum]
 568            file["type"] = commit["type%s" % fnum]
 569            files.append(file)
 570            fnum = fnum + 1
 571        return files
 572
 573    def splitFilesIntoBranches(self, commit):
 574        branches = {}
 575
 576        fnum = 0
 577        while commit.has_key("depotFile%s" % fnum):
 578            path =  commit["depotFile%s" % fnum]
 579            if not path.startswith(self.depotPath):
 580    #            if not self.silent:
 581    #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
 582                fnum = fnum + 1
 583                continue
 584
 585            file = {}
 586            file["path"] = path
 587            file["rev"] = commit["rev%s" % fnum]
 588            file["action"] = commit["action%s" % fnum]
 589            file["type"] = commit["type%s" % fnum]
 590            fnum = fnum + 1
 591
 592            relPath = path[len(self.depotPath):]
 593
 594            for branch in self.knownBranches.keys():
 595                if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
 596                    if branch not in branches:
 597                        branches[branch] = []
 598                    branches[branch].append(file)
 599
 600        return branches
 601
 602    def commit(self, details, files, branch, branchPrefix, parent = ""):
 603        epoch = details["time"]
 604        author = details["user"]
 605
 606        if self.verbose:
 607            print "commit into %s" % branch
 608
 609        self.gitStream.write("commit %s\n" % branch)
 610    #    gitStream.write("mark :%s\n" % details["change"])
 611        self.committedChanges.add(int(details["change"]))
 612        committer = ""
 613        if author not in self.users:
 614            self.getUserMapFromPerforceServer()
 615        if author in self.users:
 616            committer = "%s %s %s" % (self.users[author], epoch, self.tz)
 617        else:
 618            committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
 619
 620        self.gitStream.write("committer %s\n" % committer)
 621
 622        self.gitStream.write("data <<EOT\n")
 623        self.gitStream.write(details["desc"])
 624        self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
 625        self.gitStream.write("EOT\n\n")
 626
 627        if len(parent) > 0:
 628            if self.verbose:
 629                print "parent %s" % parent
 630            self.gitStream.write("from %s\n" % parent)
 631
 632        for file in files:
 633            path = file["path"]
 634            if not path.startswith(branchPrefix):
 635    #            if not silent:
 636    #                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
 637                continue
 638            rev = file["rev"]
 639            depotPath = path + "#" + rev
 640            relPath = path[len(branchPrefix):]
 641            action = file["action"]
 642
 643            if file["type"] == "apple":
 644                print "\nfile %s is a strange apple file that forks. Ignoring!" % path
 645                continue
 646
 647            if action == "delete":
 648                self.gitStream.write("D %s\n" % relPath)
 649            else:
 650                mode = 644
 651                if file["type"].startswith("x"):
 652                    mode = 755
 653
 654                data = self.p4File(depotPath)
 655
 656                if self.isWindows and file["type"].endswith("text"):
 657                    data = data.replace("\r\n", "\n")
 658
 659                self.gitStream.write("M %s inline %s\n" % (mode, relPath))
 660                self.gitStream.write("data %s\n" % len(data))
 661                self.gitStream.write(data)
 662                self.gitStream.write("\n")
 663
 664        self.gitStream.write("\n")
 665
 666        change = int(details["change"])
 667
 668        if self.labels.has_key(change):
 669            label = self.labels[change]
 670            labelDetails = label[0]
 671            labelRevisions = label[1]
 672            if self.verbose:
 673                print "Change %s is labelled %s" % (change, labelDetails)
 674
 675            files = p4CmdList("files %s...@%s" % (branchPrefix, change))
 676
 677            if len(files) == len(labelRevisions):
 678
 679                cleanedFiles = {}
 680                for info in files:
 681                    if info["action"] == "delete":
 682                        continue
 683                    cleanedFiles[info["depotFile"]] = info["rev"]
 684
 685                if cleanedFiles == labelRevisions:
 686                    self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
 687                    self.gitStream.write("from %s\n" % branch)
 688
 689                    owner = labelDetails["Owner"]
 690                    tagger = ""
 691                    if author in self.users:
 692                        tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
 693                    else:
 694                        tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
 695                    self.gitStream.write("tagger %s\n" % tagger)
 696                    self.gitStream.write("data <<EOT\n")
 697                    self.gitStream.write(labelDetails["Description"])
 698                    self.gitStream.write("EOT\n\n")
 699
 700                else:
 701                    if not self.silent:
 702                        print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
 703
 704            else:
 705                if not self.silent:
 706                    print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
 707
 708    def getUserMapFromPerforceServer(self):
 709        if self.userMapFromPerforceServer:
 710            return
 711        self.users = {}
 712
 713        for output in p4CmdList("users"):
 714            if not output.has_key("User"):
 715                continue
 716            self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
 717
 718        cache = open(gitdir + "/p4-usercache.txt", "wb")
 719        for user in self.users.keys():
 720            cache.write("%s\t%s\n" % (user, self.users[user]))
 721        cache.close();
 722        self.userMapFromPerforceServer = True
 723
 724    def loadUserMapFromCache(self):
 725        self.users = {}
 726        self.userMapFromPerforceServer = False
 727        try:
 728            cache = open(gitdir + "/p4-usercache.txt", "rb")
 729            lines = cache.readlines()
 730            cache.close()
 731            for line in lines:
 732                entry = line[:-1].split("\t")
 733                self.users[entry[0]] = entry[1]
 734        except IOError:
 735            self.getUserMapFromPerforceServer()
 736
 737    def getLabels(self):
 738        self.labels = {}
 739
 740        l = p4CmdList("labels %s..." % self.depotPath)
 741        if len(l) > 0 and not self.silent:
 742            print "Finding files belonging to labels in %s" % self.depotPath
 743
 744        for output in l:
 745            label = output["label"]
 746            revisions = {}
 747            newestChange = 0
 748            if self.verbose:
 749                print "Querying files for label %s" % label
 750            for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
 751                revisions[file["depotFile"]] = file["rev"]
 752                change = int(file["change"])
 753                if change > newestChange:
 754                    newestChange = change
 755
 756            self.labels[newestChange] = [output, revisions]
 757
 758        if self.verbose:
 759            print "Label changes: %s" % self.labels.keys()
 760
 761    def getBranchMapping(self):
 762        self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
 763
 764        for info in p4CmdList("branches"):
 765            details = p4Cmd("branch -o %s" % info["branch"])
 766            viewIdx = 0
 767            while details.has_key("View%s" % viewIdx):
 768                paths = details["View%s" % viewIdx].split(" ")
 769                viewIdx = viewIdx + 1
 770                # require standard //depot/foo/... //depot/bar/... mapping
 771                if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
 772                    continue
 773                source = paths[0]
 774                destination = paths[1]
 775                if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
 776                    source = source[len(self.depotPath):-4]
 777                    destination = destination[len(self.depotPath):-4]
 778                    if destination not in self.knownBranches:
 779                        self.knownBranches[destination] = source
 780                    if source not in self.knownBranches:
 781                        self.knownBranches[source] = source
 782
 783    def listExistingP4GitBranches(self):
 784        self.p4BranchesInGit = []
 785
 786        cmdline = "git rev-parse --symbolic "
 787        if self.importIntoRemotes:
 788            cmdline += " --remotes"
 789        else:
 790            cmdline += " --branches"
 791
 792        for line in mypopen(cmdline).readlines():
 793            if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
 794                continue
 795            if self.importIntoRemotes:
 796                # strip off p4
 797                branch = line[3:-1]
 798            else:
 799                branch = line[:-1]
 800            self.p4BranchesInGit.append(branch)
 801            self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
 802
 803    def createOrUpdateBranchesFromOrigin(self):
 804        if not self.silent:
 805            print "Creating/updating branch(es) in %s based on origin branch(es)" % self.refPrefix
 806
 807        for line in mypopen("git rev-parse --symbolic --remotes"):
 808            if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
 809                continue
 810
 811            headName = line[len("origin/"):-1]
 812            remoteHead = self.refPrefix + headName
 813            originHead = "origin/" + headName
 814
 815            [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead))
 816            if len(originPreviousDepotPath) == 0 or len(originP4Change) == 0:
 817                continue
 818
 819            update = False
 820            if not gitBranchExists(remoteHead):
 821                if self.verbose:
 822                    print "creating %s" % remoteHead
 823                update = True
 824            else:
 825                [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead))
 826                if len(p4Change) > 0:
 827                    if originPreviousDepotPath == p4PreviousDepotPath:
 828                        originP4Change = int(originP4Change)
 829                        p4Change = int(p4Change)
 830                        if originP4Change > p4Change:
 831                            print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead, originP4Change, remoteHead, p4Change)
 832                            update = True
 833                    else:
 834                        print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead, originPreviousDepotPath, remoteHead, p4PreviousDepotPath)
 835
 836            if update:
 837                system("git update-ref %s %s" % (remoteHead, originHead))
 838
 839    def run(self, args):
 840        self.depotPath = ""
 841        self.changeRange = ""
 842        self.initialParent = ""
 843        self.previousDepotPath = ""
 844        # map from branch depot path to parent branch
 845        self.knownBranches = {}
 846        self.initialParents = {}
 847
 848        if self.importIntoRemotes:
 849            self.refPrefix = "refs/remotes/p4/"
 850        else:
 851            self.refPrefix = "refs/heads/"
 852
 853        if self.syncWithOrigin:
 854            if gitBranchExists("origin"):
 855                if not self.silent:
 856                    print "Syncing with origin first by calling git fetch origin"
 857                system("git fetch origin")
 858
 859        createP4HeadRef = False;
 860
 861        if len(self.branch) == 0:
 862            self.branch = self.refPrefix + "master"
 863            if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
 864                system("git update-ref %s refs/heads/p4" % self.branch)
 865                system("git branch -D p4");
 866            # create it /after/ importing, when master exists
 867            if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
 868                createP4HeadRef = True
 869
 870        if len(args) == 0:
 871            self.createOrUpdateBranchesFromOrigin()
 872            self.listExistingP4GitBranches()
 873
 874            if len(self.p4BranchesInGit) > 1:
 875                if not self.silent:
 876                    print "Importing from/into multiple branches"
 877                self.detectBranches = True
 878
 879            if self.verbose:
 880                print "branches: %s" % self.p4BranchesInGit
 881
 882            p4Change = 0
 883            for branch in self.p4BranchesInGit:
 884                depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.refPrefix + branch))
 885
 886                if self.verbose:
 887                    print "path %s change %s" % (depotPath, change)
 888
 889                if len(depotPath) > 0 and len(change) > 0:
 890                    change = int(change) + 1
 891                    p4Change = max(p4Change, change)
 892
 893                    if len(self.previousDepotPath) == 0:
 894                        self.previousDepotPath = depotPath
 895                    else:
 896                        i = 0
 897                        l = min(len(self.previousDepotPath), len(depotPath))
 898                        while i < l and self.previousDepotPath[i] == depotPath[i]:
 899                            i = i + 1
 900                        self.previousDepotPath = self.previousDepotPath[:i]
 901
 902            if p4Change > 0:
 903                self.depotPath = self.previousDepotPath
 904                self.changeRange = "@%s,#head" % p4Change
 905                self.initialParent = parseRevision(self.branch)
 906                if not self.silent and not self.detectBranches:
 907                    print "Performing incremental import into %s git branch" % self.branch
 908
 909        if not self.branch.startswith("refs/"):
 910            self.branch = "refs/heads/" + self.branch
 911
 912        if len(self.depotPath) != 0:
 913            self.depotPath = self.depotPath[:-1]
 914
 915        if len(args) == 0 and len(self.depotPath) != 0:
 916            if not self.silent:
 917                print "Depot path: %s" % self.depotPath
 918        elif len(args) != 1:
 919            return False
 920        else:
 921            if len(self.depotPath) != 0 and self.depotPath != args[0]:
 922                print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
 923                sys.exit(1)
 924            self.depotPath = args[0]
 925
 926        self.revision = ""
 927        self.users = {}
 928
 929        if self.depotPath.find("@") != -1:
 930            atIdx = self.depotPath.index("@")
 931            self.changeRange = self.depotPath[atIdx:]
 932            if self.changeRange == "@all":
 933                self.changeRange = ""
 934            elif self.changeRange.find(",") == -1:
 935                self.revision = self.changeRange
 936                self.changeRange = ""
 937            self.depotPath = self.depotPath[0:atIdx]
 938        elif self.depotPath.find("#") != -1:
 939            hashIdx = self.depotPath.index("#")
 940            self.revision = self.depotPath[hashIdx:]
 941            self.depotPath = self.depotPath[0:hashIdx]
 942        elif len(self.previousDepotPath) == 0:
 943            self.revision = "#head"
 944
 945        if self.depotPath.endswith("..."):
 946            self.depotPath = self.depotPath[:-3]
 947
 948        if not self.depotPath.endswith("/"):
 949            self.depotPath += "/"
 950
 951        self.loadUserMapFromCache()
 952        self.labels = {}
 953        if self.detectLabels:
 954            self.getLabels();
 955
 956        if self.detectBranches:
 957            self.getBranchMapping();
 958            if self.verbose:
 959                print "p4-git branches: %s" % self.p4BranchesInGit
 960                print "initial parents: %s" % self.initialParents
 961            for b in self.p4BranchesInGit:
 962                if b != "master":
 963                    b = b[len(self.projectName):]
 964                self.createdBranches.add(b)
 965
 966        self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
 967
 968        importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
 969        self.gitOutput = importProcess.stdout
 970        self.gitStream = importProcess.stdin
 971        self.gitError = importProcess.stderr
 972
 973        if len(self.revision) > 0:
 974            print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
 975
 976            details = { "user" : "git perforce import user", "time" : int(time.time()) }
 977            details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
 978            details["change"] = self.revision
 979            newestRevision = 0
 980
 981            fileCnt = 0
 982            for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
 983                change = int(info["change"])
 984                if change > newestRevision:
 985                    newestRevision = change
 986
 987                if info["action"] == "delete":
 988                    # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
 989                    #fileCnt = fileCnt + 1
 990                    continue
 991
 992                for prop in [ "depotFile", "rev", "action", "type" ]:
 993                    details["%s%s" % (prop, fileCnt)] = info[prop]
 994
 995                fileCnt = fileCnt + 1
 996
 997            details["change"] = newestRevision
 998
 999            try:
1000                self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
1001            except IOError:
1002                print "IO error with git fast-import. Is your git version recent enough?"
1003                print self.gitError.read()
1004
1005        else:
1006            changes = []
1007
1008            if len(self.changesFile) > 0:
1009                output = open(self.changesFile).readlines()
1010                changeSet = Set()
1011                for line in output:
1012                    changeSet.add(int(line))
1013
1014                for change in changeSet:
1015                    changes.append(change)
1016
1017                changes.sort()
1018            else:
1019                if self.verbose:
1020                    print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
1021                output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
1022
1023                for line in output:
1024                    changeNum = line.split(" ")[1]
1025                    changes.append(changeNum)
1026
1027                changes.reverse()
1028
1029                if len(self.maxChanges) > 0:
1030                    changes = changes[0:min(int(self.maxChanges), len(changes))]
1031
1032            if len(changes) == 0:
1033                if not self.silent:
1034                    print "No changes to import!"
1035                return True
1036
1037            self.updatedBranches = set()
1038
1039            cnt = 1
1040            for change in changes:
1041                description = p4Cmd("describe %s" % change)
1042
1043                if not self.silent:
1044                    sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1045                    sys.stdout.flush()
1046                cnt = cnt + 1
1047
1048                try:
1049                    if self.detectBranches:
1050                        branches = self.splitFilesIntoBranches(description)
1051                        for branch in branches.keys():
1052                            branchPrefix = self.depotPath + branch + "/"
1053
1054                            parent = ""
1055
1056                            filesForCommit = branches[branch]
1057
1058                            if self.verbose:
1059                                print "branch is %s" % branch
1060
1061                            self.updatedBranches.add(branch)
1062
1063                            if branch not in self.createdBranches:
1064                                self.createdBranches.add(branch)
1065                                parent = self.knownBranches[branch]
1066                                if parent == branch:
1067                                    parent = ""
1068                                elif self.verbose:
1069                                    print "parent determined through known branches: %s" % parent
1070
1071                            # main branch? use master
1072                            if branch == "main":
1073                                branch = "master"
1074                            else:
1075                                branch = self.projectName + branch
1076
1077                            if parent == "main":
1078                                parent = "master"
1079                            elif len(parent) > 0:
1080                                parent = self.projectName + parent
1081
1082                            branch = self.refPrefix + branch
1083                            if len(parent) > 0:
1084                                parent = self.refPrefix + parent
1085
1086                            if self.verbose:
1087                                print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1088
1089                            if len(parent) == 0 and branch in self.initialParents:
1090                                parent = self.initialParents[branch]
1091                                del self.initialParents[branch]
1092
1093                            self.commit(description, filesForCommit, branch, branchPrefix, parent)
1094                    else:
1095                        files = self.extractFilesFromCommit(description)
1096                        self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1097                        self.initialParent = ""
1098                except IOError:
1099                    print self.gitError.read()
1100                    sys.exit(1)
1101
1102            if not self.silent:
1103                print ""
1104                if len(self.updatedBranches) > 0:
1105                    sys.stdout.write("Updated branches: ")
1106                    for b in self.updatedBranches:
1107                        sys.stdout.write("%s " % b)
1108                    sys.stdout.write("\n")
1109
1110
1111        self.gitStream.close()
1112        if importProcess.wait() != 0:
1113            die("fast-import failed: %s" % self.gitError.read())
1114        self.gitOutput.close()
1115        self.gitError.close()
1116
1117        if createP4HeadRef:
1118            system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1119
1120        return True
1121
1122class P4Rebase(Command):
1123    def __init__(self):
1124        Command.__init__(self)
1125        self.options = [ ]
1126        self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1127
1128    def run(self, args):
1129        sync = P4Sync()
1130        sync.run([])
1131        print "Rebasing the current branch"
1132        oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1133        system("git rebase p4")
1134        system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1135        return True
1136
1137class P4Clone(P4Sync):
1138    def __init__(self):
1139        P4Sync.__init__(self)
1140        self.description = "Creates a new git repository and imports from Perforce into it"
1141        self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1142        self.needsGit = False
1143
1144    def run(self, args):
1145        global gitdir
1146
1147        if len(args) < 1:
1148            return False
1149        depotPath = args[0]
1150        dir = ""
1151        if len(args) == 2:
1152            dir = args[1]
1153        elif len(args) > 2:
1154            return False
1155
1156        if not depotPath.startswith("//"):
1157            return False
1158
1159        if len(dir) == 0:
1160            dir = depotPath
1161            atPos = dir.rfind("@")
1162            if atPos != -1:
1163                dir = dir[0:atPos]
1164            hashPos = dir.rfind("#")
1165            if hashPos != -1:
1166                dir = dir[0:hashPos]
1167
1168            if dir.endswith("..."):
1169                dir = dir[:-3]
1170
1171            if dir.endswith("/"):
1172               dir = dir[:-1]
1173
1174            slashPos = dir.rfind("/")
1175            if slashPos != -1:
1176                dir = dir[slashPos + 1:]
1177
1178        print "Importing from %s into %s" % (depotPath, dir)
1179        os.makedirs(dir)
1180        os.chdir(dir)
1181        system("git init")
1182        gitdir = os.getcwd() + "/.git"
1183        if not P4Sync.run(self, [depotPath]):
1184            return False
1185        if self.branch != "master":
1186            if gitBranchExists("refs/remotes/p4/master"):
1187                system("git branch master refs/remotes/p4/master")
1188                system("git checkout -f")
1189            else:
1190                print "Could not detect main branch. No checkout/master branch created."
1191        return True
1192
1193class HelpFormatter(optparse.IndentedHelpFormatter):
1194    def __init__(self):
1195        optparse.IndentedHelpFormatter.__init__(self)
1196
1197    def format_description(self, description):
1198        if description:
1199            return description + "\n"
1200        else:
1201            return ""
1202
1203def printUsage(commands):
1204    print "usage: %s <command> [options]" % sys.argv[0]
1205    print ""
1206    print "valid commands: %s" % ", ".join(commands)
1207    print ""
1208    print "Try %s <command> --help for command specific help." % sys.argv[0]
1209    print ""
1210
1211commands = {
1212    "debug" : P4Debug(),
1213    "submit" : P4Submit(),
1214    "sync" : P4Sync(),
1215    "rebase" : P4Rebase(),
1216    "clone" : P4Clone(),
1217    "rollback" : P4RollBack()
1218}
1219
1220if len(sys.argv[1:]) == 0:
1221    printUsage(commands.keys())
1222    sys.exit(2)
1223
1224cmd = ""
1225cmdName = sys.argv[1]
1226try:
1227    cmd = commands[cmdName]
1228except KeyError:
1229    print "unknown command %s" % cmdName
1230    print ""
1231    printUsage(commands.keys())
1232    sys.exit(2)
1233
1234options = cmd.options
1235cmd.gitdir = gitdir
1236
1237args = sys.argv[2:]
1238
1239if len(options) > 0:
1240    options.append(optparse.make_option("--git-dir", dest="gitdir"))
1241
1242    parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1243                                   options,
1244                                   description = cmd.description,
1245                                   formatter = HelpFormatter())
1246
1247    (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1248
1249if cmd.needsGit:
1250    gitdir = cmd.gitdir
1251    if len(gitdir) == 0:
1252        gitdir = ".git"
1253        if not isValidGitDir(gitdir):
1254            gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1255            if os.path.exists(gitdir):
1256                cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1257                if len(cdup) > 0:
1258                    os.chdir(cdup);
1259
1260    if not isValidGitDir(gitdir):
1261        if isValidGitDir(gitdir + "/.git"):
1262            gitdir += "/.git"
1263        else:
1264            die("fatal: cannot locate git repository at %s" % gitdir)
1265
1266    os.environ["GIT_DIR"] = gitdir
1267
1268if not cmd.run(args):
1269    parser.print_help()
1270