]>
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 | # | |
5 | # Author: Simon Hausmann <hausmann@kde.org> | |
83dce55a SH |
6 | # Copyright: 2007 Simon Hausmann <hausmann@kde.org> |
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 |
b984733c | 13 | from sets import Set; |
4f5cf76a SH |
14 | |
15 | gitdir = os.environ.get("GIT_DIR", "") | |
86949eef | 16 | |
caace111 SH |
17 | def mypopen(command): |
18 | return os.popen(command, "rb"); | |
19 | ||
86949eef SH |
20 | def p4CmdList(cmd): |
21 | cmd = "p4 -G %s" % cmd | |
22 | pipe = os.popen(cmd, "rb") | |
23 | ||
24 | result = [] | |
25 | try: | |
26 | while True: | |
27 | entry = marshal.load(pipe) | |
28 | result.append(entry) | |
29 | except EOFError: | |
30 | pass | |
31 | pipe.close() | |
32 | ||
33 | return result | |
34 | ||
35 | def p4Cmd(cmd): | |
36 | list = p4CmdList(cmd) | |
37 | result = {} | |
38 | for entry in list: | |
39 | result.update(entry) | |
40 | return result; | |
41 | ||
cb2c9db5 SH |
42 | def p4Where(depotPath): |
43 | if not depotPath.endswith("/"): | |
44 | depotPath += "/" | |
45 | output = p4Cmd("where %s..." % depotPath) | |
46 | clientPath = "" | |
47 | if "path" in output: | |
48 | clientPath = output.get("path") | |
49 | elif "data" in output: | |
50 | data = output.get("data") | |
51 | lastSpace = data.rfind(" ") | |
52 | clientPath = data[lastSpace + 1:] | |
53 | ||
54 | if clientPath.endswith("..."): | |
55 | clientPath = clientPath[:-3] | |
56 | return clientPath | |
57 | ||
86949eef SH |
58 | def die(msg): |
59 | sys.stderr.write(msg + "\n") | |
60 | sys.exit(1) | |
61 | ||
62 | def currentGitBranch(): | |
caace111 | 63 | return mypopen("git name-rev HEAD").read().split(" ")[1][:-1] |
86949eef | 64 | |
4f5cf76a SH |
65 | def isValidGitDir(path): |
66 | if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"): | |
67 | return True; | |
68 | return False | |
69 | ||
463e8af6 SH |
70 | def parseRevision(ref): |
71 | return mypopen("git rev-parse %s" % ref).read()[:-1] | |
72 | ||
4f5cf76a SH |
73 | def system(cmd): |
74 | if os.system(cmd) != 0: | |
75 | die("command failed: %s" % cmd) | |
76 | ||
6ae8de88 SH |
77 | def extractLogMessageFromGitCommit(commit): |
78 | logMessage = "" | |
79 | foundTitle = False | |
caace111 | 80 | for log in mypopen("git cat-file commit %s" % commit).readlines(): |
6ae8de88 SH |
81 | if not foundTitle: |
82 | if len(log) == 1: | |
1c094184 | 83 | foundTitle = True |
6ae8de88 SH |
84 | continue |
85 | ||
86 | logMessage += log | |
87 | return logMessage | |
88 | ||
89 | def extractDepotPathAndChangeFromGitLog(log): | |
90 | values = {} | |
91 | for line in log.split("\n"): | |
92 | line = line.strip() | |
93 | if line.startswith("[git-p4:") and line.endswith("]"): | |
94 | line = line[8:-1].strip() | |
95 | for assignment in line.split(":"): | |
96 | variable = assignment.strip() | |
97 | value = "" | |
98 | equalPos = assignment.find("=") | |
99 | if equalPos != -1: | |
100 | variable = assignment[:equalPos].strip() | |
101 | value = assignment[equalPos + 1:].strip() | |
102 | if value.startswith("\"") and value.endswith("\""): | |
103 | value = value[1:-1] | |
104 | values[variable] = value | |
105 | ||
106 | return values.get("depot-path"), values.get("change") | |
107 | ||
8136a639 | 108 | def gitBranchExists(branch): |
caace111 SH |
109 | proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE); |
110 | return proc.wait() == 0; | |
8136a639 | 111 | |
b984733c SH |
112 | class Command: |
113 | def __init__(self): | |
114 | self.usage = "usage: %prog [options]" | |
8910ac0e | 115 | self.needsGit = True |
b984733c SH |
116 | |
117 | class P4Debug(Command): | |
86949eef | 118 | def __init__(self): |
6ae8de88 | 119 | Command.__init__(self) |
86949eef SH |
120 | self.options = [ |
121 | ] | |
c8c39116 | 122 | self.description = "A tool to debug the output of p4 -G." |
8910ac0e | 123 | self.needsGit = False |
86949eef SH |
124 | |
125 | def run(self, args): | |
126 | for output in p4CmdList(" ".join(args)): | |
127 | print output | |
b984733c | 128 | return True |
86949eef | 129 | |
711544b0 | 130 | class P4Submit(Command): |
4f5cf76a | 131 | def __init__(self): |
b984733c | 132 | Command.__init__(self) |
4f5cf76a SH |
133 | self.options = [ |
134 | optparse.make_option("--continue", action="store_false", dest="firstTime"), | |
135 | optparse.make_option("--origin", dest="origin"), | |
136 | optparse.make_option("--reset", action="store_true", dest="reset"), | |
4f5cf76a SH |
137 | optparse.make_option("--log-substitutions", dest="substFile"), |
138 | optparse.make_option("--noninteractive", action="store_false"), | |
04219c04 | 139 | optparse.make_option("--dry-run", action="store_true"), |
4f5cf76a SH |
140 | ] |
141 | self.description = "Submit changes from git to the perforce depot." | |
c9b50e63 | 142 | self.usage += " [name of git branch to submit into perforce depot]" |
4f5cf76a SH |
143 | self.firstTime = True |
144 | self.reset = False | |
145 | self.interactive = True | |
146 | self.dryRun = False | |
147 | self.substFile = "" | |
148 | self.firstTime = True | |
9512497b | 149 | self.origin = "" |
4f5cf76a SH |
150 | |
151 | self.logSubstitutions = {} | |
152 | self.logSubstitutions["<enter description here>"] = "%log%" | |
153 | self.logSubstitutions["\tDetails:"] = "\tDetails: %log%" | |
154 | ||
155 | def check(self): | |
156 | if len(p4CmdList("opened ...")) > 0: | |
157 | die("You have files opened with perforce! Close them before starting the sync.") | |
158 | ||
159 | def start(self): | |
160 | if len(self.config) > 0 and not self.reset: | |
c3c46244 | 161 | die("Cannot start sync. Previous sync config found at %s\nIf you want to start submitting again from scratch maybe you want to call git-p4 submit --reset" % self.configFile) |
4f5cf76a SH |
162 | |
163 | commits = [] | |
caace111 | 164 | for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines(): |
4f5cf76a SH |
165 | commits.append(line[:-1]) |
166 | commits.reverse() | |
167 | ||
168 | self.config["commits"] = commits | |
169 | ||
4f5cf76a SH |
170 | def prepareLogMessage(self, template, message): |
171 | result = "" | |
172 | ||
173 | for line in template.split("\n"): | |
174 | if line.startswith("#"): | |
175 | result += line + "\n" | |
176 | continue | |
177 | ||
178 | substituted = False | |
179 | for key in self.logSubstitutions.keys(): | |
180 | if line.find(key) != -1: | |
181 | value = self.logSubstitutions[key] | |
182 | value = value.replace("%log%", message) | |
183 | if value != "@remove@": | |
184 | result += line.replace(key, value) + "\n" | |
185 | substituted = True | |
186 | break | |
187 | ||
188 | if not substituted: | |
189 | result += line + "\n" | |
190 | ||
191 | return result | |
192 | ||
193 | def apply(self, id): | |
caace111 SH |
194 | print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read()) |
195 | diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines() | |
4f5cf76a SH |
196 | filesToAdd = set() |
197 | filesToDelete = set() | |
d336c158 | 198 | editedFiles = set() |
4f5cf76a SH |
199 | for line in diff: |
200 | modifier = line[0] | |
201 | path = line[1:].strip() | |
202 | if modifier == "M": | |
d336c158 SH |
203 | system("p4 edit \"%s\"" % path) |
204 | editedFiles.add(path) | |
4f5cf76a SH |
205 | elif modifier == "A": |
206 | filesToAdd.add(path) | |
207 | if path in filesToDelete: | |
208 | filesToDelete.remove(path) | |
209 | elif modifier == "D": | |
210 | filesToDelete.add(path) | |
211 | if path in filesToAdd: | |
212 | filesToAdd.remove(path) | |
213 | else: | |
214 | die("unknown modifier %s for %s" % (modifier, path)) | |
215 | ||
47a130b7 SH |
216 | diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id) |
217 | patchcmd = diffcmd + " | git apply " | |
218 | tryPatchCmd = diffcmd + "--check -" | |
219 | applyPatchCmd = diffcmd + "--check --apply -" | |
220 | print mypopen(diffcmd).read() | |
51a2640a | 221 | |
47a130b7 | 222 | if os.system(tryPatchCmd) != 0: |
51a2640a SH |
223 | print "Unfortunately applying the change failed!" |
224 | print "What do you want to do?" | |
225 | response = "x" | |
226 | while response != "s" and response != "a" and response != "w": | |
227 | response = raw_input("[s]kip this patch / [a]pply the patch forcibly and with .rej files / [w]rite the patch to a file (patch.txt) ") | |
228 | if response == "s": | |
229 | print "Skipping! Good luck with the next patches..." | |
230 | return | |
231 | elif response == "a": | |
47a130b7 | 232 | os.system(applyPatchCmd) |
51a2640a SH |
233 | if len(filesToAdd) > 0: |
234 | print "You may also want to call p4 add on the following files:" | |
235 | print " ".join(filesToAdd) | |
236 | if len(filesToDelete): | |
237 | print "The following files should be scheduled for deletion with p4 delete:" | |
238 | print " ".join(filesToDelete) | |
239 | die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue") | |
240 | elif response == "w": | |
241 | system(diffcmd + " > patch.txt") | |
242 | print "Patch saved to patch.txt in %s !" % self.clientPath | |
243 | die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue") | |
244 | ||
47a130b7 | 245 | system(applyPatchCmd) |
4f5cf76a SH |
246 | |
247 | for f in filesToAdd: | |
248 | system("p4 add %s" % f) | |
249 | for f in filesToDelete: | |
250 | system("p4 revert %s" % f) | |
251 | system("p4 delete %s" % f) | |
252 | ||
6ae8de88 SH |
253 | logMessage = extractLogMessageFromGitCommit(id) |
254 | logMessage = logMessage.replace("\n", "\n\t") | |
255 | logMessage = logMessage[:-1] | |
4f5cf76a | 256 | |
caace111 | 257 | template = mypopen("p4 change -o").read() |
4f5cf76a SH |
258 | |
259 | if self.interactive: | |
260 | submitTemplate = self.prepareLogMessage(template, logMessage) | |
caace111 | 261 | diff = mypopen("p4 diff -du ...").read() |
4f5cf76a SH |
262 | |
263 | for newFile in filesToAdd: | |
264 | diff += "==== new file ====\n" | |
265 | diff += "--- /dev/null\n" | |
266 | diff += "+++ %s\n" % newFile | |
267 | f = open(newFile, "r") | |
268 | for line in f.readlines(): | |
269 | diff += "+" + line | |
270 | f.close() | |
271 | ||
25df95cc SH |
272 | separatorLine = "######## everything below this line is just the diff #######" |
273 | if platform.system() == "Windows": | |
274 | separatorLine += "\r" | |
275 | separatorLine += "\n" | |
4f5cf76a SH |
276 | |
277 | response = "e" | |
53150250 | 278 | firstIteration = True |
4f5cf76a | 279 | while response == "e": |
53150250 | 280 | if not firstIteration: |
d336c158 | 281 | response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ") |
53150250 | 282 | firstIteration = False |
4f5cf76a SH |
283 | if response == "e": |
284 | [handle, fileName] = tempfile.mkstemp() | |
285 | tmpFile = os.fdopen(handle, "w+") | |
53150250 | 286 | tmpFile.write(submitTemplate + separatorLine + diff) |
4f5cf76a | 287 | tmpFile.close() |
25df95cc SH |
288 | defaultEditor = "vi" |
289 | if platform.system() == "Windows": | |
290 | defaultEditor = "notepad" | |
291 | editor = os.environ.get("EDITOR", defaultEditor); | |
4f5cf76a | 292 | system(editor + " " + fileName) |
25df95cc | 293 | tmpFile = open(fileName, "rb") |
53150250 | 294 | message = tmpFile.read() |
4f5cf76a SH |
295 | tmpFile.close() |
296 | os.remove(fileName) | |
53150250 | 297 | submitTemplate = message[:message.index(separatorLine)] |
4f5cf76a SH |
298 | |
299 | if response == "y" or response == "yes": | |
300 | if self.dryRun: | |
301 | print submitTemplate | |
302 | raw_input("Press return to continue...") | |
303 | else: | |
25df95cc | 304 | pipe = os.popen("p4 submit -i", "wb") |
4f5cf76a SH |
305 | pipe.write(submitTemplate) |
306 | pipe.close() | |
d336c158 SH |
307 | elif response == "s": |
308 | for f in editedFiles: | |
309 | system("p4 revert \"%s\"" % f); | |
310 | for f in filesToAdd: | |
311 | system("p4 revert \"%s\"" % f); | |
312 | system("rm %s" %f) | |
313 | for f in filesToDelete: | |
314 | system("p4 delete \"%s\"" % f); | |
315 | return | |
4f5cf76a SH |
316 | else: |
317 | print "Not submitting!" | |
318 | self.interactive = False | |
319 | else: | |
320 | fileName = "submit.txt" | |
321 | file = open(fileName, "w+") | |
322 | file.write(self.prepareLogMessage(template, logMessage)) | |
323 | file.close() | |
324 | print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName) | |
325 | ||
326 | def run(self, args): | |
9512497b SH |
327 | global gitdir |
328 | # make gitdir absolute so we can cd out into the perforce checkout | |
329 | gitdir = os.path.abspath(gitdir) | |
330 | os.environ["GIT_DIR"] = gitdir | |
c9b50e63 SH |
331 | |
332 | if len(args) == 0: | |
333 | self.master = currentGitBranch() | |
334 | if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)): | |
335 | die("Detecting current git branch failed!") | |
336 | elif len(args) == 1: | |
337 | self.master = args[0] | |
338 | else: | |
339 | return False | |
340 | ||
9512497b SH |
341 | depotPath = "" |
342 | if gitBranchExists("p4"): | |
343 | [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4")) | |
344 | if len(depotPath) == 0 and gitBranchExists("origin"): | |
345 | [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin")) | |
346 | ||
347 | if len(depotPath) == 0: | |
348 | print "Internal error: cannot locate perforce depot path from existing branches" | |
349 | sys.exit(128) | |
350 | ||
51a2640a | 351 | self.clientPath = p4Where(depotPath) |
9512497b | 352 | |
51a2640a | 353 | if len(self.clientPath) == 0: |
9512497b SH |
354 | print "Error: Cannot locate perforce checkout of %s in client view" % depotPath |
355 | sys.exit(128) | |
356 | ||
51a2640a | 357 | print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath) |
80b5910f | 358 | oldWorkingDirectory = os.getcwd() |
51a2640a SH |
359 | os.chdir(self.clientPath) |
360 | response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath) | |
9512497b SH |
361 | if response == "y" or response == "yes": |
362 | system("p4 sync ...") | |
363 | ||
364 | if len(self.origin) == 0: | |
365 | if gitBranchExists("p4"): | |
366 | self.origin = "p4" | |
367 | else: | |
368 | self.origin = "origin" | |
369 | ||
4f5cf76a SH |
370 | if self.reset: |
371 | self.firstTime = True | |
372 | ||
373 | if len(self.substFile) > 0: | |
374 | for line in open(self.substFile, "r").readlines(): | |
375 | tokens = line[:-1].split("=") | |
376 | self.logSubstitutions[tokens[0]] = tokens[1] | |
377 | ||
4f5cf76a SH |
378 | self.check() |
379 | self.configFile = gitdir + "/p4-git-sync.cfg" | |
380 | self.config = shelve.open(self.configFile, writeback=True) | |
381 | ||
382 | if self.firstTime: | |
383 | self.start() | |
384 | ||
385 | commits = self.config.get("commits", []) | |
386 | ||
387 | while len(commits) > 0: | |
388 | self.firstTime = False | |
389 | commit = commits[0] | |
390 | commits = commits[1:] | |
391 | self.config["commits"] = commits | |
392 | self.apply(commit) | |
393 | if not self.interactive: | |
394 | break | |
395 | ||
396 | self.config.close() | |
397 | ||
398 | if len(commits) == 0: | |
399 | if self.firstTime: | |
400 | print "No changes found to apply between %s and current HEAD" % self.origin | |
401 | else: | |
402 | print "All changes applied!" | |
5e80dd4d | 403 | response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ") |
80b5910f SH |
404 | if response == "y" or response == "yes": |
405 | os.chdir(oldWorkingDirectory) | |
406 | rebase = P4Rebase() | |
407 | rebase.run([]) | |
4f5cf76a SH |
408 | os.remove(self.configFile) |
409 | ||
b984733c SH |
410 | return True |
411 | ||
711544b0 | 412 | class P4Sync(Command): |
b984733c SH |
413 | def __init__(self): |
414 | Command.__init__(self) | |
415 | self.options = [ | |
416 | optparse.make_option("--branch", dest="branch"), | |
417 | optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"), | |
418 | optparse.make_option("--changesfile", dest="changesFile"), | |
419 | optparse.make_option("--silent", dest="silent", action="store_true"), | |
ef48f909 | 420 | optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"), |
4b97ffb1 SH |
421 | optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"), |
422 | optparse.make_option("--verbose", dest="verbose", action="store_true") | |
b984733c SH |
423 | ] |
424 | self.description = """Imports from Perforce into a git repository.\n | |
425 | example: | |
426 | //depot/my/project/ -- to import the current head | |
427 | //depot/my/project/@all -- to import everything | |
428 | //depot/my/project/@1,6 -- to import only from revision 1 to 6 | |
429 | ||
430 | (a ... is not needed in the path p4 specification, it's added implicitly)""" | |
431 | ||
432 | self.usage += " //depot/path[@revRange]" | |
433 | ||
b984733c | 434 | self.silent = False |
b984733c SH |
435 | self.createdBranches = Set() |
436 | self.committedChanges = Set() | |
569d1bd4 | 437 | self.branch = "" |
b984733c | 438 | self.detectBranches = False |
cb53e1f8 | 439 | self.detectLabels = False |
b984733c | 440 | self.changesFile = "" |
ef48f909 | 441 | self.syncWithOrigin = False |
4b97ffb1 | 442 | self.verbose = False |
b984733c SH |
443 | |
444 | def p4File(self, depotPath): | |
445 | return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read() | |
446 | ||
447 | def extractFilesFromCommit(self, commit): | |
448 | files = [] | |
449 | fnum = 0 | |
450 | while commit.has_key("depotFile%s" % fnum): | |
451 | path = commit["depotFile%s" % fnum] | |
8f872531 | 452 | if not path.startswith(self.depotPath): |
b984733c | 453 | # if not self.silent: |
8f872531 | 454 | # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change) |
b984733c SH |
455 | fnum = fnum + 1 |
456 | continue | |
457 | ||
458 | file = {} | |
459 | file["path"] = path | |
460 | file["rev"] = commit["rev%s" % fnum] | |
461 | file["action"] = commit["action%s" % fnum] | |
462 | file["type"] = commit["type%s" % fnum] | |
463 | files.append(file) | |
464 | fnum = fnum + 1 | |
465 | return files | |
466 | ||
71b112d4 | 467 | def splitFilesIntoBranches(self, commit): |
d5904674 | 468 | branches = {} |
b984733c | 469 | |
71b112d4 SH |
470 | fnum = 0 |
471 | while commit.has_key("depotFile%s" % fnum): | |
472 | path = commit["depotFile%s" % fnum] | |
473 | if not path.startswith(self.depotPath): | |
474 | # if not self.silent: | |
475 | # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change) | |
476 | fnum = fnum + 1 | |
477 | continue | |
478 | ||
479 | file = {} | |
480 | file["path"] = path | |
481 | file["rev"] = commit["rev%s" % fnum] | |
482 | file["action"] = commit["action%s" % fnum] | |
483 | file["type"] = commit["type%s" % fnum] | |
484 | fnum = fnum + 1 | |
485 | ||
486 | relPath = path[len(self.depotPath):] | |
b984733c | 487 | |
4b97ffb1 | 488 | for branch in self.knownBranches.keys(): |
71b112d4 | 489 | if relPath.startswith(branch): |
d5904674 SH |
490 | if branch not in branches: |
491 | branches[branch] = [] | |
71b112d4 | 492 | branches[branch].append(file) |
b984733c SH |
493 | |
494 | return branches | |
495 | ||
4b97ffb1 | 496 | def commit(self, details, files, branch, branchPrefix, parent = ""): |
b984733c SH |
497 | epoch = details["time"] |
498 | author = details["user"] | |
499 | ||
4b97ffb1 SH |
500 | if self.verbose: |
501 | print "commit into %s" % branch | |
502 | ||
b984733c SH |
503 | self.gitStream.write("commit %s\n" % branch) |
504 | # gitStream.write("mark :%s\n" % details["change"]) | |
505 | self.committedChanges.add(int(details["change"])) | |
506 | committer = "" | |
b607e71e SH |
507 | if author not in self.users: |
508 | self.getUserMapFromPerforceServer() | |
b984733c | 509 | if author in self.users: |
0828ab14 | 510 | committer = "%s %s %s" % (self.users[author], epoch, self.tz) |
b984733c | 511 | else: |
0828ab14 | 512 | committer = "%s <a@b> %s %s" % (author, epoch, self.tz) |
b984733c SH |
513 | |
514 | self.gitStream.write("committer %s\n" % committer) | |
515 | ||
516 | self.gitStream.write("data <<EOT\n") | |
517 | self.gitStream.write(details["desc"]) | |
6ae8de88 | 518 | self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"])) |
b984733c SH |
519 | self.gitStream.write("EOT\n\n") |
520 | ||
521 | if len(parent) > 0: | |
4b97ffb1 SH |
522 | if self.verbose: |
523 | print "parent %s" % parent | |
b984733c SH |
524 | self.gitStream.write("from %s\n" % parent) |
525 | ||
b984733c SH |
526 | for file in files: |
527 | path = file["path"] | |
528 | if not path.startswith(branchPrefix): | |
529 | # if not silent: | |
530 | # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"]) | |
531 | continue | |
532 | rev = file["rev"] | |
533 | depotPath = path + "#" + rev | |
534 | relPath = path[len(branchPrefix):] | |
535 | action = file["action"] | |
536 | ||
537 | if file["type"] == "apple": | |
538 | print "\nfile %s is a strange apple file that forks. Ignoring!" % path | |
539 | continue | |
540 | ||
541 | if action == "delete": | |
542 | self.gitStream.write("D %s\n" % relPath) | |
543 | else: | |
544 | mode = 644 | |
545 | if file["type"].startswith("x"): | |
546 | mode = 755 | |
547 | ||
548 | data = self.p4File(depotPath) | |
549 | ||
550 | self.gitStream.write("M %s inline %s\n" % (mode, relPath)) | |
551 | self.gitStream.write("data %s\n" % len(data)) | |
552 | self.gitStream.write(data) | |
553 | self.gitStream.write("\n") | |
554 | ||
555 | self.gitStream.write("\n") | |
556 | ||
1f4ba1cb SH |
557 | change = int(details["change"]) |
558 | ||
9bda3a85 | 559 | if self.labels.has_key(change): |
1f4ba1cb SH |
560 | label = self.labels[change] |
561 | labelDetails = label[0] | |
562 | labelRevisions = label[1] | |
71b112d4 SH |
563 | if self.verbose: |
564 | print "Change %s is labelled %s" % (change, labelDetails) | |
1f4ba1cb SH |
565 | |
566 | files = p4CmdList("files %s...@%s" % (branchPrefix, change)) | |
567 | ||
568 | if len(files) == len(labelRevisions): | |
569 | ||
570 | cleanedFiles = {} | |
571 | for info in files: | |
572 | if info["action"] == "delete": | |
573 | continue | |
574 | cleanedFiles[info["depotFile"]] = info["rev"] | |
575 | ||
576 | if cleanedFiles == labelRevisions: | |
577 | self.gitStream.write("tag tag_%s\n" % labelDetails["label"]) | |
578 | self.gitStream.write("from %s\n" % branch) | |
579 | ||
580 | owner = labelDetails["Owner"] | |
581 | tagger = "" | |
582 | if author in self.users: | |
583 | tagger = "%s %s %s" % (self.users[owner], epoch, self.tz) | |
584 | else: | |
585 | tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz) | |
586 | self.gitStream.write("tagger %s\n" % tagger) | |
587 | self.gitStream.write("data <<EOT\n") | |
588 | self.gitStream.write(labelDetails["Description"]) | |
589 | self.gitStream.write("EOT\n\n") | |
590 | ||
591 | else: | |
a46668fa | 592 | if not self.silent: |
1f4ba1cb SH |
593 | print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change) |
594 | ||
595 | else: | |
a46668fa | 596 | if not self.silent: |
1f4ba1cb | 597 | print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change) |
b984733c | 598 | |
b607e71e | 599 | def getUserMapFromPerforceServer(self): |
b984733c SH |
600 | self.users = {} |
601 | ||
602 | for output in p4CmdList("users"): | |
603 | if not output.has_key("User"): | |
604 | continue | |
605 | self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">" | |
606 | ||
b607e71e SH |
607 | cache = open(gitdir + "/p4-usercache.txt", "wb") |
608 | for user in self.users.keys(): | |
609 | cache.write("%s\t%s\n" % (user, self.users[user])) | |
610 | cache.close(); | |
611 | ||
612 | def loadUserMapFromCache(self): | |
613 | self.users = {} | |
614 | try: | |
615 | cache = open(gitdir + "/p4-usercache.txt", "rb") | |
616 | lines = cache.readlines() | |
617 | cache.close() | |
618 | for line in lines: | |
619 | entry = line[:-1].split("\t") | |
620 | self.users[entry[0]] = entry[1] | |
621 | except IOError: | |
622 | self.getUserMapFromPerforceServer() | |
623 | ||
1f4ba1cb SH |
624 | def getLabels(self): |
625 | self.labels = {} | |
626 | ||
8f872531 | 627 | l = p4CmdList("labels %s..." % self.depotPath) |
10c3211b | 628 | if len(l) > 0 and not self.silent: |
8f872531 | 629 | print "Finding files belonging to labels in %s" % self.depotPath |
01ce1fe9 SH |
630 | |
631 | for output in l: | |
1f4ba1cb SH |
632 | label = output["label"] |
633 | revisions = {} | |
634 | newestChange = 0 | |
71b112d4 SH |
635 | if self.verbose: |
636 | print "Querying files for label %s" % label | |
637 | for file in p4CmdList("files %s...@%s" % (self.depotPath, label)): | |
1f4ba1cb SH |
638 | revisions[file["depotFile"]] = file["rev"] |
639 | change = int(file["change"]) | |
640 | if change > newestChange: | |
641 | newestChange = change | |
642 | ||
9bda3a85 SH |
643 | self.labels[newestChange] = [output, revisions] |
644 | ||
645 | if self.verbose: | |
646 | print "Label changes: %s" % self.labels.keys() | |
1f4ba1cb | 647 | |
4b97ffb1 | 648 | def getBranchMapping(self): |
29bdbac1 | 649 | self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:] |
4b97ffb1 SH |
650 | |
651 | for info in p4CmdList("branches"): | |
652 | details = p4Cmd("branch -o %s" % info["branch"]) | |
653 | viewIdx = 0 | |
654 | while details.has_key("View%s" % viewIdx): | |
655 | paths = details["View%s" % viewIdx].split(" ") | |
656 | viewIdx = viewIdx + 1 | |
657 | # require standard //depot/foo/... //depot/bar/... mapping | |
658 | if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."): | |
659 | continue | |
660 | source = paths[0] | |
661 | destination = paths[1] | |
662 | if source.startswith(self.depotPath) and destination.startswith(self.depotPath): | |
663 | source = source[len(self.depotPath):-4] | |
664 | destination = destination[len(self.depotPath):-4] | |
29bdbac1 SH |
665 | if destination not in self.knownBranches: |
666 | self.knownBranches[destination] = source | |
667 | if source not in self.knownBranches: | |
668 | self.knownBranches[source] = source | |
669 | ||
670 | def listExistingP4GitBranches(self): | |
671 | self.p4BranchesInGit = [] | |
672 | ||
673 | for line in mypopen("git rev-parse --symbolic --remotes").readlines(): | |
674 | if line.startswith("p4/") and line != "p4/HEAD\n": | |
675 | branch = line[3:-1] | |
676 | self.p4BranchesInGit.append(branch) | |
677 | self.initialParents["refs/remotes/p4/" + branch] = parseRevision(line[:-1]) | |
4b97ffb1 | 678 | |
b984733c | 679 | def run(self, args): |
8f872531 | 680 | self.depotPath = "" |
179caebf SH |
681 | self.changeRange = "" |
682 | self.initialParent = "" | |
cd6cc0d3 | 683 | self.previousDepotPath = "" |
29bdbac1 SH |
684 | # map from branch depot path to parent branch |
685 | self.knownBranches = {} | |
686 | self.initialParents = {} | |
687 | ||
688 | self.listExistingP4GitBranches() | |
689 | ||
690 | if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self.detectBranches: | |
691 | ### needs to be ported to multi branch import | |
179caebf | 692 | |
ef48f909 SH |
693 | print "Syncing with origin first as requested by calling git fetch origin" |
694 | system("git fetch origin") | |
695 | [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin")) | |
696 | [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4")) | |
697 | if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0: | |
698 | if originPreviousDepotPath == p4PreviousDepotPath: | |
699 | originP4Change = int(originP4Change) | |
700 | p4Change = int(p4Change) | |
701 | if originP4Change > p4Change: | |
702 | print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change) | |
703 | system("git update-ref refs/remotes/p4/master origin"); | |
704 | else: | |
705 | print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath) | |
706 | ||
569d1bd4 | 707 | if len(self.branch) == 0: |
48df6fd8 | 708 | self.branch = "refs/remotes/p4/master" |
c6d44cb1 | 709 | if gitBranchExists("refs/heads/p4"): |
48df6fd8 | 710 | system("git update-ref %s refs/heads/p4" % self.branch) |
48df6fd8 | 711 | system("git branch -D p4"); |
05094f98 SH |
712 | if not gitBranchExists("refs/remotes/p4/HEAD"): |
713 | system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch) | |
967f72e2 SH |
714 | |
715 | if len(args) == 0: | |
29bdbac1 SH |
716 | if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches: |
717 | ### needs to be ported to multi branch import | |
967f72e2 SH |
718 | if not self.silent: |
719 | print "Creating %s branch in git repository based on origin" % self.branch | |
8ead4fda SH |
720 | branch = self.branch |
721 | if not branch.startswith("refs"): | |
722 | branch = "refs/heads/" + branch | |
723 | system("git update-ref %s origin" % branch) | |
967f72e2 | 724 | |
29bdbac1 SH |
725 | if self.verbose: |
726 | print "branches: %s" % self.p4BranchesInGit | |
727 | ||
728 | p4Change = 0 | |
729 | for branch in self.p4BranchesInGit: | |
730 | depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch)) | |
731 | ||
732 | if self.verbose: | |
733 | print "path %s change %s" % (depotPath, change) | |
734 | ||
735 | if len(depotPath) > 0 and len(change) > 0: | |
736 | change = int(change) + 1 | |
737 | p4Change = max(p4Change, change) | |
738 | ||
739 | if len(self.previousDepotPath) == 0: | |
740 | self.previousDepotPath = depotPath | |
741 | else: | |
742 | i = 0 | |
743 | l = min(len(self.previousDepotPath), len(depotPath)) | |
744 | while i < l and self.previousDepotPath[i] == depotPath[i]: | |
745 | i = i + 1 | |
746 | self.previousDepotPath = self.previousDepotPath[:i] | |
747 | ||
748 | if p4Change > 0: | |
8f872531 | 749 | self.depotPath = self.previousDepotPath |
d5904674 | 750 | self.changeRange = "@%s,#head" % p4Change |
463e8af6 | 751 | self.initialParent = parseRevision(self.branch) |
967f72e2 SH |
752 | if not self.silent: |
753 | print "Performing incremental import into %s git branch" % self.branch | |
569d1bd4 | 754 | |
f9162f6a SH |
755 | if not self.branch.startswith("refs/"): |
756 | self.branch = "refs/heads/" + self.branch | |
179caebf | 757 | |
8f872531 SH |
758 | if len(self.depotPath) != 0: |
759 | self.depotPath = self.depotPath[:-1] | |
b984733c | 760 | |
8f872531 | 761 | if len(args) == 0 and len(self.depotPath) != 0: |
b984733c | 762 | if not self.silent: |
8f872531 | 763 | print "Depot path: %s" % self.depotPath |
b984733c SH |
764 | elif len(args) != 1: |
765 | return False | |
766 | else: | |
8f872531 SH |
767 | if len(self.depotPath) != 0 and self.depotPath != args[0]: |
768 | print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0]) | |
b984733c | 769 | sys.exit(1) |
8f872531 | 770 | self.depotPath = args[0] |
b984733c | 771 | |
b984733c SH |
772 | self.revision = "" |
773 | self.users = {} | |
b984733c | 774 | |
8f872531 SH |
775 | if self.depotPath.find("@") != -1: |
776 | atIdx = self.depotPath.index("@") | |
777 | self.changeRange = self.depotPath[atIdx:] | |
b984733c SH |
778 | if self.changeRange == "@all": |
779 | self.changeRange = "" | |
780 | elif self.changeRange.find(",") == -1: | |
781 | self.revision = self.changeRange | |
782 | self.changeRange = "" | |
8f872531 SH |
783 | self.depotPath = self.depotPath[0:atIdx] |
784 | elif self.depotPath.find("#") != -1: | |
785 | hashIdx = self.depotPath.index("#") | |
786 | self.revision = self.depotPath[hashIdx:] | |
787 | self.depotPath = self.depotPath[0:hashIdx] | |
b984733c SH |
788 | elif len(self.previousDepotPath) == 0: |
789 | self.revision = "#head" | |
790 | ||
8f872531 SH |
791 | if self.depotPath.endswith("..."): |
792 | self.depotPath = self.depotPath[:-3] | |
b984733c | 793 | |
8f872531 SH |
794 | if not self.depotPath.endswith("/"): |
795 | self.depotPath += "/" | |
b984733c | 796 | |
b607e71e | 797 | self.loadUserMapFromCache() |
cb53e1f8 SH |
798 | self.labels = {} |
799 | if self.detectLabels: | |
800 | self.getLabels(); | |
b984733c | 801 | |
4b97ffb1 SH |
802 | if self.detectBranches: |
803 | self.getBranchMapping(); | |
29bdbac1 SH |
804 | if self.verbose: |
805 | print "p4-git branches: %s" % self.p4BranchesInGit | |
806 | print "initial parents: %s" % self.initialParents | |
807 | for b in self.p4BranchesInGit: | |
808 | if b != "master": | |
809 | b = b[len(self.projectName):] | |
810 | self.createdBranches.add(b) | |
4b97ffb1 | 811 | |
f291b4e3 | 812 | self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60)) |
b984733c | 813 | |
08483580 SH |
814 | importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE); |
815 | self.gitOutput = importProcess.stdout | |
816 | self.gitStream = importProcess.stdin | |
817 | self.gitError = importProcess.stderr | |
b984733c SH |
818 | |
819 | if len(self.revision) > 0: | |
8f872531 | 820 | print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision) |
b984733c SH |
821 | |
822 | details = { "user" : "git perforce import user", "time" : int(time.time()) } | |
8f872531 | 823 | details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision) |
b984733c SH |
824 | details["change"] = self.revision |
825 | newestRevision = 0 | |
826 | ||
827 | fileCnt = 0 | |
8f872531 | 828 | for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)): |
b984733c SH |
829 | change = int(info["change"]) |
830 | if change > newestRevision: | |
831 | newestRevision = change | |
832 | ||
833 | if info["action"] == "delete": | |
c45b1cfe SH |
834 | # don't increase the file cnt, otherwise details["depotFile123"] will have gaps! |
835 | #fileCnt = fileCnt + 1 | |
b984733c SH |
836 | continue |
837 | ||
838 | for prop in [ "depotFile", "rev", "action", "type" ]: | |
839 | details["%s%s" % (prop, fileCnt)] = info[prop] | |
840 | ||
841 | fileCnt = fileCnt + 1 | |
842 | ||
843 | details["change"] = newestRevision | |
844 | ||
845 | try: | |
8f872531 | 846 | self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath) |
c715706b | 847 | except IOError: |
fd4ca86a | 848 | print "IO error with git fast-import. Is your git version recent enough?" |
b984733c SH |
849 | print self.gitError.read() |
850 | ||
851 | else: | |
852 | changes = [] | |
853 | ||
0828ab14 | 854 | if len(self.changesFile) > 0: |
b984733c SH |
855 | output = open(self.changesFile).readlines() |
856 | changeSet = Set() | |
857 | for line in output: | |
858 | changeSet.add(int(line)) | |
859 | ||
860 | for change in changeSet: | |
861 | changes.append(change) | |
862 | ||
863 | changes.sort() | |
864 | else: | |
29bdbac1 SH |
865 | if self.verbose: |
866 | print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange) | |
caace111 | 867 | output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines() |
b984733c SH |
868 | |
869 | for line in output: | |
870 | changeNum = line.split(" ")[1] | |
871 | changes.append(changeNum) | |
872 | ||
873 | changes.reverse() | |
874 | ||
875 | if len(changes) == 0: | |
0828ab14 | 876 | if not self.silent: |
b984733c | 877 | print "no changes to import!" |
1f52af6c | 878 | return True |
b984733c SH |
879 | |
880 | cnt = 1 | |
881 | for change in changes: | |
882 | description = p4Cmd("describe %s" % change) | |
883 | ||
0828ab14 | 884 | if not self.silent: |
b984733c SH |
885 | sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes))) |
886 | sys.stdout.flush() | |
887 | cnt = cnt + 1 | |
888 | ||
889 | try: | |
b984733c | 890 | if self.detectBranches: |
71b112d4 | 891 | branches = self.splitFilesIntoBranches(description) |
d5904674 | 892 | for branch in branches.keys(): |
8f872531 | 893 | branchPrefix = self.depotPath + branch + "/" |
b984733c | 894 | |
b984733c | 895 | parent = "" |
4b97ffb1 | 896 | |
d5904674 | 897 | filesForCommit = branches[branch] |
4b97ffb1 | 898 | |
29bdbac1 SH |
899 | if self.verbose: |
900 | print "branch is %s" % branch | |
901 | ||
8f9b2e08 | 902 | if branch not in self.createdBranches: |
b984733c | 903 | self.createdBranches.add(branch) |
4b97ffb1 | 904 | parent = self.knownBranches[branch] |
b984733c SH |
905 | if parent == branch: |
906 | parent = "" | |
29bdbac1 SH |
907 | elif self.verbose: |
908 | print "parent determined through known branches: %s" % parent | |
b984733c | 909 | |
8f9b2e08 SH |
910 | # main branch? use master |
911 | if branch == "main": | |
912 | branch = "master" | |
913 | else: | |
29bdbac1 | 914 | branch = self.projectName + branch |
8f9b2e08 SH |
915 | |
916 | if parent == "main": | |
917 | parent = "master" | |
918 | elif len(parent) > 0: | |
29bdbac1 | 919 | parent = self.projectName + parent |
8f9b2e08 | 920 | |
4b97ffb1 | 921 | branch = "refs/remotes/p4/" + branch |
b984733c | 922 | if len(parent) > 0: |
4b97ffb1 | 923 | parent = "refs/remotes/p4/" + parent |
29bdbac1 SH |
924 | |
925 | if self.verbose: | |
926 | print "looking for initial parent for %s; current parent is %s" % (branch, parent) | |
927 | ||
928 | if len(parent) == 0 and branch in self.initialParents: | |
929 | parent = self.initialParents[branch] | |
930 | del self.initialParents[branch] | |
931 | ||
71b112d4 | 932 | self.commit(description, filesForCommit, branch, branchPrefix, parent) |
b984733c | 933 | else: |
71b112d4 | 934 | files = self.extractFilesFromCommit(description) |
8f872531 | 935 | self.commit(description, files, self.branch, self.depotPath, self.initialParent) |
b984733c SH |
936 | self.initialParent = "" |
937 | except IOError: | |
938 | print self.gitError.read() | |
939 | sys.exit(1) | |
940 | ||
941 | if not self.silent: | |
942 | print "" | |
943 | ||
b984733c SH |
944 | |
945 | self.gitStream.close() | |
29bdbac1 SH |
946 | if importProcess.wait() != 0: |
947 | die("fast-import failed: %s" % self.gitError.read()) | |
b984733c SH |
948 | self.gitOutput.close() |
949 | self.gitError.close() | |
950 | ||
b984733c SH |
951 | return True |
952 | ||
01ce1fe9 SH |
953 | class P4Rebase(Command): |
954 | def __init__(self): | |
955 | Command.__init__(self) | |
ef48f909 | 956 | self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ] |
01ce1fe9 | 957 | self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it" |
ef48f909 | 958 | self.syncWithOrigin = False |
01ce1fe9 SH |
959 | |
960 | def run(self, args): | |
961 | sync = P4Sync() | |
ef48f909 | 962 | sync.syncWithOrigin = self.syncWithOrigin |
01ce1fe9 SH |
963 | sync.run([]) |
964 | print "Rebasing the current branch" | |
caace111 | 965 | oldHead = mypopen("git rev-parse HEAD").read()[:-1] |
01ce1fe9 | 966 | system("git rebase p4") |
1f52af6c | 967 | system("git diff-tree --stat --summary -M %s HEAD" % oldHead) |
01ce1fe9 SH |
968 | return True |
969 | ||
f9a3a4f7 SH |
970 | class P4Clone(P4Sync): |
971 | def __init__(self): | |
972 | P4Sync.__init__(self) | |
973 | self.description = "Creates a new git repository and imports from Perforce into it" | |
974 | self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]" | |
975 | self.needsGit = False | |
f9a3a4f7 SH |
976 | |
977 | def run(self, args): | |
59fa4171 SH |
978 | global gitdir |
979 | ||
f9a3a4f7 SH |
980 | if len(args) < 1: |
981 | return False | |
982 | depotPath = args[0] | |
983 | dir = "" | |
984 | if len(args) == 2: | |
985 | dir = args[1] | |
986 | elif len(args) > 2: | |
987 | return False | |
988 | ||
989 | if not depotPath.startswith("//"): | |
990 | return False | |
991 | ||
992 | if len(dir) == 0: | |
993 | dir = depotPath | |
994 | atPos = dir.rfind("@") | |
995 | if atPos != -1: | |
996 | dir = dir[0:atPos] | |
997 | hashPos = dir.rfind("#") | |
998 | if hashPos != -1: | |
999 | dir = dir[0:hashPos] | |
1000 | ||
1001 | if dir.endswith("..."): | |
1002 | dir = dir[:-3] | |
1003 | ||
1004 | if dir.endswith("/"): | |
1005 | dir = dir[:-1] | |
1006 | ||
1007 | slashPos = dir.rfind("/") | |
1008 | if slashPos != -1: | |
1009 | dir = dir[slashPos + 1:] | |
1010 | ||
1011 | print "Importing from %s into %s" % (depotPath, dir) | |
1012 | os.makedirs(dir) | |
1013 | os.chdir(dir) | |
1014 | system("git init") | |
64ffb06a | 1015 | gitdir = os.getcwd() + "/.git" |
f9a3a4f7 SH |
1016 | if not P4Sync.run(self, [depotPath]): |
1017 | return False | |
f9a3a4f7 | 1018 | if self.branch != "master": |
8f9b2e08 SH |
1019 | if gitBranchExists("refs/remotes/p4/master"): |
1020 | system("git branch master refs/remotes/p4/master") | |
1021 | system("git checkout -f") | |
1022 | else: | |
1023 | print "Could not detect main branch. No checkout/master branch created." | |
f9a3a4f7 SH |
1024 | return True |
1025 | ||
b984733c SH |
1026 | class HelpFormatter(optparse.IndentedHelpFormatter): |
1027 | def __init__(self): | |
1028 | optparse.IndentedHelpFormatter.__init__(self) | |
1029 | ||
1030 | def format_description(self, description): | |
1031 | if description: | |
1032 | return description + "\n" | |
1033 | else: | |
1034 | return "" | |
4f5cf76a | 1035 | |
86949eef SH |
1036 | def printUsage(commands): |
1037 | print "usage: %s <command> [options]" % sys.argv[0] | |
1038 | print "" | |
1039 | print "valid commands: %s" % ", ".join(commands) | |
1040 | print "" | |
1041 | print "Try %s <command> --help for command specific help." % sys.argv[0] | |
1042 | print "" | |
1043 | ||
1044 | commands = { | |
1045 | "debug" : P4Debug(), | |
711544b0 | 1046 | "submit" : P4Submit(), |
01ce1fe9 | 1047 | "sync" : P4Sync(), |
f9a3a4f7 SH |
1048 | "rebase" : P4Rebase(), |
1049 | "clone" : P4Clone() | |
86949eef SH |
1050 | } |
1051 | ||
1052 | if len(sys.argv[1:]) == 0: | |
1053 | printUsage(commands.keys()) | |
1054 | sys.exit(2) | |
1055 | ||
1056 | cmd = "" | |
1057 | cmdName = sys.argv[1] | |
1058 | try: | |
1059 | cmd = commands[cmdName] | |
1060 | except KeyError: | |
1061 | print "unknown command %s" % cmdName | |
1062 | print "" | |
1063 | printUsage(commands.keys()) | |
1064 | sys.exit(2) | |
1065 | ||
4f5cf76a SH |
1066 | options = cmd.options |
1067 | cmd.gitdir = gitdir | |
4f5cf76a | 1068 | |
e20a9e53 | 1069 | args = sys.argv[2:] |
86949eef | 1070 | |
e20a9e53 SH |
1071 | if len(options) > 0: |
1072 | options.append(optparse.make_option("--git-dir", dest="gitdir")) | |
1073 | ||
1074 | parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName), | |
1075 | options, | |
1076 | description = cmd.description, | |
1077 | formatter = HelpFormatter()) | |
1078 | ||
1079 | (cmd, args) = parser.parse_args(sys.argv[2:], cmd); | |
86949eef | 1080 | |
8910ac0e SH |
1081 | if cmd.needsGit: |
1082 | gitdir = cmd.gitdir | |
1083 | if len(gitdir) == 0: | |
1084 | gitdir = ".git" | |
1085 | if not isValidGitDir(gitdir): | |
81f2373f | 1086 | gitdir = mypopen("git rev-parse --git-dir").read()[:-1] |
dc1a93b6 | 1087 | if os.path.exists(gitdir): |
5c4153e4 SH |
1088 | cdup = mypopen("git rev-parse --show-cdup").read()[:-1]; |
1089 | if len(cdup) > 0: | |
1090 | os.chdir(cdup); | |
4f5cf76a | 1091 | |
8910ac0e SH |
1092 | if not isValidGitDir(gitdir): |
1093 | if isValidGitDir(gitdir + "/.git"): | |
1094 | gitdir += "/.git" | |
1095 | else: | |
1096 | die("fatal: cannot locate git repository at %s" % gitdir) | |
4f5cf76a | 1097 | |
8910ac0e | 1098 | os.environ["GIT_DIR"] = gitdir |
4f5cf76a | 1099 | |
b984733c SH |
1100 | if not cmd.run(args): |
1101 | parser.print_help() | |
1102 |