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