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