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