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