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