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