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