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