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