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