summaryrefslogtreecommitdiff
path: root/contrib/fast-import/p4-git-sync.py
blob: 0c0f629a1d6898147a862b08cbd0bafc94b6da89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/python
#
# p4-git-sync.py
#
# Author: Simon Hausmann <hausmann@kde.org>
# License: MIT <http://www.opensource.org/licenses/mit-license.php>
#

import os, string, shelve, stat
import getopt, sys, marshal

def p4CmdList(cmd):
    cmd = "p4 -G %s" % cmd
    pipe = os.popen(cmd, "rb")

    result = []
    try:
        while True:
            entry = marshal.load(pipe)
            result.append(entry)
    except EOFError:
        pass
    pipe.close()

    return result

def p4Cmd(cmd):
    list = p4CmdList(cmd)
    result = {}
    for entry in list:
        result.update(entry)
    return result;

try:
    opts, args = getopt.getopt(sys.argv[1:], "", [ "continue", "git-dir=", "origin=", "reset", "master=",
                                                   "submit-log-subst=", "log-substitutions=" ])
except getopt.GetoptError:
    print "fixme, syntax error"
    sys.exit(1)

logSubstitutions = {}
logSubstitutions["<enter description here>"] = "%log%"
logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
gitdir = os.environ.get("GIT_DIR", "")
origin = "origin"
master = "master"
firstTime = True
reset = False

for o, a in opts:
    if o == "--git-dir":
        gitdir = a
    elif o == "--origin":
        origin = a
    elif o == "--master":
        master = a
    elif o == "--continue":
        firstTime = False
    elif o == "--reset":
        reset = True
        firstTime = True
    elif o == "--submit-log-subst":
        key = a.split("%")[0]
        value = a.split("%")[1]
        logSubstitutions[key] = value
    elif o == "--log-substitutions":
        for line in open(a, "r").readlines():
            tokens = line[:-1].split("=")
            logSubstitutions[tokens[0]] = tokens[1]

if len(gitdir) == 0:
    gitdir = ".git"
else:
    os.environ["GIT_DIR"] = gitdir

configFile = gitdir + "/p4-git-sync.cfg"

origin = "origin"
if len(args) == 1:
    origin = args[0]

def die(msg):
    sys.stderr.write(msg + "\n")
    sys.exit(1)

def system(cmd):
    if os.system(cmd) != 0:
        die("command failed: %s" % cmd)

def check():
    return
    if len(p4CmdList("opened ...")) > 0:
        die("You have files opened with perforce! Close them before starting the sync.")

def start(config):
    if len(config) > 0 and not reset:
        die("Cannot start sync. Previous sync config found at %s" % configFile)

    #if len(os.popen("git-update-index --refresh").read()) > 0:
    #    die("Your working tree is not clean. Check with git status!")

    commits = []
    for line in os.popen("git-rev-list --no-merges %s..%s" % (origin, master)).readlines():
        commits.append(line[:-1])
    commits.reverse()

    config["commits"] = commits

#    print "Cleaning index..."
#    system("git checkout -f")

def prepareLogMessage(template, message):
    result = ""

    substs = logSubstitutions
    for k in substs.keys():
        substs[k] = substs[k].replace("%log%", message)

    for line in template.split("\n"):
        if line.startswith("#"):
            result += line + "\n"
            continue

        substituted = False
        for key in substs.keys():
            if line.find(key) != -1:
                value = substs[key]
                if value != "@remove@":
                    result += line.replace(key, value) + "\n"
                substituted = True
                break

        if not substituted:
            result += line + "\n"

    return result

def apply(id):
    print "Applying %s" % (os.popen("git-log --max-count=1 --pretty=oneline %s" % id).read())
    diff = os.popen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
    filesToAdd = set()
    filesToDelete = set()
    for line in diff:
        modifier = line[0]
        path = line[1:].strip()
        if modifier == "M":
            system("p4 edit %s" % path)
        elif modifier == "A":
            filesToAdd.add(path)
            if path in filesToDelete:
                filesToDelete.remove(path)
        elif modifier == "D":
            filesToDelete.add(path)
            if path in filesToAdd:
                filesToAdd.remove(path)
        else:
            die("unknown modifier %s for %s" % (modifier, path))

    system("git-diff-files --name-only -z | git-update-index --remove -z --stdin")
    system("git cherry-pick --no-commit \"%s\"" % id)

    for f in filesToAdd:
        system("p4 add %s" % f)
    for f in filesToDelete:
        system("p4 revert %s" % f)
        system("p4 delete %s" % f)

    logMessage = ""
    foundTitle = False
    for log in os.popen("git-cat-file commit %s" % id).readlines():
        log = log[:-1]
        if not foundTitle:
            if len(log) == 0:
                foundTitle = 1
            continue

        if len(logMessage) > 0:
            logMessage += "\t"
        logMessage += log + "\n"

    template = os.popen("p4 change -o").read()
    fileName = "submit.txt"
    file = open(fileName, "w+")
    file.write(prepareLogMessage(template, logMessage))
    file.close()
    print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)

check()

config = shelve.open(configFile, writeback=True)

if firstTime:
    start(config)

commits = config.get("commits", [])

if len(commits) > 0:
    firstTime = False
    commit = commits[0]
    commits = commits[1:]
    config["commits"] = commits
    apply(commit)

config.close()

if len(commits) == 0:
    if firstTime:
        print "No changes found to apply between %s and current HEAD" % origin
    else:
        print "All changes applied!"
    os.remove(configFile)