contrib / fast-import / git-p4on commit Merge branch 'master' of git://git.kernel.org/pub/scm/gitk/gitk into pm/gitk (e1341ab)
   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 <simon@lst.de>
   6# Copyright: 2007 Simon Hausmann <simon@lst.de>
   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
  13import re
  14
  15from sets import Set;
  16
  17verbose = False
  18
  19def die(msg):
  20    if verbose:
  21        raise Exception(msg)
  22    else:
  23        sys.stderr.write(msg + "\n")
  24        sys.exit(1)
  25
  26def write_pipe(c, str):
  27    if verbose:
  28        sys.stderr.write('Writing pipe: %s\n' % c)
  29
  30    pipe = os.popen(c, 'w')
  31    val = pipe.write(str)
  32    if pipe.close():
  33        die('Command failed: %s' % c)
  34
  35    return val
  36
  37def read_pipe(c, ignore_error=False):
  38    if verbose:
  39        sys.stderr.write('Reading pipe: %s\n' % c)
  40
  41    pipe = os.popen(c, 'rb')
  42    val = pipe.read()
  43    if pipe.close() and not ignore_error:
  44        die('Command failed: %s' % c)
  45
  46    return val
  47
  48
  49def read_pipe_lines(c):
  50    if verbose:
  51        sys.stderr.write('Reading pipe: %s\n' % c)
  52    ## todo: check return status
  53    pipe = os.popen(c, 'rb')
  54    val = pipe.readlines()
  55    if pipe.close():
  56        die('Command failed: %s' % c)
  57
  58    return val
  59
  60def system(cmd):
  61    if verbose:
  62        sys.stderr.write("executing %s\n" % cmd)
  63    if os.system(cmd) != 0:
  64        die("command failed: %s" % cmd)
  65
  66def p4CmdList(cmd):
  67    cmd = "p4 -G %s" % cmd
  68    if verbose:
  69        sys.stderr.write("Opening pipe: %s\n" % cmd)
  70    pipe = os.popen(cmd, "rb")
  71
  72    result = []
  73    try:
  74        while True:
  75            entry = marshal.load(pipe)
  76            result.append(entry)
  77    except EOFError:
  78        pass
  79    exitCode = pipe.close()
  80    if exitCode != None:
  81        entry = {}
  82        entry["p4ExitCode"] = exitCode
  83        result.append(entry)
  84
  85    return result
  86
  87def p4Cmd(cmd):
  88    list = p4CmdList(cmd)
  89    result = {}
  90    for entry in list:
  91        result.update(entry)
  92    return result;
  93
  94def p4Where(depotPath):
  95    if not depotPath.endswith("/"):
  96        depotPath += "/"
  97    output = p4Cmd("where %s..." % depotPath)
  98    if output["code"] == "error":
  99        return ""
 100    clientPath = ""
 101    if "path" in output:
 102        clientPath = output.get("path")
 103    elif "data" in output:
 104        data = output.get("data")
 105        lastSpace = data.rfind(" ")
 106        clientPath = data[lastSpace + 1:]
 107
 108    if clientPath.endswith("..."):
 109        clientPath = clientPath[:-3]
 110    return clientPath
 111
 112def currentGitBranch():
 113    return read_pipe("git name-rev HEAD").split(" ")[1].strip()
 114
 115def isValidGitDir(path):
 116    if (os.path.exists(path + "/HEAD")
 117        and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
 118        return True;
 119    return False
 120
 121def parseRevision(ref):
 122    return read_pipe("git rev-parse %s" % ref).strip()
 123
 124def extractLogMessageFromGitCommit(commit):
 125    logMessage = ""
 126
 127    ## fixme: title is first line of commit, not 1st paragraph.
 128    foundTitle = False
 129    for log in read_pipe_lines("git cat-file commit %s" % commit):
 130       if not foundTitle:
 131           if len(log) == 1:
 132               foundTitle = True
 133           continue
 134
 135       logMessage += log
 136    return logMessage
 137
 138def extractSettingsGitLog(log):
 139    values = {}
 140    for line in log.split("\n"):
 141        line = line.strip()
 142        m = re.search (r"^ *\[git-p4: (.*)\]$", line)
 143        if not m:
 144            continue
 145
 146        assignments = m.group(1).split (':')
 147        for a in assignments:
 148            vals = a.split ('=')
 149            key = vals[0].strip()
 150            val = ('='.join (vals[1:])).strip()
 151            if val.endswith ('\"') and val.startswith('"'):
 152                val = val[1:-1]
 153
 154            values[key] = val
 155
 156    paths = values.get("depot-paths")
 157    if not paths:
 158        paths = values.get("depot-path")
 159    if paths:
 160        values['depot-paths'] = paths.split(',')
 161    return values
 162
 163def gitBranchExists(branch):
 164    proc = subprocess.Popen(["git", "rev-parse", branch],
 165                            stderr=subprocess.PIPE, stdout=subprocess.PIPE);
 166    return proc.wait() == 0;
 167
 168def gitConfig(key):
 169    return read_pipe("git config %s" % key, ignore_error=True).strip()
 170
 171def findUpstreamBranchPoint(head = "HEAD"):
 172    settings = None
 173    branchPoint = ""
 174    parent = 0
 175    while parent < 65535:
 176        commit = head + "~%s" % parent
 177        log = extractLogMessageFromGitCommit(commit)
 178        settings = extractSettingsGitLog(log)
 179        if not settings.has_key("depot-paths"):
 180            parent = parent + 1
 181            continue
 182
 183        names = read_pipe_lines("git name-rev \"--refs=refs/remotes/p4/*\" \"%s\"" % commit)
 184        if len(names) <= 0:
 185            continue
 186
 187        # strip away the beginning of 'HEAD~42 refs/remotes/p4/foo'
 188        branchPoint = names[0].strip()[len(commit) + 1:]
 189        break
 190
 191    return [branchPoint, settings]
 192
 193class Command:
 194    def __init__(self):
 195        self.usage = "usage: %prog [options]"
 196        self.needsGit = True
 197
 198class P4Debug(Command):
 199    def __init__(self):
 200        Command.__init__(self)
 201        self.options = [
 202            optparse.make_option("--verbose", dest="verbose", action="store_true",
 203                                 default=False),
 204            ]
 205        self.description = "A tool to debug the output of p4 -G."
 206        self.needsGit = False
 207        self.verbose = False
 208
 209    def run(self, args):
 210        j = 0
 211        for output in p4CmdList(" ".join(args)):
 212            print 'Element: %d' % j
 213            j += 1
 214            print output
 215        return True
 216
 217class P4RollBack(Command):
 218    def __init__(self):
 219        Command.__init__(self)
 220        self.options = [
 221            optparse.make_option("--verbose", dest="verbose", action="store_true"),
 222            optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
 223        ]
 224        self.description = "A tool to debug the multi-branch import. Don't use :)"
 225        self.verbose = False
 226        self.rollbackLocalBranches = False
 227
 228    def run(self, args):
 229        if len(args) != 1:
 230            return False
 231        maxChange = int(args[0])
 232
 233        if "p4ExitCode" in p4Cmd("changes -m 1"):
 234            die("Problems executing p4");
 235
 236        if self.rollbackLocalBranches:
 237            refPrefix = "refs/heads/"
 238            lines = read_pipe_lines("git rev-parse --symbolic --branches")
 239        else:
 240            refPrefix = "refs/remotes/"
 241            lines = read_pipe_lines("git rev-parse --symbolic --remotes")
 242
 243        for line in lines:
 244            if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
 245                line = line.strip()
 246                ref = refPrefix + line
 247                log = extractLogMessageFromGitCommit(ref)
 248                settings = extractSettingsGitLog(log)
 249
 250                depotPaths = settings['depot-paths']
 251                change = settings['change']
 252
 253                changed = False
 254
 255                if len(p4Cmd("changes -m 1 "  + ' '.join (['%s...@%s' % (p, maxChange)
 256                                                           for p in depotPaths]))) == 0:
 257                    print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
 258                    system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
 259                    continue
 260
 261                while change and int(change) > maxChange:
 262                    changed = True
 263                    if self.verbose:
 264                        print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
 265                    system("git update-ref %s \"%s^\"" % (ref, ref))
 266                    log = extractLogMessageFromGitCommit(ref)
 267                    settings =  extractSettingsGitLog(log)
 268
 269
 270                    depotPaths = settings['depot-paths']
 271                    change = settings['change']
 272
 273                if changed:
 274                    print "%s rewound to %s" % (ref, change)
 275
 276        return True
 277
 278class P4Submit(Command):
 279    def __init__(self):
 280        Command.__init__(self)
 281        self.options = [
 282                optparse.make_option("--continue", action="store_false", dest="firstTime"),
 283                optparse.make_option("--verbose", dest="verbose", action="store_true"),
 284                optparse.make_option("--origin", dest="origin"),
 285                optparse.make_option("--reset", action="store_true", dest="reset"),
 286                optparse.make_option("--log-substitutions", dest="substFile"),
 287                optparse.make_option("--dry-run", action="store_true"),
 288                optparse.make_option("--direct", dest="directSubmit", action="store_true"),
 289                optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
 290        ]
 291        self.description = "Submit changes from git to the perforce depot."
 292        self.usage += " [name of git branch to submit into perforce depot]"
 293        self.firstTime = True
 294        self.reset = False
 295        self.interactive = True
 296        self.dryRun = False
 297        self.substFile = ""
 298        self.firstTime = True
 299        self.origin = ""
 300        self.directSubmit = False
 301        self.trustMeLikeAFool = False
 302        self.verbose = False
 303        self.isWindows = (platform.system() == "Windows")
 304
 305        self.logSubstitutions = {}
 306        self.logSubstitutions["<enter description here>"] = "%log%"
 307        self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
 308
 309    def check(self):
 310        if len(p4CmdList("opened ...")) > 0:
 311            die("You have files opened with perforce! Close them before starting the sync.")
 312
 313    def start(self):
 314        if len(self.config) > 0 and not self.reset:
 315            die("Cannot start sync. Previous sync config found at %s\n"
 316                "If you want to start submitting again from scratch "
 317                "maybe you want to call git-p4 submit --reset" % self.configFile)
 318
 319        commits = []
 320        if self.directSubmit:
 321            commits.append("0")
 322        else:
 323            for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
 324                commits.append(line.strip())
 325            commits.reverse()
 326
 327        self.config["commits"] = commits
 328
 329    def prepareLogMessage(self, template, message):
 330        result = ""
 331
 332        for line in template.split("\n"):
 333            if line.startswith("#"):
 334                result += line + "\n"
 335                continue
 336
 337            substituted = False
 338            for key in self.logSubstitutions.keys():
 339                if line.find(key) != -1:
 340                    value = self.logSubstitutions[key]
 341                    value = value.replace("%log%", message)
 342                    if value != "@remove@":
 343                        result += line.replace(key, value) + "\n"
 344                    substituted = True
 345                    break
 346
 347            if not substituted:
 348                result += line + "\n"
 349
 350        return result
 351
 352    def applyCommit(self, id):
 353        if self.directSubmit:
 354            print "Applying local change in working directory/index"
 355            diff = self.diffStatus
 356        else:
 357            print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
 358            diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
 359        filesToAdd = set()
 360        filesToDelete = set()
 361        editedFiles = set()
 362        for line in diff:
 363            modifier = line[0]
 364            path = line[1:].strip()
 365            if modifier == "M":
 366                system("p4 edit \"%s\"" % path)
 367                editedFiles.add(path)
 368            elif modifier == "A":
 369                filesToAdd.add(path)
 370                if path in filesToDelete:
 371                    filesToDelete.remove(path)
 372            elif modifier == "D":
 373                filesToDelete.add(path)
 374                if path in filesToAdd:
 375                    filesToAdd.remove(path)
 376            else:
 377                die("unknown modifier %s for %s" % (modifier, path))
 378
 379        if self.directSubmit:
 380            diffcmd = "cat \"%s\"" % self.diffFile
 381        else:
 382            diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
 383        patchcmd = diffcmd + " | git apply "
 384        tryPatchCmd = patchcmd + "--check -"
 385        applyPatchCmd = patchcmd + "--check --apply -"
 386
 387        if os.system(tryPatchCmd) != 0:
 388            print "Unfortunately applying the change failed!"
 389            print "What do you want to do?"
 390            response = "x"
 391            while response != "s" and response != "a" and response != "w":
 392                response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
 393                                     "and with .rej files / [w]rite the patch to a file (patch.txt) ")
 394            if response == "s":
 395                print "Skipping! Good luck with the next patches..."
 396                return
 397            elif response == "a":
 398                os.system(applyPatchCmd)
 399                if len(filesToAdd) > 0:
 400                    print "You may also want to call p4 add on the following files:"
 401                    print " ".join(filesToAdd)
 402                if len(filesToDelete):
 403                    print "The following files should be scheduled for deletion with p4 delete:"
 404                    print " ".join(filesToDelete)
 405                die("Please resolve and submit the conflict manually and "
 406                    + "continue afterwards with git-p4 submit --continue")
 407            elif response == "w":
 408                system(diffcmd + " > patch.txt")
 409                print "Patch saved to patch.txt in %s !" % self.clientPath
 410                die("Please resolve and submit the conflict manually and "
 411                    "continue afterwards with git-p4 submit --continue")
 412
 413        system(applyPatchCmd)
 414
 415        for f in filesToAdd:
 416            system("p4 add \"%s\"" % f)
 417        for f in filesToDelete:
 418            system("p4 revert \"%s\"" % f)
 419            system("p4 delete \"%s\"" % f)
 420
 421        logMessage = ""
 422        if not self.directSubmit:
 423            logMessage = extractLogMessageFromGitCommit(id)
 424            logMessage = logMessage.replace("\n", "\n\t")
 425            if self.isWindows:
 426                logMessage = logMessage.replace("\n", "\r\n")
 427            logMessage = logMessage.strip()
 428
 429        template = read_pipe("p4 change -o")
 430
 431        if self.interactive:
 432            submitTemplate = self.prepareLogMessage(template, logMessage)
 433            diff = read_pipe("p4 diff -du ...")
 434
 435            for newFile in filesToAdd:
 436                diff += "==== new file ====\n"
 437                diff += "--- /dev/null\n"
 438                diff += "+++ %s\n" % newFile
 439                f = open(newFile, "r")
 440                for line in f.readlines():
 441                    diff += "+" + line
 442                f.close()
 443
 444            separatorLine = "######## everything below this line is just the diff #######"
 445            if platform.system() == "Windows":
 446                separatorLine += "\r"
 447            separatorLine += "\n"
 448
 449            response = "e"
 450            if self.trustMeLikeAFool:
 451                response = "y"
 452
 453            firstIteration = True
 454            while response == "e":
 455                if not firstIteration:
 456                    response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
 457                firstIteration = False
 458                if response == "e":
 459                    [handle, fileName] = tempfile.mkstemp()
 460                    tmpFile = os.fdopen(handle, "w+")
 461                    tmpFile.write(submitTemplate + separatorLine + diff)
 462                    tmpFile.close()
 463                    defaultEditor = "vi"
 464                    if platform.system() == "Windows":
 465                        defaultEditor = "notepad"
 466                    editor = os.environ.get("EDITOR", defaultEditor);
 467                    system(editor + " " + fileName)
 468                    tmpFile = open(fileName, "rb")
 469                    message = tmpFile.read()
 470                    tmpFile.close()
 471                    os.remove(fileName)
 472                    submitTemplate = message[:message.index(separatorLine)]
 473                    if self.isWindows:
 474                        submitTemplate = submitTemplate.replace("\r\n", "\n")
 475
 476            if response == "y" or response == "yes":
 477               if self.dryRun:
 478                   print submitTemplate
 479                   raw_input("Press return to continue...")
 480               else:
 481                   if self.directSubmit:
 482                       print "Submitting to git first"
 483                       os.chdir(self.oldWorkingDirectory)
 484                       write_pipe("git commit -a -F -", submitTemplate)
 485                       os.chdir(self.clientPath)
 486
 487                   write_pipe("p4 submit -i", submitTemplate)
 488            elif response == "s":
 489                for f in editedFiles:
 490                    system("p4 revert \"%s\"" % f);
 491                for f in filesToAdd:
 492                    system("p4 revert \"%s\"" % f);
 493                    system("rm %s" %f)
 494                for f in filesToDelete:
 495                    system("p4 delete \"%s\"" % f);
 496                return
 497            else:
 498                print "Not submitting!"
 499                self.interactive = False
 500        else:
 501            fileName = "submit.txt"
 502            file = open(fileName, "w+")
 503            file.write(self.prepareLogMessage(template, logMessage))
 504            file.close()
 505            print ("Perforce submit template written as %s. "
 506                   + "Please review/edit and then use p4 submit -i < %s to submit directly!"
 507                   % (fileName, fileName))
 508
 509    def run(self, args):
 510        if len(args) == 0:
 511            self.master = currentGitBranch()
 512            if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
 513                die("Detecting current git branch failed!")
 514        elif len(args) == 1:
 515            self.master = args[0]
 516        else:
 517            return False
 518
 519        [upstream, settings] = findUpstreamBranchPoint()
 520        depotPath = settings['depot-paths'][0]
 521        if len(self.origin) == 0:
 522            self.origin = upstream
 523
 524        if self.verbose:
 525            print "Origin branch is " + self.origin
 526
 527        if len(depotPath) == 0:
 528            print "Internal error: cannot locate perforce depot path from existing branches"
 529            sys.exit(128)
 530
 531        self.clientPath = p4Where(depotPath)
 532
 533        if len(self.clientPath) == 0:
 534            print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
 535            sys.exit(128)
 536
 537        print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
 538        self.oldWorkingDirectory = os.getcwd()
 539
 540        if self.directSubmit:
 541            self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
 542            if len(self.diffStatus) == 0:
 543                print "No changes in working directory to submit."
 544                return True
 545            patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
 546            self.diffFile = self.gitdir + "/p4-git-diff"
 547            f = open(self.diffFile, "wb")
 548            f.write(patch)
 549            f.close();
 550
 551        os.chdir(self.clientPath)
 552        response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
 553        if response == "y" or response == "yes":
 554            system("p4 sync ...")
 555
 556        if self.reset:
 557            self.firstTime = True
 558
 559        if len(self.substFile) > 0:
 560            for line in open(self.substFile, "r").readlines():
 561                tokens = line.strip().split("=")
 562                self.logSubstitutions[tokens[0]] = tokens[1]
 563
 564        self.check()
 565        self.configFile = self.gitdir + "/p4-git-sync.cfg"
 566        self.config = shelve.open(self.configFile, writeback=True)
 567
 568        if self.firstTime:
 569            self.start()
 570
 571        commits = self.config.get("commits", [])
 572
 573        while len(commits) > 0:
 574            self.firstTime = False
 575            commit = commits[0]
 576            commits = commits[1:]
 577            self.config["commits"] = commits
 578            self.applyCommit(commit)
 579            if not self.interactive:
 580                break
 581
 582        self.config.close()
 583
 584        if self.directSubmit:
 585            os.remove(self.diffFile)
 586
 587        if len(commits) == 0:
 588            if self.firstTime:
 589                print "No changes found to apply between %s and current HEAD" % self.origin
 590            else:
 591                print "All changes applied!"
 592                os.chdir(self.oldWorkingDirectory)
 593                response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
 594                if response == "y" or response == "yes":
 595                    rebase = P4Rebase()
 596                    rebase.run([])
 597            os.remove(self.configFile)
 598
 599        return True
 600
 601class P4Sync(Command):
 602    def __init__(self):
 603        Command.__init__(self)
 604        self.options = [
 605                optparse.make_option("--branch", dest="branch"),
 606                optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
 607                optparse.make_option("--changesfile", dest="changesFile"),
 608                optparse.make_option("--silent", dest="silent", action="store_true"),
 609                optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
 610                optparse.make_option("--verbose", dest="verbose", action="store_true"),
 611                optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
 612                                     help="Import into refs/heads/ , not refs/remotes"),
 613                optparse.make_option("--max-changes", dest="maxChanges"),
 614                optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
 615                                     help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
 616        ]
 617        self.description = """Imports from Perforce into a git repository.\n
 618    example:
 619    //depot/my/project/ -- to import the current head
 620    //depot/my/project/@all -- to import everything
 621    //depot/my/project/@1,6 -- to import only from revision 1 to 6
 622
 623    (a ... is not needed in the path p4 specification, it's added implicitly)"""
 624
 625        self.usage += " //depot/path[@revRange]"
 626        self.silent = False
 627        self.createdBranches = Set()
 628        self.committedChanges = Set()
 629        self.branch = ""
 630        self.detectBranches = False
 631        self.detectLabels = False
 632        self.changesFile = ""
 633        self.syncWithOrigin = True
 634        self.verbose = False
 635        self.importIntoRemotes = True
 636        self.maxChanges = ""
 637        self.isWindows = (platform.system() == "Windows")
 638        self.keepRepoPath = False
 639        self.depotPaths = None
 640        self.p4BranchesInGit = []
 641
 642        if gitConfig("git-p4.syncFromOrigin") == "false":
 643            self.syncWithOrigin = False
 644
 645    def extractFilesFromCommit(self, commit):
 646        files = []
 647        fnum = 0
 648        while commit.has_key("depotFile%s" % fnum):
 649            path =  commit["depotFile%s" % fnum]
 650
 651            found = [p for p in self.depotPaths
 652                     if path.startswith (p)]
 653            if not found:
 654                fnum = fnum + 1
 655                continue
 656
 657            file = {}
 658            file["path"] = path
 659            file["rev"] = commit["rev%s" % fnum]
 660            file["action"] = commit["action%s" % fnum]
 661            file["type"] = commit["type%s" % fnum]
 662            files.append(file)
 663            fnum = fnum + 1
 664        return files
 665
 666    def stripRepoPath(self, path, prefixes):
 667        if self.keepRepoPath:
 668            prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
 669
 670        for p in prefixes:
 671            if path.startswith(p):
 672                path = path[len(p):]
 673
 674        return path
 675
 676    def splitFilesIntoBranches(self, commit):
 677        branches = {}
 678        fnum = 0
 679        while commit.has_key("depotFile%s" % fnum):
 680            path =  commit["depotFile%s" % fnum]
 681            found = [p for p in self.depotPaths
 682                     if path.startswith (p)]
 683            if not found:
 684                fnum = fnum + 1
 685                continue
 686
 687            file = {}
 688            file["path"] = path
 689            file["rev"] = commit["rev%s" % fnum]
 690            file["action"] = commit["action%s" % fnum]
 691            file["type"] = commit["type%s" % fnum]
 692            fnum = fnum + 1
 693
 694            relPath = self.stripRepoPath(path, self.depotPaths)
 695
 696            for branch in self.knownBranches.keys():
 697
 698                # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
 699                if relPath.startswith(branch + "/"):
 700                    if branch not in branches:
 701                        branches[branch] = []
 702                    branches[branch].append(file)
 703                    break
 704
 705        return branches
 706
 707    ## Should move this out, doesn't use SELF.
 708    def readP4Files(self, files):
 709        files = [f for f in files
 710                 if f['action'] != 'delete']
 711
 712        if not files:
 713            return
 714
 715        # We cannot put all the files on the command line
 716        # OS have limitations on the max lenght of arguments
 717        # POSIX says it's 4096 bytes, default for Linux seems to be 130 K.
 718        # and all OS from the table below seems to be higher than POSIX.
 719        # See http://www.in-ulm.de/~mascheck/various/argmax/
 720        argmax = min(4000, os.sysconf('SC_ARG_MAX'))
 721        chunk = ''
 722        filedata = []
 723        for i in xrange(len(files)):
 724            f = files[i]
 725            chunk += '"%s#%s" ' % (f['path'], f['rev'])
 726            if len(chunk) > argmax or i == len(files)-1:
 727                data = p4CmdList('print %s' % chunk)
 728                if "p4ExitCode" in data[0]:
 729                    die("Problems executing p4. Error: [%d]." % (data[0]['p4ExitCode']));
 730                filedata.extend(data)
 731                chunk = ''
 732
 733        j = 0;
 734        contents = {}
 735        while j < len(filedata):
 736            stat = filedata[j]
 737            j += 1
 738            text = ''
 739            while j < len(filedata) and filedata[j]['code'] in ('text',
 740                                                                'binary'):
 741                text += filedata[j]['data']
 742                j += 1
 743
 744
 745            if not stat.has_key('depotFile'):
 746                sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
 747                continue
 748
 749            contents[stat['depotFile']] = text
 750
 751        for f in files:
 752            assert not f.has_key('data')
 753            f['data'] = contents[f['path']]
 754
 755    def commit(self, details, files, branch, branchPrefixes, parent = ""):
 756        epoch = details["time"]
 757        author = details["user"]
 758
 759        if self.verbose:
 760            print "commit into %s" % branch
 761
 762        # start with reading files; if that fails, we should not
 763        # create a commit.
 764        new_files = []
 765        for f in files:
 766            if [p for p in branchPrefixes if f['path'].startswith(p)]:
 767                new_files.append (f)
 768            else:
 769                sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
 770        files = new_files
 771        self.readP4Files(files)
 772
 773
 774
 775
 776        self.gitStream.write("commit %s\n" % branch)
 777#        gitStream.write("mark :%s\n" % details["change"])
 778        self.committedChanges.add(int(details["change"]))
 779        committer = ""
 780        if author not in self.users:
 781            self.getUserMapFromPerforceServer()
 782        if author in self.users:
 783            committer = "%s %s %s" % (self.users[author], epoch, self.tz)
 784        else:
 785            committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
 786
 787        self.gitStream.write("committer %s\n" % committer)
 788
 789        self.gitStream.write("data <<EOT\n")
 790        self.gitStream.write(details["desc"])
 791        self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s"
 792                             % (','.join (branchPrefixes), details["change"]))
 793        if len(details['options']) > 0:
 794            self.gitStream.write(": options = %s" % details['options'])
 795        self.gitStream.write("]\nEOT\n\n")
 796
 797        if len(parent) > 0:
 798            if self.verbose:
 799                print "parent %s" % parent
 800            self.gitStream.write("from %s\n" % parent)
 801
 802        for file in files:
 803            if file["type"] == "apple":
 804                print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
 805                continue
 806
 807            relPath = self.stripRepoPath(file['path'], branchPrefixes)
 808            if file["action"] == "delete":
 809                self.gitStream.write("D %s\n" % relPath)
 810            else:
 811                mode = 644
 812                if file["type"].startswith("x"):
 813                    mode = 755
 814
 815                data = file['data']
 816
 817                if self.isWindows and file["type"].endswith("text"):
 818                    data = data.replace("\r\n", "\n")
 819
 820                self.gitStream.write("M %d inline %s\n" % (mode, relPath))
 821                self.gitStream.write("data %s\n" % len(data))
 822                self.gitStream.write(data)
 823                self.gitStream.write("\n")
 824
 825        self.gitStream.write("\n")
 826
 827        change = int(details["change"])
 828
 829        if self.labels.has_key(change):
 830            label = self.labels[change]
 831            labelDetails = label[0]
 832            labelRevisions = label[1]
 833            if self.verbose:
 834                print "Change %s is labelled %s" % (change, labelDetails)
 835
 836            files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
 837                                                    for p in branchPrefixes]))
 838
 839            if len(files) == len(labelRevisions):
 840
 841                cleanedFiles = {}
 842                for info in files:
 843                    if info["action"] == "delete":
 844                        continue
 845                    cleanedFiles[info["depotFile"]] = info["rev"]
 846
 847                if cleanedFiles == labelRevisions:
 848                    self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
 849                    self.gitStream.write("from %s\n" % branch)
 850
 851                    owner = labelDetails["Owner"]
 852                    tagger = ""
 853                    if author in self.users:
 854                        tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
 855                    else:
 856                        tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
 857                    self.gitStream.write("tagger %s\n" % tagger)
 858                    self.gitStream.write("data <<EOT\n")
 859                    self.gitStream.write(labelDetails["Description"])
 860                    self.gitStream.write("EOT\n\n")
 861
 862                else:
 863                    if not self.silent:
 864                        print ("Tag %s does not match with change %s: files do not match."
 865                               % (labelDetails["label"], change))
 866
 867            else:
 868                if not self.silent:
 869                    print ("Tag %s does not match with change %s: file count is different."
 870                           % (labelDetails["label"], change))
 871
 872    def getUserCacheFilename(self):
 873        return os.environ["HOME"] + "/.gitp4-usercache.txt"
 874
 875    def getUserMapFromPerforceServer(self):
 876        if self.userMapFromPerforceServer:
 877            return
 878        self.users = {}
 879
 880        for output in p4CmdList("users"):
 881            if not output.has_key("User"):
 882                continue
 883            self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
 884
 885
 886        s = ''
 887        for (key, val) in self.users.items():
 888            s += "%s\t%s\n" % (key, val)
 889
 890        open(self.getUserCacheFilename(), "wb").write(s)
 891        self.userMapFromPerforceServer = True
 892
 893    def loadUserMapFromCache(self):
 894        self.users = {}
 895        self.userMapFromPerforceServer = False
 896        try:
 897            cache = open(self.getUserCacheFilename(), "rb")
 898            lines = cache.readlines()
 899            cache.close()
 900            for line in lines:
 901                entry = line.strip().split("\t")
 902                self.users[entry[0]] = entry[1]
 903        except IOError:
 904            self.getUserMapFromPerforceServer()
 905
 906    def getLabels(self):
 907        self.labels = {}
 908
 909        l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
 910        if len(l) > 0 and not self.silent:
 911            print "Finding files belonging to labels in %s" % `self.depotPath`
 912
 913        for output in l:
 914            label = output["label"]
 915            revisions = {}
 916            newestChange = 0
 917            if self.verbose:
 918                print "Querying files for label %s" % label
 919            for file in p4CmdList("files "
 920                                  +  ' '.join (["%s...@%s" % (p, label)
 921                                                for p in self.depotPaths])):
 922                revisions[file["depotFile"]] = file["rev"]
 923                change = int(file["change"])
 924                if change > newestChange:
 925                    newestChange = change
 926
 927            self.labels[newestChange] = [output, revisions]
 928
 929        if self.verbose:
 930            print "Label changes: %s" % self.labels.keys()
 931
 932    def guessProjectName(self):
 933        for p in self.depotPaths:
 934            if p.endswith("/"):
 935                p = p[:-1]
 936            p = p[p.strip().rfind("/") + 1:]
 937            if not p.endswith("/"):
 938               p += "/"
 939            return p
 940
 941    def getBranchMapping(self):
 942        lostAndFoundBranches = set()
 943
 944        for info in p4CmdList("branches"):
 945            details = p4Cmd("branch -o %s" % info["branch"])
 946            viewIdx = 0
 947            while details.has_key("View%s" % viewIdx):
 948                paths = details["View%s" % viewIdx].split(" ")
 949                viewIdx = viewIdx + 1
 950                # require standard //depot/foo/... //depot/bar/... mapping
 951                if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
 952                    continue
 953                source = paths[0]
 954                destination = paths[1]
 955                ## HACK
 956                if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
 957                    source = source[len(self.depotPaths[0]):-4]
 958                    destination = destination[len(self.depotPaths[0]):-4]
 959
 960                    if destination in self.knownBranches:
 961                        if not self.silent:
 962                            print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
 963                            print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
 964                        continue
 965
 966                    self.knownBranches[destination] = source
 967
 968                    lostAndFoundBranches.discard(destination)
 969
 970                    if source not in self.knownBranches:
 971                        lostAndFoundBranches.add(source)
 972
 973
 974        for branch in lostAndFoundBranches:
 975            self.knownBranches[branch] = branch
 976
 977    def listExistingP4GitBranches(self):
 978        self.p4BranchesInGit = []
 979
 980        cmdline = "git rev-parse --symbolic "
 981        if self.importIntoRemotes:
 982            cmdline += " --remotes"
 983        else:
 984            cmdline += " --branches"
 985
 986        for line in read_pipe_lines(cmdline):
 987            line = line.strip()
 988
 989            ## only import to p4/
 990            if not line.startswith('p4/') or line == "p4/HEAD":
 991                continue
 992            branch = line
 993
 994            # strip off p4
 995            branch = re.sub ("^p4/", "", line)
 996
 997            self.p4BranchesInGit.append(branch)
 998            self.initialParents[self.refPrefix + branch] = parseRevision(line)
 999
1000    def createOrUpdateBranchesFromOrigin(self):
1001        if not self.silent:
1002            print ("Creating/updating branch(es) in %s based on origin branch(es)"
1003                   % self.refPrefix)
1004
1005        originPrefix = "origin/p4/"
1006
1007        for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
1008            line = line.strip()
1009            if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
1010                continue
1011
1012            headName = line[len(originPrefix):]
1013            remoteHead = self.refPrefix + headName
1014            originHead = line
1015
1016            original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
1017            if (not original.has_key('depot-paths')
1018                or not original.has_key('change')):
1019                continue
1020
1021            update = False
1022            if not gitBranchExists(remoteHead):
1023                if self.verbose:
1024                    print "creating %s" % remoteHead
1025                update = True
1026            else:
1027                settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
1028                if settings.has_key('change') > 0:
1029                    if settings['depot-paths'] == original['depot-paths']:
1030                        originP4Change = int(original['change'])
1031                        p4Change = int(settings['change'])
1032                        if originP4Change > p4Change:
1033                            print ("%s (%s) is newer than %s (%s). "
1034                                   "Updating p4 branch from origin."
1035                                   % (originHead, originP4Change,
1036                                      remoteHead, p4Change))
1037                            update = True
1038                    else:
1039                        print ("Ignoring: %s was imported from %s while "
1040                               "%s was imported from %s"
1041                               % (originHead, ','.join(original['depot-paths']),
1042                                  remoteHead, ','.join(settings['depot-paths'])))
1043
1044            if update:
1045                system("git update-ref %s %s" % (remoteHead, originHead))
1046
1047    def updateOptionDict(self, d):
1048        option_keys = {}
1049        if self.keepRepoPath:
1050            option_keys['keepRepoPath'] = 1
1051
1052        d["options"] = ' '.join(sorted(option_keys.keys()))
1053
1054    def readOptions(self, d):
1055        self.keepRepoPath = (d.has_key('options')
1056                             and ('keepRepoPath' in d['options']))
1057
1058    def run(self, args):
1059        self.depotPaths = []
1060        self.changeRange = ""
1061        self.initialParent = ""
1062        self.previousDepotPaths = []
1063
1064        # map from branch depot path to parent branch
1065        self.knownBranches = {}
1066        self.initialParents = {}
1067        self.hasOrigin = gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
1068        if not self.syncWithOrigin:
1069            self.hasOrigin = False
1070
1071        if self.importIntoRemotes:
1072            self.refPrefix = "refs/remotes/p4/"
1073        else:
1074            self.refPrefix = "refs/heads/p4/"
1075
1076        if self.syncWithOrigin and self.hasOrigin:
1077            if not self.silent:
1078                print "Syncing with origin first by calling git fetch origin"
1079            system("git fetch origin")
1080
1081        if len(self.branch) == 0:
1082            self.branch = self.refPrefix + "master"
1083            if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1084                system("git update-ref %s refs/heads/p4" % self.branch)
1085                system("git branch -D p4");
1086            # create it /after/ importing, when master exists
1087            if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
1088                system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1089
1090        # TODO: should always look at previous commits,
1091        # merge with previous imports, if possible.
1092        if args == []:
1093            if self.hasOrigin:
1094                self.createOrUpdateBranchesFromOrigin()
1095            self.listExistingP4GitBranches()
1096
1097            if len(self.p4BranchesInGit) > 1:
1098                if not self.silent:
1099                    print "Importing from/into multiple branches"
1100                self.detectBranches = True
1101
1102            if self.verbose:
1103                print "branches: %s" % self.p4BranchesInGit
1104
1105            p4Change = 0
1106            for branch in self.p4BranchesInGit:
1107                logMsg =  extractLogMessageFromGitCommit(self.refPrefix + branch)
1108
1109                settings = extractSettingsGitLog(logMsg)
1110
1111                self.readOptions(settings)
1112                if (settings.has_key('depot-paths')
1113                    and settings.has_key ('change')):
1114                    change = int(settings['change']) + 1
1115                    p4Change = max(p4Change, change)
1116
1117                    depotPaths = sorted(settings['depot-paths'])
1118                    if self.previousDepotPaths == []:
1119                        self.previousDepotPaths = depotPaths
1120                    else:
1121                        paths = []
1122                        for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1123                            for i in range(0, min(len(cur), len(prev))):
1124                                if cur[i] <> prev[i]:
1125                                    i = i - 1
1126                                    break
1127
1128                            paths.append (cur[:i + 1])
1129
1130                        self.previousDepotPaths = paths
1131
1132            if p4Change > 0:
1133                self.depotPaths = sorted(self.previousDepotPaths)
1134                self.changeRange = "@%s,#head" % p4Change
1135                if not self.detectBranches:
1136                    self.initialParent = parseRevision(self.branch)
1137                if not self.silent and not self.detectBranches:
1138                    print "Performing incremental import into %s git branch" % self.branch
1139
1140        if not self.branch.startswith("refs/"):
1141            self.branch = "refs/heads/" + self.branch
1142
1143        if len(args) == 0 and self.depotPaths:
1144            if not self.silent:
1145                print "Depot paths: %s" % ' '.join(self.depotPaths)
1146        else:
1147            if self.depotPaths and self.depotPaths != args:
1148                print ("previous import used depot path %s and now %s was specified. "
1149                       "This doesn't work!" % (' '.join (self.depotPaths),
1150                                               ' '.join (args)))
1151                sys.exit(1)
1152
1153            self.depotPaths = sorted(args)
1154
1155        self.revision = ""
1156        self.users = {}
1157
1158        newPaths = []
1159        for p in self.depotPaths:
1160            if p.find("@") != -1:
1161                atIdx = p.index("@")
1162                self.changeRange = p[atIdx:]
1163                if self.changeRange == "@all":
1164                    self.changeRange = ""
1165                elif ',' not in self.changeRange:
1166                    self.revision = self.changeRange
1167                    self.changeRange = ""
1168                p = p[0:atIdx]
1169            elif p.find("#") != -1:
1170                hashIdx = p.index("#")
1171                self.revision = p[hashIdx:]
1172                p = p[0:hashIdx]
1173            elif self.previousDepotPaths == []:
1174                self.revision = "#head"
1175
1176            p = re.sub ("\.\.\.$", "", p)
1177            if not p.endswith("/"):
1178                p += "/"
1179
1180            newPaths.append(p)
1181
1182        self.depotPaths = newPaths
1183
1184
1185        self.loadUserMapFromCache()
1186        self.labels = {}
1187        if self.detectLabels:
1188            self.getLabels();
1189
1190        if self.detectBranches:
1191            ## FIXME - what's a P4 projectName ?
1192            self.projectName = self.guessProjectName()
1193
1194            if not self.hasOrigin:
1195                self.getBranchMapping();
1196            if self.verbose:
1197                print "p4-git branches: %s" % self.p4BranchesInGit
1198                print "initial parents: %s" % self.initialParents
1199            for b in self.p4BranchesInGit:
1200                if b != "master":
1201
1202                    ## FIXME
1203                    b = b[len(self.projectName):]
1204                self.createdBranches.add(b)
1205
1206        self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1207
1208        importProcess = subprocess.Popen(["git", "fast-import"],
1209                                         stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1210                                         stderr=subprocess.PIPE);
1211        self.gitOutput = importProcess.stdout
1212        self.gitStream = importProcess.stdin
1213        self.gitError = importProcess.stderr
1214
1215        if self.revision:
1216            print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), self.revision, self.branch)
1217
1218            details = { "user" : "git perforce import user", "time" : int(time.time()) }
1219            details["desc"] = ("Initial import of %s from the state at revision %s"
1220                               % (' '.join(self.depotPaths), self.revision))
1221            details["change"] = self.revision
1222            newestRevision = 0
1223
1224            fileCnt = 0
1225            for info in p4CmdList("files "
1226                                  +  ' '.join(["%s...%s"
1227                                               % (p, self.revision)
1228                                               for p in self.depotPaths])):
1229
1230                if info['code'] == 'error':
1231                    sys.stderr.write("p4 returned an error: %s\n"
1232                                     % info['data'])
1233                    sys.exit(1)
1234
1235
1236                change = int(info["change"])
1237                if change > newestRevision:
1238                    newestRevision = change
1239
1240                if info["action"] == "delete":
1241                    # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1242                    #fileCnt = fileCnt + 1
1243                    continue
1244
1245                for prop in ["depotFile", "rev", "action", "type" ]:
1246                    details["%s%s" % (prop, fileCnt)] = info[prop]
1247
1248                fileCnt = fileCnt + 1
1249
1250            details["change"] = newestRevision
1251            self.updateOptionDict(details)
1252            try:
1253                self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1254            except IOError:
1255                print "IO error with git fast-import. Is your git version recent enough?"
1256                print self.gitError.read()
1257
1258        else:
1259            changes = []
1260
1261            if len(self.changesFile) > 0:
1262                output = open(self.changesFile).readlines()
1263                changeSet = Set()
1264                for line in output:
1265                    changeSet.add(int(line))
1266
1267                for change in changeSet:
1268                    changes.append(change)
1269
1270                changes.sort()
1271            else:
1272                if self.verbose:
1273                    print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1274                                                              self.changeRange)
1275                assert self.depotPaths
1276                output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1277                                                                    for p in self.depotPaths]))
1278
1279                for line in output:
1280                    changeNum = line.split(" ")[1]
1281                    changes.append(changeNum)
1282
1283                changes.reverse()
1284
1285                if len(self.maxChanges) > 0:
1286                    changes = changes[0:min(int(self.maxChanges), len(changes))]
1287
1288            if len(changes) == 0:
1289                if not self.silent:
1290                    print "No changes to import!"
1291                return True
1292
1293            if not self.silent and not self.detectBranches:
1294                print "Import destination: %s" % self.branch
1295
1296            self.updatedBranches = set()
1297
1298            cnt = 1
1299            for change in changes:
1300                description = p4Cmd("describe %s" % change)
1301                self.updateOptionDict(description)
1302
1303                if not self.silent:
1304                    sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1305                    sys.stdout.flush()
1306                cnt = cnt + 1
1307
1308                try:
1309                    if self.detectBranches:
1310                        branches = self.splitFilesIntoBranches(description)
1311                        for branch in branches.keys():
1312                            ## HACK  --hwn
1313                            branchPrefix = self.depotPaths[0] + branch + "/"
1314
1315                            parent = ""
1316
1317                            filesForCommit = branches[branch]
1318
1319                            if self.verbose:
1320                                print "branch is %s" % branch
1321
1322                            self.updatedBranches.add(branch)
1323
1324                            if branch not in self.createdBranches:
1325                                self.createdBranches.add(branch)
1326                                parent = self.knownBranches[branch]
1327                                if parent == branch:
1328                                    parent = ""
1329                                elif self.verbose:
1330                                    print "parent determined through known branches: %s" % parent
1331
1332                            # main branch? use master
1333                            if branch == "main":
1334                                branch = "master"
1335                            else:
1336
1337                                ## FIXME
1338                                branch = self.projectName + branch
1339
1340                            if parent == "main":
1341                                parent = "master"
1342                            elif len(parent) > 0:
1343                                ## FIXME
1344                                parent = self.projectName + parent
1345
1346                            branch = self.refPrefix + branch
1347                            if len(parent) > 0:
1348                                parent = self.refPrefix + parent
1349
1350                            if self.verbose:
1351                                print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1352
1353                            if len(parent) == 0 and branch in self.initialParents:
1354                                parent = self.initialParents[branch]
1355                                del self.initialParents[branch]
1356
1357                            self.commit(description, filesForCommit, branch, [branchPrefix], parent)
1358                    else:
1359                        files = self.extractFilesFromCommit(description)
1360                        self.commit(description, files, self.branch, self.depotPaths,
1361                                    self.initialParent)
1362                        self.initialParent = ""
1363                except IOError:
1364                    print self.gitError.read()
1365                    sys.exit(1)
1366
1367            if not self.silent:
1368                print ""
1369                if len(self.updatedBranches) > 0:
1370                    sys.stdout.write("Updated branches: ")
1371                    for b in self.updatedBranches:
1372                        sys.stdout.write("%s " % b)
1373                    sys.stdout.write("\n")
1374
1375
1376        self.gitStream.close()
1377        if importProcess.wait() != 0:
1378            die("fast-import failed: %s" % self.gitError.read())
1379        self.gitOutput.close()
1380        self.gitError.close()
1381
1382        return True
1383
1384class P4Rebase(Command):
1385    def __init__(self):
1386        Command.__init__(self)
1387        self.options = [ ]
1388        self.description = ("Fetches the latest revision from perforce and "
1389                            + "rebases the current work (branch) against it")
1390        self.verbose = False
1391
1392    def run(self, args):
1393        sync = P4Sync()
1394        sync.run([])
1395
1396        [upstream, settings] = findUpstreamBranchPoint()
1397        if len(upstream) == 0:
1398            die("Cannot find upstream branchpoint for rebase")
1399
1400        # the branchpoint may be p4/foo~3, so strip off the parent
1401        upstream = re.sub("~[0-9]+$", "", upstream)
1402
1403        print "Rebasing the current branch onto %s" % upstream
1404        oldHead = read_pipe("git rev-parse HEAD").strip()
1405        system("git rebase %s" % upstream)
1406        system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1407        return True
1408
1409class P4Clone(P4Sync):
1410    def __init__(self):
1411        P4Sync.__init__(self)
1412        self.description = "Creates a new git repository and imports from Perforce into it"
1413        self.usage = "usage: %prog [options] //depot/path[@revRange]"
1414        self.options.append(
1415            optparse.make_option("--destination", dest="cloneDestination",
1416                                 action='store', default=None,
1417                                 help="where to leave result of the clone"))
1418        self.cloneDestination = None
1419        self.needsGit = False
1420
1421    def defaultDestination(self, args):
1422        ## TODO: use common prefix of args?
1423        depotPath = args[0]
1424        depotDir = re.sub("(@[^@]*)$", "", depotPath)
1425        depotDir = re.sub("(#[^#]*)$", "", depotDir)
1426        depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1427        depotDir = re.sub(r"/$", "", depotDir)
1428        return os.path.split(depotDir)[1]
1429
1430    def run(self, args):
1431        if len(args) < 1:
1432            return False
1433
1434        if self.keepRepoPath and not self.cloneDestination:
1435            sys.stderr.write("Must specify destination for --keep-path\n")
1436            sys.exit(1)
1437
1438        depotPaths = args
1439
1440        if not self.cloneDestination and len(depotPaths) > 1:
1441            self.cloneDestination = depotPaths[-1]
1442            depotPaths = depotPaths[:-1]
1443
1444        for p in depotPaths:
1445            if not p.startswith("//"):
1446                return False
1447
1448        if not self.cloneDestination:
1449            self.cloneDestination = self.defaultDestination(args)
1450
1451        print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1452        if not os.path.exists(self.cloneDestination):
1453            os.makedirs(self.cloneDestination)
1454        os.chdir(self.cloneDestination)
1455        system("git init")
1456        self.gitdir = os.getcwd() + "/.git"
1457        if not P4Sync.run(self, depotPaths):
1458            return False
1459        if self.branch != "master":
1460            if gitBranchExists("refs/remotes/p4/master"):
1461                system("git branch master refs/remotes/p4/master")
1462                system("git checkout -f")
1463            else:
1464                print "Could not detect main branch. No checkout/master branch created."
1465
1466        return True
1467
1468class P4Branches(Command):
1469    def __init__(self):
1470        Command.__init__(self)
1471        self.options = [ ]
1472        self.description = ("Shows the git branches that hold imports and their "
1473                            + "corresponding perforce depot paths")
1474        self.verbose = False
1475
1476    def run(self, args):
1477        cmdline = "git rev-parse --symbolic "
1478        cmdline += " --remotes"
1479
1480        for line in read_pipe_lines(cmdline):
1481            line = line.strip()
1482
1483            if not line.startswith('p4/') or line == "p4/HEAD":
1484                continue
1485            branch = line
1486
1487            log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
1488            settings = extractSettingsGitLog(log)
1489
1490            print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
1491        return True
1492
1493class HelpFormatter(optparse.IndentedHelpFormatter):
1494    def __init__(self):
1495        optparse.IndentedHelpFormatter.__init__(self)
1496
1497    def format_description(self, description):
1498        if description:
1499            return description + "\n"
1500        else:
1501            return ""
1502
1503def printUsage(commands):
1504    print "usage: %s <command> [options]" % sys.argv[0]
1505    print ""
1506    print "valid commands: %s" % ", ".join(commands)
1507    print ""
1508    print "Try %s <command> --help for command specific help." % sys.argv[0]
1509    print ""
1510
1511commands = {
1512    "debug" : P4Debug,
1513    "submit" : P4Submit,
1514    "sync" : P4Sync,
1515    "rebase" : P4Rebase,
1516    "clone" : P4Clone,
1517    "rollback" : P4RollBack,
1518    "branches" : P4Branches
1519}
1520
1521
1522def main():
1523    if len(sys.argv[1:]) == 0:
1524        printUsage(commands.keys())
1525        sys.exit(2)
1526
1527    cmd = ""
1528    cmdName = sys.argv[1]
1529    try:
1530        klass = commands[cmdName]
1531        cmd = klass()
1532    except KeyError:
1533        print "unknown command %s" % cmdName
1534        print ""
1535        printUsage(commands.keys())
1536        sys.exit(2)
1537
1538    options = cmd.options
1539    cmd.gitdir = os.environ.get("GIT_DIR", None)
1540
1541    args = sys.argv[2:]
1542
1543    if len(options) > 0:
1544        options.append(optparse.make_option("--git-dir", dest="gitdir"))
1545
1546        parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1547                                       options,
1548                                       description = cmd.description,
1549                                       formatter = HelpFormatter())
1550
1551        (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1552    global verbose
1553    verbose = cmd.verbose
1554    if cmd.needsGit:
1555        if cmd.gitdir == None:
1556            cmd.gitdir = os.path.abspath(".git")
1557            if not isValidGitDir(cmd.gitdir):
1558                cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1559                if os.path.exists(cmd.gitdir):
1560                    cdup = read_pipe("git rev-parse --show-cdup").strip()
1561                    if len(cdup) > 0:
1562                        os.chdir(cdup);
1563
1564        if not isValidGitDir(cmd.gitdir):
1565            if isValidGitDir(cmd.gitdir + "/.git"):
1566                cmd.gitdir += "/.git"
1567            else:
1568                die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1569
1570        os.environ["GIT_DIR"] = cmd.gitdir
1571
1572    if not cmd.run(args):
1573        parser.print_help()
1574
1575
1576if __name__ == '__main__':
1577    main()