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