contrib / fast-import / git-p4on commit Detect with git-p4 submit --direct when there are no changes in the working directory (cbf5efa)
   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            if len(self.diffStatus) == 0:
 390                print "No changes in working directory to submit."
 391                return True
 392            patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
 393            self.diffFile = gitdir + "/p4-git-diff"
 394            f = open(self.diffFile, "wb")
 395            f.write(patch)
 396            f.close();
 397
 398        os.chdir(self.clientPath)
 399        response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
 400        if response == "y" or response == "yes":
 401            system("p4 sync ...")
 402
 403        if len(self.origin) == 0:
 404            if gitBranchExists("p4"):
 405                self.origin = "p4"
 406            else:
 407                self.origin = "origin"
 408
 409        if self.reset:
 410            self.firstTime = True
 411
 412        if len(self.substFile) > 0:
 413            for line in open(self.substFile, "r").readlines():
 414                tokens = line[:-1].split("=")
 415                self.logSubstitutions[tokens[0]] = tokens[1]
 416
 417        self.check()
 418        self.configFile = gitdir + "/p4-git-sync.cfg"
 419        self.config = shelve.open(self.configFile, writeback=True)
 420
 421        if self.firstTime:
 422            self.start()
 423
 424        commits = self.config.get("commits", [])
 425
 426        while len(commits) > 0:
 427            self.firstTime = False
 428            commit = commits[0]
 429            commits = commits[1:]
 430            self.config["commits"] = commits
 431            self.apply(commit)
 432            if not self.interactive:
 433                break
 434
 435        self.config.close()
 436
 437        if self.directSubmit:
 438            os.remove(self.diffFile)
 439
 440        if len(commits) == 0:
 441            if self.firstTime:
 442                print "No changes found to apply between %s and current HEAD" % self.origin
 443            else:
 444                print "All changes applied!"
 445                response = ""
 446                os.chdir(oldWorkingDirectory)
 447
 448                if self.directSubmit:
 449                    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 ")
 450                    if response == "y" or response == "yes":
 451                        system("git reset --hard")
 452
 453                if len(response) == 0:
 454                    response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
 455                if response == "y" or response == "yes":
 456                    rebase = P4Rebase()
 457                    rebase.run([])
 458            os.remove(self.configFile)
 459
 460        return True
 461
 462class P4Sync(Command):
 463    def __init__(self):
 464        Command.__init__(self)
 465        self.options = [
 466                optparse.make_option("--branch", dest="branch"),
 467                optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
 468                optparse.make_option("--changesfile", dest="changesFile"),
 469                optparse.make_option("--silent", dest="silent", action="store_true"),
 470                optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
 471                optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
 472                optparse.make_option("--verbose", dest="verbose", action="store_true")
 473        ]
 474        self.description = """Imports from Perforce into a git repository.\n
 475    example:
 476    //depot/my/project/ -- to import the current head
 477    //depot/my/project/@all -- to import everything
 478    //depot/my/project/@1,6 -- to import only from revision 1 to 6
 479
 480    (a ... is not needed in the path p4 specification, it's added implicitly)"""
 481
 482        self.usage += " //depot/path[@revRange]"
 483
 484        self.silent = False
 485        self.createdBranches = Set()
 486        self.committedChanges = Set()
 487        self.branch = ""
 488        self.detectBranches = False
 489        self.detectLabels = False
 490        self.changesFile = ""
 491        self.syncWithOrigin = False
 492        self.verbose = False
 493
 494    def p4File(self, depotPath):
 495        return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
 496
 497    def extractFilesFromCommit(self, commit):
 498        files = []
 499        fnum = 0
 500        while commit.has_key("depotFile%s" % fnum):
 501            path =  commit["depotFile%s" % fnum]
 502            if not path.startswith(self.depotPath):
 503    #            if not self.silent:
 504    #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
 505                fnum = fnum + 1
 506                continue
 507
 508            file = {}
 509            file["path"] = path
 510            file["rev"] = commit["rev%s" % fnum]
 511            file["action"] = commit["action%s" % fnum]
 512            file["type"] = commit["type%s" % fnum]
 513            files.append(file)
 514            fnum = fnum + 1
 515        return files
 516
 517    def splitFilesIntoBranches(self, commit):
 518        branches = {}
 519
 520        fnum = 0
 521        while commit.has_key("depotFile%s" % fnum):
 522            path =  commit["depotFile%s" % fnum]
 523            if not path.startswith(self.depotPath):
 524    #            if not self.silent:
 525    #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
 526                fnum = fnum + 1
 527                continue
 528
 529            file = {}
 530            file["path"] = path
 531            file["rev"] = commit["rev%s" % fnum]
 532            file["action"] = commit["action%s" % fnum]
 533            file["type"] = commit["type%s" % fnum]
 534            fnum = fnum + 1
 535
 536            relPath = path[len(self.depotPath):]
 537
 538            for branch in self.knownBranches.keys():
 539                if relPath.startswith(branch):
 540                    if branch not in branches:
 541                        branches[branch] = []
 542                    branches[branch].append(file)
 543
 544        return branches
 545
 546    def commit(self, details, files, branch, branchPrefix, parent = ""):
 547        epoch = details["time"]
 548        author = details["user"]
 549
 550        if self.verbose:
 551            print "commit into %s" % branch
 552
 553        self.gitStream.write("commit %s\n" % branch)
 554    #    gitStream.write("mark :%s\n" % details["change"])
 555        self.committedChanges.add(int(details["change"]))
 556        committer = ""
 557        if author not in self.users:
 558            self.getUserMapFromPerforceServer()
 559        if author in self.users:
 560            committer = "%s %s %s" % (self.users[author], epoch, self.tz)
 561        else:
 562            committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
 563
 564        self.gitStream.write("committer %s\n" % committer)
 565
 566        self.gitStream.write("data <<EOT\n")
 567        self.gitStream.write(details["desc"])
 568        self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
 569        self.gitStream.write("EOT\n\n")
 570
 571        if len(parent) > 0:
 572            if self.verbose:
 573                print "parent %s" % parent
 574            self.gitStream.write("from %s\n" % parent)
 575
 576        for file in files:
 577            path = file["path"]
 578            if not path.startswith(branchPrefix):
 579    #            if not silent:
 580    #                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
 581                continue
 582            rev = file["rev"]
 583            depotPath = path + "#" + rev
 584            relPath = path[len(branchPrefix):]
 585            action = file["action"]
 586
 587            if file["type"] == "apple":
 588                print "\nfile %s is a strange apple file that forks. Ignoring!" % path
 589                continue
 590
 591            if action == "delete":
 592                self.gitStream.write("D %s\n" % relPath)
 593            else:
 594                mode = 644
 595                if file["type"].startswith("x"):
 596                    mode = 755
 597
 598                data = self.p4File(depotPath)
 599
 600                self.gitStream.write("M %s inline %s\n" % (mode, relPath))
 601                self.gitStream.write("data %s\n" % len(data))
 602                self.gitStream.write(data)
 603                self.gitStream.write("\n")
 604
 605        self.gitStream.write("\n")
 606
 607        change = int(details["change"])
 608
 609        if self.labels.has_key(change):
 610            label = self.labels[change]
 611            labelDetails = label[0]
 612            labelRevisions = label[1]
 613            if self.verbose:
 614                print "Change %s is labelled %s" % (change, labelDetails)
 615
 616            files = p4CmdList("files %s...@%s" % (branchPrefix, change))
 617
 618            if len(files) == len(labelRevisions):
 619
 620                cleanedFiles = {}
 621                for info in files:
 622                    if info["action"] == "delete":
 623                        continue
 624                    cleanedFiles[info["depotFile"]] = info["rev"]
 625
 626                if cleanedFiles == labelRevisions:
 627                    self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
 628                    self.gitStream.write("from %s\n" % branch)
 629
 630                    owner = labelDetails["Owner"]
 631                    tagger = ""
 632                    if author in self.users:
 633                        tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
 634                    else:
 635                        tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
 636                    self.gitStream.write("tagger %s\n" % tagger)
 637                    self.gitStream.write("data <<EOT\n")
 638                    self.gitStream.write(labelDetails["Description"])
 639                    self.gitStream.write("EOT\n\n")
 640
 641                else:
 642                    if not self.silent:
 643                        print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
 644
 645            else:
 646                if not self.silent:
 647                    print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
 648
 649    def getUserMapFromPerforceServer(self):
 650        self.users = {}
 651
 652        for output in p4CmdList("users"):
 653            if not output.has_key("User"):
 654                continue
 655            self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
 656
 657        cache = open(gitdir + "/p4-usercache.txt", "wb")
 658        for user in self.users.keys():
 659            cache.write("%s\t%s\n" % (user, self.users[user]))
 660        cache.close();
 661
 662    def loadUserMapFromCache(self):
 663        self.users = {}
 664        try:
 665            cache = open(gitdir + "/p4-usercache.txt", "rb")
 666            lines = cache.readlines()
 667            cache.close()
 668            for line in lines:
 669                entry = line[:-1].split("\t")
 670                self.users[entry[0]] = entry[1]
 671        except IOError:
 672            self.getUserMapFromPerforceServer()
 673
 674    def getLabels(self):
 675        self.labels = {}
 676
 677        l = p4CmdList("labels %s..." % self.depotPath)
 678        if len(l) > 0 and not self.silent:
 679            print "Finding files belonging to labels in %s" % self.depotPath
 680
 681        for output in l:
 682            label = output["label"]
 683            revisions = {}
 684            newestChange = 0
 685            if self.verbose:
 686                print "Querying files for label %s" % label
 687            for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
 688                revisions[file["depotFile"]] = file["rev"]
 689                change = int(file["change"])
 690                if change > newestChange:
 691                    newestChange = change
 692
 693            self.labels[newestChange] = [output, revisions]
 694
 695        if self.verbose:
 696            print "Label changes: %s" % self.labels.keys()
 697
 698    def getBranchMapping(self):
 699        self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
 700
 701        for info in p4CmdList("branches"):
 702            details = p4Cmd("branch -o %s" % info["branch"])
 703            viewIdx = 0
 704            while details.has_key("View%s" % viewIdx):
 705                paths = details["View%s" % viewIdx].split(" ")
 706                viewIdx = viewIdx + 1
 707                # require standard //depot/foo/... //depot/bar/... mapping
 708                if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
 709                    continue
 710                source = paths[0]
 711                destination = paths[1]
 712                if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
 713                    source = source[len(self.depotPath):-4]
 714                    destination = destination[len(self.depotPath):-4]
 715                    if destination not in self.knownBranches:
 716                        self.knownBranches[destination] = source
 717                    if source not in self.knownBranches:
 718                        self.knownBranches[source] = source
 719
 720    def listExistingP4GitBranches(self):
 721        self.p4BranchesInGit = []
 722
 723        for line in mypopen("git rev-parse --symbolic --remotes").readlines():
 724            if line.startswith("p4/") and line != "p4/HEAD\n":
 725                branch = line[3:-1]
 726                self.p4BranchesInGit.append(branch)
 727                self.initialParents["refs/remotes/p4/" + branch] = parseRevision(line[:-1])
 728
 729    def run(self, args):
 730        self.depotPath = ""
 731        self.changeRange = ""
 732        self.initialParent = ""
 733        self.previousDepotPath = ""
 734        # map from branch depot path to parent branch
 735        self.knownBranches = {}
 736        self.initialParents = {}
 737
 738        createP4HeadRef = False;
 739
 740        if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self.detectBranches:
 741            ### needs to be ported to multi branch import
 742
 743            print "Syncing with origin first as requested by calling git fetch origin"
 744            system("git fetch origin")
 745            [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
 746            [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
 747            if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
 748                if originPreviousDepotPath == p4PreviousDepotPath:
 749                    originP4Change = int(originP4Change)
 750                    p4Change = int(p4Change)
 751                    if originP4Change > p4Change:
 752                        print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
 753                        system("git update-ref refs/remotes/p4/master origin");
 754                else:
 755                    print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
 756
 757        if len(self.branch) == 0:
 758            self.branch = "refs/remotes/p4/master"
 759            if gitBranchExists("refs/heads/p4"):
 760                system("git update-ref %s refs/heads/p4" % self.branch)
 761                system("git branch -D p4");
 762            # create it /after/ importing, when master exists
 763            if not gitBranchExists("refs/remotes/p4/HEAD"):
 764                createP4HeadRef = True
 765
 766        # this needs to be called after the conversion from heads/p4 to remotes/p4/master
 767        self.listExistingP4GitBranches()
 768        if len(self.p4BranchesInGit) > 1 and not self.silent:
 769            print "Importing from/into multiple branches"
 770            self.detectBranches = True
 771
 772        if len(args) == 0:
 773            if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
 774                ### needs to be ported to multi branch import
 775                if not self.silent:
 776                    print "Creating %s branch in git repository based on origin" % self.branch
 777                branch = self.branch
 778                if not branch.startswith("refs"):
 779                    branch = "refs/heads/" + branch
 780                system("git update-ref %s origin" % branch)
 781
 782            if self.verbose:
 783                print "branches: %s" % self.p4BranchesInGit
 784
 785            p4Change = 0
 786            for branch in self.p4BranchesInGit:
 787                depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch))
 788
 789                if self.verbose:
 790                    print "path %s change %s" % (depotPath, change)
 791
 792                if len(depotPath) > 0 and len(change) > 0:
 793                    change = int(change) + 1
 794                    p4Change = max(p4Change, change)
 795
 796                    if len(self.previousDepotPath) == 0:
 797                        self.previousDepotPath = depotPath
 798                    else:
 799                        i = 0
 800                        l = min(len(self.previousDepotPath), len(depotPath))
 801                        while i < l and self.previousDepotPath[i] == depotPath[i]:
 802                            i = i + 1
 803                        self.previousDepotPath = self.previousDepotPath[:i]
 804
 805            if p4Change > 0:
 806                self.depotPath = self.previousDepotPath
 807                self.changeRange = "@%s,#head" % p4Change
 808                self.initialParent = parseRevision(self.branch)
 809                if not self.silent and not self.detectBranches:
 810                    print "Performing incremental import into %s git branch" % self.branch
 811
 812        if not self.branch.startswith("refs/"):
 813            self.branch = "refs/heads/" + self.branch
 814
 815        if len(self.depotPath) != 0:
 816            self.depotPath = self.depotPath[:-1]
 817
 818        if len(args) == 0 and len(self.depotPath) != 0:
 819            if not self.silent:
 820                print "Depot path: %s" % self.depotPath
 821        elif len(args) != 1:
 822            return False
 823        else:
 824            if len(self.depotPath) != 0 and self.depotPath != args[0]:
 825                print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
 826                sys.exit(1)
 827            self.depotPath = args[0]
 828
 829        self.revision = ""
 830        self.users = {}
 831
 832        if self.depotPath.find("@") != -1:
 833            atIdx = self.depotPath.index("@")
 834            self.changeRange = self.depotPath[atIdx:]
 835            if self.changeRange == "@all":
 836                self.changeRange = ""
 837            elif self.changeRange.find(",") == -1:
 838                self.revision = self.changeRange
 839                self.changeRange = ""
 840            self.depotPath = self.depotPath[0:atIdx]
 841        elif self.depotPath.find("#") != -1:
 842            hashIdx = self.depotPath.index("#")
 843            self.revision = self.depotPath[hashIdx:]
 844            self.depotPath = self.depotPath[0:hashIdx]
 845        elif len(self.previousDepotPath) == 0:
 846            self.revision = "#head"
 847
 848        if self.depotPath.endswith("..."):
 849            self.depotPath = self.depotPath[:-3]
 850
 851        if not self.depotPath.endswith("/"):
 852            self.depotPath += "/"
 853
 854        self.loadUserMapFromCache()
 855        self.labels = {}
 856        if self.detectLabels:
 857            self.getLabels();
 858
 859        if self.detectBranches:
 860            self.getBranchMapping();
 861            if self.verbose:
 862                print "p4-git branches: %s" % self.p4BranchesInGit
 863                print "initial parents: %s" % self.initialParents
 864            for b in self.p4BranchesInGit:
 865                if b != "master":
 866                    b = b[len(self.projectName):]
 867                self.createdBranches.add(b)
 868
 869        self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
 870
 871        importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
 872        self.gitOutput = importProcess.stdout
 873        self.gitStream = importProcess.stdin
 874        self.gitError = importProcess.stderr
 875
 876        if len(self.revision) > 0:
 877            print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
 878
 879            details = { "user" : "git perforce import user", "time" : int(time.time()) }
 880            details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
 881            details["change"] = self.revision
 882            newestRevision = 0
 883
 884            fileCnt = 0
 885            for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
 886                change = int(info["change"])
 887                if change > newestRevision:
 888                    newestRevision = change
 889
 890                if info["action"] == "delete":
 891                    # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
 892                    #fileCnt = fileCnt + 1
 893                    continue
 894
 895                for prop in [ "depotFile", "rev", "action", "type" ]:
 896                    details["%s%s" % (prop, fileCnt)] = info[prop]
 897
 898                fileCnt = fileCnt + 1
 899
 900            details["change"] = newestRevision
 901
 902            try:
 903                self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
 904            except IOError:
 905                print "IO error with git fast-import. Is your git version recent enough?"
 906                print self.gitError.read()
 907
 908        else:
 909            changes = []
 910
 911            if len(self.changesFile) > 0:
 912                output = open(self.changesFile).readlines()
 913                changeSet = Set()
 914                for line in output:
 915                    changeSet.add(int(line))
 916
 917                for change in changeSet:
 918                    changes.append(change)
 919
 920                changes.sort()
 921            else:
 922                if self.verbose:
 923                    print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
 924                output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
 925
 926                for line in output:
 927                    changeNum = line.split(" ")[1]
 928                    changes.append(changeNum)
 929
 930                changes.reverse()
 931
 932            if len(changes) == 0:
 933                if not self.silent:
 934                    print "No changes to import!"
 935                return True
 936
 937            self.updatedBranches = set()
 938
 939            cnt = 1
 940            for change in changes:
 941                description = p4Cmd("describe %s" % change)
 942
 943                if not self.silent:
 944                    sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
 945                    sys.stdout.flush()
 946                cnt = cnt + 1
 947
 948                try:
 949                    if self.detectBranches:
 950                        branches = self.splitFilesIntoBranches(description)
 951                        for branch in branches.keys():
 952                            branchPrefix = self.depotPath + branch + "/"
 953
 954                            parent = ""
 955
 956                            filesForCommit = branches[branch]
 957
 958                            if self.verbose:
 959                                print "branch is %s" % branch
 960
 961                            self.updatedBranches.add(branch)
 962
 963                            if branch not in self.createdBranches:
 964                                self.createdBranches.add(branch)
 965                                parent = self.knownBranches[branch]
 966                                if parent == branch:
 967                                    parent = ""
 968                                elif self.verbose:
 969                                    print "parent determined through known branches: %s" % parent
 970
 971                            # main branch? use master
 972                            if branch == "main":
 973                                branch = "master"
 974                            else:
 975                                branch = self.projectName + branch
 976
 977                            if parent == "main":
 978                                parent = "master"
 979                            elif len(parent) > 0:
 980                                parent = self.projectName + parent
 981
 982                            branch = "refs/remotes/p4/" + branch
 983                            if len(parent) > 0:
 984                                parent = "refs/remotes/p4/" + parent
 985
 986                            if self.verbose:
 987                                print "looking for initial parent for %s; current parent is %s" % (branch, parent)
 988
 989                            if len(parent) == 0 and branch in self.initialParents:
 990                                parent = self.initialParents[branch]
 991                                del self.initialParents[branch]
 992
 993                            self.commit(description, filesForCommit, branch, branchPrefix, parent)
 994                    else:
 995                        files = self.extractFilesFromCommit(description)
 996                        self.commit(description, files, self.branch, self.depotPath, self.initialParent)
 997                        self.initialParent = ""
 998                except IOError:
 999                    print self.gitError.read()
1000                    sys.exit(1)
1001
1002            if not self.silent:
1003                print ""
1004                if len(self.updatedBranches) > 0:
1005                    sys.stdout.write("Updated branches: ")
1006                    for b in self.updatedBranches:
1007                        sys.stdout.write("%s " % b)
1008                    sys.stdout.write("\n")
1009
1010
1011        self.gitStream.close()
1012        if importProcess.wait() != 0:
1013            die("fast-import failed: %s" % self.gitError.read())
1014        self.gitOutput.close()
1015        self.gitError.close()
1016
1017        if createP4HeadRef:
1018            system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch)
1019
1020        return True
1021
1022class P4Rebase(Command):
1023    def __init__(self):
1024        Command.__init__(self)
1025        self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
1026        self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1027        self.syncWithOrigin = False
1028
1029    def run(self, args):
1030        sync = P4Sync()
1031        sync.syncWithOrigin = self.syncWithOrigin
1032        sync.run([])
1033        print "Rebasing the current branch"
1034        oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1035        system("git rebase p4")
1036        system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1037        return True
1038
1039class P4Clone(P4Sync):
1040    def __init__(self):
1041        P4Sync.__init__(self)
1042        self.description = "Creates a new git repository and imports from Perforce into it"
1043        self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1044        self.needsGit = False
1045
1046    def run(self, args):
1047        global gitdir
1048
1049        if len(args) < 1:
1050            return False
1051        depotPath = args[0]
1052        dir = ""
1053        if len(args) == 2:
1054            dir = args[1]
1055        elif len(args) > 2:
1056            return False
1057
1058        if not depotPath.startswith("//"):
1059            return False
1060
1061        if len(dir) == 0:
1062            dir = depotPath
1063            atPos = dir.rfind("@")
1064            if atPos != -1:
1065                dir = dir[0:atPos]
1066            hashPos = dir.rfind("#")
1067            if hashPos != -1:
1068                dir = dir[0:hashPos]
1069
1070            if dir.endswith("..."):
1071                dir = dir[:-3]
1072
1073            if dir.endswith("/"):
1074               dir = dir[:-1]
1075
1076            slashPos = dir.rfind("/")
1077            if slashPos != -1:
1078                dir = dir[slashPos + 1:]
1079
1080        print "Importing from %s into %s" % (depotPath, dir)
1081        os.makedirs(dir)
1082        os.chdir(dir)
1083        system("git init")
1084        gitdir = os.getcwd() + "/.git"
1085        if not P4Sync.run(self, [depotPath]):
1086            return False
1087        if self.branch != "master":
1088            if gitBranchExists("refs/remotes/p4/master"):
1089                system("git branch master refs/remotes/p4/master")
1090                system("git checkout -f")
1091            else:
1092                print "Could not detect main branch. No checkout/master branch created."
1093        return True
1094
1095class HelpFormatter(optparse.IndentedHelpFormatter):
1096    def __init__(self):
1097        optparse.IndentedHelpFormatter.__init__(self)
1098
1099    def format_description(self, description):
1100        if description:
1101            return description + "\n"
1102        else:
1103            return ""
1104
1105def printUsage(commands):
1106    print "usage: %s <command> [options]" % sys.argv[0]
1107    print ""
1108    print "valid commands: %s" % ", ".join(commands)
1109    print ""
1110    print "Try %s <command> --help for command specific help." % sys.argv[0]
1111    print ""
1112
1113commands = {
1114    "debug" : P4Debug(),
1115    "submit" : P4Submit(),
1116    "sync" : P4Sync(),
1117    "rebase" : P4Rebase(),
1118    "clone" : P4Clone()
1119}
1120
1121if len(sys.argv[1:]) == 0:
1122    printUsage(commands.keys())
1123    sys.exit(2)
1124
1125cmd = ""
1126cmdName = sys.argv[1]
1127try:
1128    cmd = commands[cmdName]
1129except KeyError:
1130    print "unknown command %s" % cmdName
1131    print ""
1132    printUsage(commands.keys())
1133    sys.exit(2)
1134
1135options = cmd.options
1136cmd.gitdir = gitdir
1137
1138args = sys.argv[2:]
1139
1140if len(options) > 0:
1141    options.append(optparse.make_option("--git-dir", dest="gitdir"))
1142
1143    parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1144                                   options,
1145                                   description = cmd.description,
1146                                   formatter = HelpFormatter())
1147
1148    (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1149
1150if cmd.needsGit:
1151    gitdir = cmd.gitdir
1152    if len(gitdir) == 0:
1153        gitdir = ".git"
1154        if not isValidGitDir(gitdir):
1155            gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1156            if os.path.exists(gitdir):
1157                cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1158                if len(cdup) > 0:
1159                    os.chdir(cdup);
1160
1161    if not isValidGitDir(gitdir):
1162        if isValidGitDir(gitdir + "/.git"):
1163            gitdir += "/.git"
1164        else:
1165            die("fatal: cannot locate git repository at %s" % gitdir)
1166
1167    os.environ["GIT_DIR"] = gitdir
1168
1169if not cmd.run(args):
1170    parser.print_help()
1171