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