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