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