8982e45345cb120e675285e480c6ceb9c585c801
   1#!/usr/bin/python
   2#
   3# p4-git-sync.py
   4#
   5# Author: Simon Hausmann <hausmann@kde.org>
   6# License: MIT <http://www.opensource.org/licenses/mit-license.php>
   7#
   8
   9import os, string, shelve, stat
  10import getopt, sys, marshal
  11
  12def p4CmdList(cmd):
  13    cmd = "p4 -G %s" % cmd
  14    pipe = os.popen(cmd, "rb")
  15
  16    result = []
  17    try:
  18        while True:
  19            entry = marshal.load(pipe)
  20            result.append(entry)
  21    except EOFError:
  22        pass
  23    pipe.close()
  24
  25    return result
  26
  27def p4Cmd(cmd):
  28    list = p4CmdList(cmd)
  29    result = {}
  30    for entry in list:
  31        result.update(entry)
  32    return result;
  33
  34try:
  35    opts, args = getopt.getopt(sys.argv[1:], "", [ "continue", "--git-dir=", "origin=", "reset", "master=",
  36                                                   "submit-log-subst=" ])
  37except getopt.GetoptError:
  38    print "fixme, syntax error"
  39    sys.exit(1)
  40
  41logSubstitutions = {}
  42logSubstitutions["<enter description here>"] = "%log%"
  43logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
  44gitdir = os.environ.get("GIT_DIR", "")
  45origin = "origin"
  46master = "master"
  47firstTime = True
  48reset = False
  49
  50for o, a in opts:
  51    if o == "--git-dir":
  52        gitdir = a
  53    elif o == "--origin":
  54        origin = a
  55    elif o == "--master":
  56        master = a
  57    elif o == "--continue":
  58        firstTime = False
  59    elif o == "--reset":
  60        reset = True
  61        firstTime = True
  62    elif o == "--submit-log-subst":
  63        key = a.split("%")[0]
  64        value = a.split("%")[1]
  65        logSubstitutions[key] = value
  66
  67if len(gitdir) == 0:
  68    gitdir = ".git"
  69else:
  70    os.environ["GIT_DIR"] = gitdir
  71
  72configFile = gitdir + "/p4-git-sync.cfg"
  73
  74origin = "origin"
  75if len(args) == 1:
  76    origin = args[0]
  77
  78def die(msg):
  79    sys.stderr.write(msg + "\n")
  80    sys.exit(1)
  81
  82def system(cmd):
  83    if os.system(cmd) != 0:
  84        die("command failed: %s" % cmd)
  85
  86def check():
  87    return
  88    if len(p4CmdList("opened ...")) > 0:
  89        die("You have files opened with perforce! Close them before starting the sync.")
  90
  91def start(config):
  92    if len(config) > 0 and not reset:
  93        die("Cannot start sync. Previous sync config found at %s" % configFile)
  94
  95    #if len(os.popen("git-update-index --refresh").read()) > 0:
  96    #    die("Your working tree is not clean. Check with git status!")
  97
  98    commits = []
  99    for line in os.popen("git-rev-list --no-merges %s..%s" % (origin, master)).readlines():
 100        commits.append(line[:-1])
 101    commits.reverse()
 102
 103    config["commits"] = commits
 104
 105#    print "Cleaning index..."
 106#    system("git checkout -f")
 107
 108def prepareLogMessage(template, message):
 109    result = ""
 110
 111    substs = logSubstitutions
 112    for k in substs.keys():
 113        substs[k] = substs[k].replace("%log%", message)
 114
 115    for line in template.split("\n"):
 116        if line.startswith("#"):
 117            result += line + "\n"
 118            continue
 119
 120        substituted = False
 121        for key in substs.keys():
 122            if line.find(key) != -1:
 123                value = substs[key]
 124                if value != "@remove@":
 125                    result += line.replace(key, value) + "\n"
 126                substituted = True
 127                break
 128
 129        if not substituted:
 130            result += line + "\n"
 131
 132    return result
 133
 134def apply(id):
 135    print "Applying %s" % (os.popen("git-log --max-count=1 --pretty=oneline %s" % id).read())
 136    diff = os.popen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
 137    filesToAdd = set()
 138    filesToDelete = set()
 139    for line in diff:
 140        modifier = line[0]
 141        path = line[1:].strip()
 142        if modifier == "M":
 143            system("p4 edit %s" % path)
 144        elif modifier == "A":
 145            filesToAdd.add(path)
 146            if path in filesToDelete:
 147                filesToDelete.remove(path)
 148        elif modifier == "D":
 149            filesToDelete.add(path)
 150            if path in filesToAdd:
 151                filesToAdd.remove(path)
 152        else:
 153            die("unknown modifier %s for %s" % (modifier, path))
 154
 155    system("git-diff-files --name-only -z | git-update-index --remove -z --stdin")
 156    system("git cherry-pick --no-commit \"%s\"" % id)
 157
 158    for f in filesToAdd:
 159        system("p4 add %s" % f)
 160    for f in filesToDelete:
 161        system("p4 revert %s" % f)
 162        system("p4 delete %s" % f)
 163
 164    logMessage = ""
 165    foundTitle = False
 166    for log in os.popen("git-cat-file commit %s" % id).readlines():
 167        log = log[:-1]
 168        if not foundTitle:
 169            if len(log) == 0:
 170                foundTitle = 1
 171            continue
 172
 173        if len(logMessage) > 0:
 174            logMessage += "\t"
 175        logMessage += log + "\n"
 176
 177    template = os.popen("p4 change -o").read()
 178    fileName = "submit.txt"
 179    file = open(fileName, "w+")
 180    file.write(prepareLogMessage(template, logMessage))
 181    file.close()
 182    print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
 183
 184check()
 185
 186config = shelve.open(configFile, writeback=True)
 187
 188if firstTime:
 189    start(config)
 190
 191commits = config.get("commits", [])
 192
 193if len(commits) > 0:
 194    firstTime = False
 195    commit = commits[0]
 196    commits = commits[1:]
 197    config["commits"] = commits
 198    apply(commit)
 199
 200config.close()
 201
 202if len(commits) == 0:
 203    if firstTime:
 204        print "No changes found to apply between %s and current HEAD" % origin
 205    else:
 206        print "All changes applied!"
 207    os.remove(configFile)
 208