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