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