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