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