beb6529b44dcd91ac96929a46afc61e5058a90aa
   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        self.listExistingP4GitBranches()
 734        if len(self.p4BranchesInGit) > 1 and not self.silent:
 735            print "Importing from/into multiple branches"
 736            self.detectBranches = True
 737
 738        if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self.detectBranches:
 739            ### needs to be ported to multi branch import
 740
 741            print "Syncing with origin first as requested by calling git fetch origin"
 742            system("git fetch origin")
 743            [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
 744            [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
 745            if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
 746                if originPreviousDepotPath == p4PreviousDepotPath:
 747                    originP4Change = int(originP4Change)
 748                    p4Change = int(p4Change)
 749                    if originP4Change > p4Change:
 750                        print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
 751                        system("git update-ref refs/remotes/p4/master origin");
 752                else:
 753                    print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
 754
 755        if len(self.branch) == 0:
 756            self.branch = "refs/remotes/p4/master"
 757            if gitBranchExists("refs/heads/p4"):
 758                system("git update-ref %s refs/heads/p4" % self.branch)
 759                system("git branch -D p4");
 760            if not gitBranchExists("refs/remotes/p4/HEAD"):
 761                system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch)
 762
 763        if len(args) == 0:
 764            if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
 765                ### needs to be ported to multi branch import
 766                if not self.silent:
 767                    print "Creating %s branch in git repository based on origin" % self.branch
 768                branch = self.branch
 769                if not branch.startswith("refs"):
 770                    branch = "refs/heads/" + branch
 771                system("git update-ref %s origin" % branch)
 772
 773            if self.verbose:
 774                print "branches: %s" % self.p4BranchesInGit
 775
 776            p4Change = 0
 777            for branch in self.p4BranchesInGit:
 778                depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch))
 779
 780                if self.verbose:
 781                    print "path %s change %s" % (depotPath, change)
 782
 783                if len(depotPath) > 0 and len(change) > 0:
 784                    change = int(change) + 1
 785                    p4Change = max(p4Change, change)
 786
 787                    if len(self.previousDepotPath) == 0:
 788                        self.previousDepotPath = depotPath
 789                    else:
 790                        i = 0
 791                        l = min(len(self.previousDepotPath), len(depotPath))
 792                        while i < l and self.previousDepotPath[i] == depotPath[i]:
 793                            i = i + 1
 794                        self.previousDepotPath = self.previousDepotPath[:i]
 795
 796            if p4Change > 0:
 797                self.depotPath = self.previousDepotPath
 798                self.changeRange = "@%s,#head" % p4Change
 799                self.initialParent = parseRevision(self.branch)
 800                if not self.silent and not self.detectBranches:
 801                    print "Performing incremental import into %s git branch" % self.branch
 802
 803        if not self.branch.startswith("refs/"):
 804            self.branch = "refs/heads/" + self.branch
 805
 806        if len(self.depotPath) != 0:
 807            self.depotPath = self.depotPath[:-1]
 808
 809        if len(args) == 0 and len(self.depotPath) != 0:
 810            if not self.silent:
 811                print "Depot path: %s" % self.depotPath
 812        elif len(args) != 1:
 813            return False
 814        else:
 815            if len(self.depotPath) != 0 and self.depotPath != args[0]:
 816                print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
 817                sys.exit(1)
 818            self.depotPath = args[0]
 819
 820        self.revision = ""
 821        self.users = {}
 822
 823        if self.depotPath.find("@") != -1:
 824            atIdx = self.depotPath.index("@")
 825            self.changeRange = self.depotPath[atIdx:]
 826            if self.changeRange == "@all":
 827                self.changeRange = ""
 828            elif self.changeRange.find(",") == -1:
 829                self.revision = self.changeRange
 830                self.changeRange = ""
 831            self.depotPath = self.depotPath[0:atIdx]
 832        elif self.depotPath.find("#") != -1:
 833            hashIdx = self.depotPath.index("#")
 834            self.revision = self.depotPath[hashIdx:]
 835            self.depotPath = self.depotPath[0:hashIdx]
 836        elif len(self.previousDepotPath) == 0:
 837            self.revision = "#head"
 838
 839        if self.depotPath.endswith("..."):
 840            self.depotPath = self.depotPath[:-3]
 841
 842        if not self.depotPath.endswith("/"):
 843            self.depotPath += "/"
 844
 845        self.loadUserMapFromCache()
 846        self.labels = {}
 847        if self.detectLabels:
 848            self.getLabels();
 849
 850        if self.detectBranches:
 851            self.getBranchMapping();
 852            if self.verbose:
 853                print "p4-git branches: %s" % self.p4BranchesInGit
 854                print "initial parents: %s" % self.initialParents
 855            for b in self.p4BranchesInGit:
 856                if b != "master":
 857                    b = b[len(self.projectName):]
 858                self.createdBranches.add(b)
 859
 860        self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
 861
 862        importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
 863        self.gitOutput = importProcess.stdout
 864        self.gitStream = importProcess.stdin
 865        self.gitError = importProcess.stderr
 866
 867        if len(self.revision) > 0:
 868            print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
 869
 870            details = { "user" : "git perforce import user", "time" : int(time.time()) }
 871            details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
 872            details["change"] = self.revision
 873            newestRevision = 0
 874
 875            fileCnt = 0
 876            for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
 877                change = int(info["change"])
 878                if change > newestRevision:
 879                    newestRevision = change
 880
 881                if info["action"] == "delete":
 882                    # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
 883                    #fileCnt = fileCnt + 1
 884                    continue
 885
 886                for prop in [ "depotFile", "rev", "action", "type" ]:
 887                    details["%s%s" % (prop, fileCnt)] = info[prop]
 888
 889                fileCnt = fileCnt + 1
 890
 891            details["change"] = newestRevision
 892
 893            try:
 894                self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
 895            except IOError:
 896                print "IO error with git fast-import. Is your git version recent enough?"
 897                print self.gitError.read()
 898
 899        else:
 900            changes = []
 901
 902            if len(self.changesFile) > 0:
 903                output = open(self.changesFile).readlines()
 904                changeSet = Set()
 905                for line in output:
 906                    changeSet.add(int(line))
 907
 908                for change in changeSet:
 909                    changes.append(change)
 910
 911                changes.sort()
 912            else:
 913                if self.verbose:
 914                    print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
 915                output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
 916
 917                for line in output:
 918                    changeNum = line.split(" ")[1]
 919                    changes.append(changeNum)
 920
 921                changes.reverse()
 922
 923            if len(changes) == 0:
 924                if not self.silent:
 925                    print "No changes to import!"
 926                return True
 927
 928            self.updatedBranches = set()
 929
 930            cnt = 1
 931            for change in changes:
 932                description = p4Cmd("describe %s" % change)
 933
 934                if not self.silent:
 935                    sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
 936                    sys.stdout.flush()
 937                cnt = cnt + 1
 938
 939                try:
 940                    if self.detectBranches:
 941                        branches = self.splitFilesIntoBranches(description)
 942                        for branch in branches.keys():
 943                            branchPrefix = self.depotPath + branch + "/"
 944
 945                            parent = ""
 946
 947                            filesForCommit = branches[branch]
 948
 949                            if self.verbose:
 950                                print "branch is %s" % branch
 951
 952                            self.updatedBranches.add(branch)
 953
 954                            if branch not in self.createdBranches:
 955                                self.createdBranches.add(branch)
 956                                parent = self.knownBranches[branch]
 957                                if parent == branch:
 958                                    parent = ""
 959                                elif self.verbose:
 960                                    print "parent determined through known branches: %s" % parent
 961
 962                            # main branch? use master
 963                            if branch == "main":
 964                                branch = "master"
 965                            else:
 966                                branch = self.projectName + branch
 967
 968                            if parent == "main":
 969                                parent = "master"
 970                            elif len(parent) > 0:
 971                                parent = self.projectName + parent
 972
 973                            branch = "refs/remotes/p4/" + branch
 974                            if len(parent) > 0:
 975                                parent = "refs/remotes/p4/" + parent
 976
 977                            if self.verbose:
 978                                print "looking for initial parent for %s; current parent is %s" % (branch, parent)
 979
 980                            if len(parent) == 0 and branch in self.initialParents:
 981                                parent = self.initialParents[branch]
 982                                del self.initialParents[branch]
 983
 984                            self.commit(description, filesForCommit, branch, branchPrefix, parent)
 985                    else:
 986                        files = self.extractFilesFromCommit(description)
 987                        self.commit(description, files, self.branch, self.depotPath, self.initialParent)
 988                        self.initialParent = ""
 989                except IOError:
 990                    print self.gitError.read()
 991                    sys.exit(1)
 992
 993            if not self.silent:
 994                print ""
 995                if len(self.updatedBranches) > 0:
 996                    sys.stdout.write("Updated branches: ")
 997                    for b in self.updatedBranches:
 998                        sys.stdout.write("%s " % b)
 999                    sys.stdout.write("\n")
1000
1001
1002        self.gitStream.close()
1003        if importProcess.wait() != 0:
1004            die("fast-import failed: %s" % self.gitError.read())
1005        self.gitOutput.close()
1006        self.gitError.close()
1007
1008        return True
1009
1010class P4Rebase(Command):
1011    def __init__(self):
1012        Command.__init__(self)
1013        self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
1014        self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1015        self.syncWithOrigin = False
1016
1017    def run(self, args):
1018        sync = P4Sync()
1019        sync.syncWithOrigin = self.syncWithOrigin
1020        sync.run([])
1021        print "Rebasing the current branch"
1022        oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1023        system("git rebase p4")
1024        system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1025        return True
1026
1027class P4Clone(P4Sync):
1028    def __init__(self):
1029        P4Sync.__init__(self)
1030        self.description = "Creates a new git repository and imports from Perforce into it"
1031        self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1032        self.needsGit = False
1033
1034    def run(self, args):
1035        global gitdir
1036
1037        if len(args) < 1:
1038            return False
1039        depotPath = args[0]
1040        dir = ""
1041        if len(args) == 2:
1042            dir = args[1]
1043        elif len(args) > 2:
1044            return False
1045
1046        if not depotPath.startswith("//"):
1047            return False
1048
1049        if len(dir) == 0:
1050            dir = depotPath
1051            atPos = dir.rfind("@")
1052            if atPos != -1:
1053                dir = dir[0:atPos]
1054            hashPos = dir.rfind("#")
1055            if hashPos != -1:
1056                dir = dir[0:hashPos]
1057
1058            if dir.endswith("..."):
1059                dir = dir[:-3]
1060
1061            if dir.endswith("/"):
1062               dir = dir[:-1]
1063
1064            slashPos = dir.rfind("/")
1065            if slashPos != -1:
1066                dir = dir[slashPos + 1:]
1067
1068        print "Importing from %s into %s" % (depotPath, dir)
1069        os.makedirs(dir)
1070        os.chdir(dir)
1071        system("git init")
1072        gitdir = os.getcwd() + "/.git"
1073        if not P4Sync.run(self, [depotPath]):
1074            return False
1075        if self.branch != "master":
1076            if gitBranchExists("refs/remotes/p4/master"):
1077                system("git branch master refs/remotes/p4/master")
1078                system("git checkout -f")
1079            else:
1080                print "Could not detect main branch. No checkout/master branch created."
1081        return True
1082
1083class HelpFormatter(optparse.IndentedHelpFormatter):
1084    def __init__(self):
1085        optparse.IndentedHelpFormatter.__init__(self)
1086
1087    def format_description(self, description):
1088        if description:
1089            return description + "\n"
1090        else:
1091            return ""
1092
1093def printUsage(commands):
1094    print "usage: %s <command> [options]" % sys.argv[0]
1095    print ""
1096    print "valid commands: %s" % ", ".join(commands)
1097    print ""
1098    print "Try %s <command> --help for command specific help." % sys.argv[0]
1099    print ""
1100
1101commands = {
1102    "debug" : P4Debug(),
1103    "submit" : P4Submit(),
1104    "sync" : P4Sync(),
1105    "rebase" : P4Rebase(),
1106    "clone" : P4Clone()
1107}
1108
1109if len(sys.argv[1:]) == 0:
1110    printUsage(commands.keys())
1111    sys.exit(2)
1112
1113cmd = ""
1114cmdName = sys.argv[1]
1115try:
1116    cmd = commands[cmdName]
1117except KeyError:
1118    print "unknown command %s" % cmdName
1119    print ""
1120    printUsage(commands.keys())
1121    sys.exit(2)
1122
1123options = cmd.options
1124cmd.gitdir = gitdir
1125
1126args = sys.argv[2:]
1127
1128if len(options) > 0:
1129    options.append(optparse.make_option("--git-dir", dest="gitdir"))
1130
1131    parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1132                                   options,
1133                                   description = cmd.description,
1134                                   formatter = HelpFormatter())
1135
1136    (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1137
1138if cmd.needsGit:
1139    gitdir = cmd.gitdir
1140    if len(gitdir) == 0:
1141        gitdir = ".git"
1142        if not isValidGitDir(gitdir):
1143            gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1144            if os.path.exists(gitdir):
1145                cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1146                if len(cdup) > 0:
1147                    os.chdir(cdup);
1148
1149    if not isValidGitDir(gitdir):
1150        if isValidGitDir(gitdir + "/.git"):
1151            gitdir += "/.git"
1152        else:
1153            die("fatal: cannot locate git repository at %s" % gitdir)
1154
1155    os.environ["GIT_DIR"] = gitdir
1156
1157if not cmd.run(args):
1158    parser.print_help()
1159