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