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