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