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