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