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