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