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