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