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