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