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