3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <hausmann@kde.org>
6 # Copyright: 2007 Simon Hausmann <hausmann@kde.org>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
11 import optparse
, sys
, os
, marshal
, popen2
, shelve
12 import tempfile
, getopt
, sha
, os
.path
, time
15 gitdir
= os
.environ
.get("GIT_DIR", "")
18 cmd
= "p4 -G %s" % cmd
19 pipe
= os
.popen(cmd
, "rb")
24 entry
= marshal
.load(pipe
)
40 sys
.stderr
.write(msg
+ "\n")
43 def currentGitBranch():
44 return os
.popen("git-name-rev HEAD").read().split(" ")[1][:-1]
46 def isValidGitDir(path
):
47 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
52 if os
.system(cmd
) != 0:
53 die("command failed: %s" % cmd
)
57 self
.usage
= "usage: %prog [options]"
59 class P4Debug(Command
):
63 self
.description
= "A tool to debug the output of p4 -G."
66 for output
in p4CmdList(" ".join(args
)):
70 class P4CleanTags(Command
):
72 Command
.__init
__(self
)
74 # optparse.make_option("--branch", dest="branch", default="refs/heads/master")
76 self
.description
= "A tool to remove stale unused tags from incremental perforce imports."
78 branch
= currentGitBranch()
79 print "Cleaning out stale p4 import tags..."
80 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % branch
)
83 tagIdx
= output
.index(" tags/p4/")
85 print "Cannot find any p4/* tag. Nothing to do."
89 caretIdx
= output
.index("^")
91 caretIdx
= len(output
) - 1
92 rev
= int(output
[tagIdx
+ 9 : caretIdx
])
94 allTags
= os
.popen("git tag -l p4/").readlines()
95 for i
in range(len(allTags
)):
96 allTags
[i
] = int(allTags
[i
][3:-1])
103 print os
.popen("git tag -d p4/%s" % rev
).read()
105 print "%s tags removed." % len(allTags
)
108 class P4Sync(Command
):
110 Command
.__init
__(self
)
112 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
113 optparse
.make_option("--origin", dest
="origin"),
114 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
115 optparse
.make_option("--master", dest
="master"),
116 optparse
.make_option("--log-substitutions", dest
="substFile"),
117 optparse
.make_option("--noninteractive", action
="store_false"),
118 optparse
.make_option("--dry-run", action
="store_true")
120 self
.description
= "Submit changes from git to the perforce depot."
121 self
.firstTime
= True
123 self
.interactive
= True
126 self
.firstTime
= True
127 self
.origin
= "origin"
130 self
.logSubstitutions
= {}
131 self
.logSubstitutions
["<enter description here>"] = "%log%"
132 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
135 if len(p4CmdList("opened ...")) > 0:
136 die("You have files opened with perforce! Close them before starting the sync.")
139 if len(self
.config
) > 0 and not self
.reset
:
140 die("Cannot start sync. Previous sync config found at %s" % self
.configFile
)
143 for line
in os
.popen("git-rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
144 commits
.append(line
[:-1])
147 self
.config
["commits"] = commits
149 print "Creating temporary p4-sync branch from %s ..." % self
.origin
150 system("git checkout -f -b p4-sync %s" % self
.origin
)
152 def prepareLogMessage(self
, template
, message
):
155 for line
in template
.split("\n"):
156 if line
.startswith("#"):
157 result
+= line
+ "\n"
161 for key
in self
.logSubstitutions
.keys():
162 if line
.find(key
) != -1:
163 value
= self
.logSubstitutions
[key
]
164 value
= value
.replace("%log%", message
)
165 if value
!= "@remove@":
166 result
+= line
.replace(key
, value
) + "\n"
171 result
+= line
+ "\n"
176 print "Applying %s" % (os
.popen("git-log --max-count=1 --pretty=oneline %s" % id).read())
177 diff
= os
.popen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
179 filesToDelete
= set()
182 path
= line
[1:].strip()
184 system("p4 edit %s" % path
)
185 elif modifier
== "A":
187 if path
in filesToDelete
:
188 filesToDelete
.remove(path
)
189 elif modifier
== "D":
190 filesToDelete
.add(path
)
191 if path
in filesToAdd
:
192 filesToAdd
.remove(path
)
194 die("unknown modifier %s for %s" % (modifier
, path
))
196 system("git-diff-files --name-only -z | git-update-index --remove -z --stdin")
197 system("git cherry-pick --no-commit \"%s\"" % id)
200 system("p4 add %s" % f
)
201 for f
in filesToDelete
:
202 system("p4 revert %s" % f
)
203 system("p4 delete %s" % f
)
207 for log
in os
.popen("git-cat-file commit %s" % id).readlines():
213 if len(logMessage
) > 0:
217 template
= os
.popen("p4 change -o").read()
220 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
221 diff
= os
.popen("p4 diff -du ...").read()
223 for newFile
in filesToAdd
:
224 diff
+= "==== new file ====\n"
225 diff
+= "--- /dev/null\n"
226 diff
+= "+++ %s\n" % newFile
227 f
= open(newFile
, "r")
228 for line
in f
.readlines():
232 pipe
= os
.popen("less", "w")
233 pipe
.write(submitTemplate
+ diff
)
237 while response
== "e":
238 response
= raw_input("Do you want to submit this change (y/e/n)? ")
240 [handle
, fileName
] = tempfile
.mkstemp()
241 tmpFile
= os
.fdopen(handle
, "w+")
242 tmpFile
.write(submitTemplate
)
244 editor
= os
.environ
.get("EDITOR", "vi")
245 system(editor
+ " " + fileName
)
246 tmpFile
= open(fileName
, "r")
247 submitTemplate
= tmpFile
.read()
251 if response
== "y" or response
== "yes":
254 raw_input("Press return to continue...")
256 pipe
= os
.popen("p4 submit -i", "w")
257 pipe
.write(submitTemplate
)
260 print "Not submitting!"
261 self
.interactive
= False
263 fileName
= "submit.txt"
264 file = open(fileName
, "w+")
265 file.write(self
.prepareLogMessage(template
, logMessage
))
267 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
271 self
.firstTime
= True
273 if len(self
.substFile
) > 0:
274 for line
in open(self
.substFile
, "r").readlines():
275 tokens
= line
[:-1].split("=")
276 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
278 if len(self
.master
) == 0:
279 self
.master
= currentGitBranch()
280 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
281 die("Detecting current git branch failed!")
284 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
285 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
290 commits
= self
.config
.get("commits", [])
292 while len(commits
) > 0:
293 self
.firstTime
= False
295 commits
= commits
[1:]
296 self
.config
["commits"] = commits
298 if not self
.interactive
:
303 if len(commits
) == 0:
305 print "No changes found to apply between %s and current HEAD" % self
.origin
307 print "All changes applied!"
308 print "Deleting temporary p4-sync branch and going back to %s" % self
.master
309 system("git checkout %s" % self
.master
)
310 system("git branch -D p4-sync")
311 print "Cleaning out your perforce checkout by doing p4 edit ... ; p4 revert ..."
312 system("p4 edit ... >/dev/null")
313 system("p4 revert ... >/dev/null")
314 os
.remove(self
.configFile
)
318 class GitSync(Command
):
320 Command
.__init
__(self
)
322 optparse
.make_option("--branch", dest
="branch"),
323 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
324 optparse
.make_option("--changesfile", dest
="changesFile"),
325 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
326 optparse
.make_option("--known-branches", dest
="knownBranches"),
327 optparse
.make_option("--cache", dest
="doCache", action
="store_true"),
328 optparse
.make_option("--command-cache", dest
="commandCache", action
="store_true")
330 self
.description
= """Imports from Perforce into a git repository.\n
332 //depot/my/project/ -- to import the current head
333 //depot/my/project/@all -- to import everything
334 //depot/my/project/@1,6 -- to import only from revision 1 to 6
336 (a ... is not needed in the path p4 specification, it's added implicitly)"""
338 self
.usage
+= " //depot/path[@revRange]"
340 self
.dataCache
= False
341 self
.commandCache
= False
343 self
.knownBranches
= Set()
344 self
.createdBranches
= Set()
345 self
.committedChanges
= Set()
346 self
.branch
= "master"
347 self
.detectBranches
= False
348 self
.changesFile
= ""
350 def p4File(self
, depotPath
):
351 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
353 def extractFilesFromCommit(self
, commit
):
356 while commit
.has_key("depotFile%s" % fnum
):
357 path
= commit
["depotFile%s" % fnum
]
358 if not path
.startswith(self
.globalPrefix
):
359 # if not self.silent:
360 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.globalPrefix, change)
366 file["rev"] = commit
["rev%s" % fnum
]
367 file["action"] = commit
["action%s" % fnum
]
368 file["type"] = commit
["type%s" % fnum
]
373 def isSubPathOf(self
, first
, second
):
374 if not first
.startswith(second
):
378 return first
[len(second
)] == "/"
380 def branchesForCommit(self
, files
):
384 relativePath
= file["path"][len(self
.globalPrefix
):]
385 # strip off the filename
386 relativePath
= relativePath
[0:relativePath
.rfind("/")]
388 # if len(branches) == 0:
389 # branches.add(relativePath)
390 # knownBranches.add(relativePath)
393 ###### this needs more testing :)
395 for branch
in branches
:
396 if relativePath
== branch
:
399 # if relativePath.startswith(branch):
400 if self
.isSubPathOf(relativePath
, branch
):
403 # if branch.startswith(relativePath):
404 if self
.isSubPathOf(branch
, relativePath
):
405 branches
.remove(branch
)
411 for branch
in knownBranches
:
412 #if relativePath.startswith(branch):
413 if self
.isSubPathOf(relativePath
, branch
):
414 if len(branches
) == 0:
415 relativePath
= branch
423 branches
.add(relativePath
)
424 self
.knownBranches
.add(relativePath
)
428 def findBranchParent(self
, branchPrefix
, files
):
431 if not path
.startswith(branchPrefix
):
433 action
= file["action"]
434 if action
!= "integrate" and action
!= "branch":
437 depotPath
= path
+ "#" + rev
439 log
= p4CmdList("filelog \"%s\"" % depotPath
)
441 print "eek! I got confused by the filelog of %s" % depotPath
445 if log
["action0"] != action
:
446 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
449 branchAction
= log
["how0,0"]
450 # if branchAction == "branch into" or branchAction == "ignored":
451 # continue # ignore for branching
453 if not branchAction
.endswith(" from"):
454 continue # ignore for branching
455 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
458 source
= log
["file0,0"]
459 if source
.startswith(branchPrefix
):
462 lastSourceRev
= log
["erev0,0"]
464 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
465 if len(sourceLog
) != 1:
466 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
468 sourceLog
= sourceLog
[0]
470 relPath
= source
[len(self
.globalPrefix
):]
471 # strip off the filename
472 relPath
= relPath
[0:relPath
.rfind("/")]
474 for branch
in self
.knownBranches
:
475 if self
.isSubPathOf(relPath
, branch
):
476 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
479 # print "%s is not a subpath of branch %s" % (relPath, branch)
483 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= "", merged
= ""):
484 epoch
= details
["time"]
485 author
= details
["user"]
487 self
.gitStream
.write("commit %s\n" % branch
)
488 # gitStream.write("mark :%s\n" % details["change"])
489 self
.committedChanges
.add(int(details
["change"]))
491 if author
in self
.users
:
492 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
494 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
496 self
.gitStream
.write("committer %s\n" % committer
)
498 self
.gitStream
.write("data <<EOT\n")
499 self
.gitStream
.write(details
["desc"])
500 self
.gitStream
.write("\n[ imported from %s; change %s ]\n" % (branchPrefix
, details
["change"]))
501 self
.gitStream
.write("EOT\n\n")
504 self
.gitStream
.write("from %s\n" % parent
)
507 self
.gitStream
.write("merge %s\n" % merged
)
511 if not path
.startswith(branchPrefix
):
513 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
516 depotPath
= path
+ "#" + rev
517 relPath
= path
[len(branchPrefix
):]
518 action
= file["action"]
520 if file["type"] == "apple":
521 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
524 if action
== "delete":
525 self
.gitStream
.write("D %s\n" % relPath
)
528 if file["type"].startswith("x"):
531 data
= self
.p4File(depotPath
)
533 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
534 self
.gitStream
.write("data %s\n" % len(data
))
535 self
.gitStream
.write(data
)
536 self
.gitStream
.write("\n")
538 self
.gitStream
.write("\n")
540 self
.lastChange
= int(details
["change"])
542 def extractFilesInCommitToBranch(self
, files
, branchPrefix
):
547 if path
.startswith(branchPrefix
):
548 newFiles
.append(file)
552 def findBranchSourceHeuristic(self
, files
, branch
, branchPrefix
):
554 action
= file["action"]
555 if action
!= "integrate" and action
!= "branch":
559 depotPath
= path
+ "#" + rev
561 log
= p4CmdList("filelog \"%s\"" % depotPath
)
563 print "eek! I got confused by the filelog of %s" % depotPath
567 if log
["action0"] != action
:
568 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
571 branchAction
= log
["how0,0"]
573 if not branchAction
.endswith(" from"):
574 continue # ignore for branching
575 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
578 source
= log
["file0,0"]
579 if source
.startswith(branchPrefix
):
582 lastSourceRev
= log
["erev0,0"]
584 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
585 if len(sourceLog
) != 1:
586 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
588 sourceLog
= sourceLog
[0]
590 relPath
= source
[len(self
.globalPrefix
):]
591 # strip off the filename
592 relPath
= relPath
[0:relPath
.rfind("/")]
594 for candidate
in self
.knownBranches
:
595 if self
.isSubPathOf(relPath
, candidate
) and candidate
!= branch
:
600 def changeIsBranchMerge(self
, sourceBranch
, destinationBranch
, change
):
602 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ sourceBranch
+ "/", change
)):
603 if file["action"] == "delete":
605 sourceFiles
[file["depotFile"]] = file
607 destinationFiles
= {}
608 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ destinationBranch
+ "/", change
)):
609 destinationFiles
[file["depotFile"]] = file
611 for fileName
in sourceFiles
.keys():
615 for integration
in p4CmdList("integrated \"%s\"" % fileName
):
616 toFile
= integration
["fromFile"] # yes, it's true, it's fromFile
617 if not toFile
in destinationFiles
:
619 destFile
= destinationFiles
[toFile
]
620 if destFile
["action"] == "delete":
621 # print "file %s has been deleted in %s" % (fileName, toFile)
624 integrationCount
+= 1
625 if integration
["how"] == "branch from":
628 if int(integration
["change"]) == change
:
629 integrations
.append(integration
)
631 if int(integration
["change"]) > change
:
634 destRev
= int(destFile
["rev"])
636 startRev
= integration
["startFromRev"][1:]
637 if startRev
== "none":
640 startRev
= int(startRev
)
642 endRev
= integration
["endFromRev"][1:]
648 initialBranch
= (destRev
== 1 and integration
["how"] != "branch into")
649 inRange
= (destRev
>= startRev
and destRev
<= endRev
)
650 newer
= (destRev
> startRev
and destRev
> endRev
)
652 if initialBranch
or inRange
or newer
:
653 integrations
.append(integration
)
658 if len(integrations
) == 0 and integrationCount
> 1:
659 print "file %s was not integrated from %s into %s" % (fileName
, sourceBranch
, destinationBranch
)
664 def getUserMap(self
):
667 for output
in p4CmdList("users"):
668 if not output
.has_key("User"):
670 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
673 self
.branch
= "refs/heads/" + self
.branch
674 self
.globalPrefix
= self
.previousDepotPath
= os
.popen("git-repo-config --get p4.depotpath").read()
675 if len(self
.globalPrefix
) != 0:
676 self
.globalPrefix
= self
.globalPrefix
[:-1]
678 if len(args
) == 0 and len(self
.globalPrefix
) != 0:
680 print "[using previously specified depot path %s]" % self
.globalPrefix
684 if len(self
.globalPrefix
) != 0 and self
.globalPrefix
!= args
[0]:
685 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.globalPrefix
, args
[0])
687 self
.globalPrefix
= args
[0]
689 self
.changeRange
= ""
692 self
.initialParent
= ""
696 if self
.globalPrefix
.find("@") != -1:
697 atIdx
= self
.globalPrefix
.index("@")
698 self
.changeRange
= self
.globalPrefix
[atIdx
:]
699 if self
.changeRange
== "@all":
700 self
.changeRange
= ""
701 elif self
.changeRange
.find(",") == -1:
702 self
.revision
= self
.changeRange
703 self
.changeRange
= ""
704 self
.globalPrefix
= self
.globalPrefix
[0:atIdx
]
705 elif self
.globalPrefix
.find("#") != -1:
706 hashIdx
= self
.globalPrefix
.index("#")
707 self
.revision
= self
.globalPrefix
[hashIdx
:]
708 self
.globalPrefix
= self
.globalPrefix
[0:hashIdx
]
709 elif len(self
.previousDepotPath
) == 0:
710 self
.revision
= "#head"
712 if self
.globalPrefix
.endswith("..."):
713 self
.globalPrefix
= self
.globalPrefix
[:-3]
715 if not self
.globalPrefix
.endswith("/"):
716 self
.globalPrefix
+= "/"
720 if len(self
.changeRange
) == 0:
722 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % self
.branch
)
724 if output
.endswith("\n"):
726 tagIdx
= output
.index(" tags/p4/")
727 caretIdx
= output
.find("^")
731 self
.rev
= int(output
[tagIdx
+ 9 : endPos
]) + 1
732 self
.changeRange
= "@%s,#head" % self
.rev
733 self
.initialParent
= os
.popen("git-rev-parse %s" % self
.branch
).read()[:-1]
734 self
.initialTag
= "p4/%s" % (int(self
.rev
) - 1)
738 self
.tz
= - time
.timezone
/ 36
739 tzsign
= ("%s" % self
.tz
)[0]
740 if tzsign
!= '+' and tzsign
!= '-':
741 self
.tz
= "+" + ("%s" % self
.tz
)
743 self
.gitOutput
, self
.gitStream
, self
.gitError
= popen2
.popen3("git-fast-import")
745 if len(self
.revision
) > 0:
746 print "Doing initial import of %s from revision %s" % (self
.globalPrefix
, self
.revision
)
748 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
749 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.globalPrefix
, self
.revision
)
750 details
["change"] = self
.revision
754 for info
in p4CmdList("files %s...%s" % (self
.globalPrefix
, self
.revision
)):
755 change
= int(info
["change"])
756 if change
> newestRevision
:
757 newestRevision
= change
759 if info
["action"] == "delete":
760 fileCnt
= fileCnt
+ 1
763 for prop
in [ "depotFile", "rev", "action", "type" ]:
764 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
766 fileCnt
= fileCnt
+ 1
768 details
["change"] = newestRevision
771 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.globalPrefix
)
773 print self
.gitError
.read()
778 if len(self
.changesFile
) > 0:
779 output
= open(self
.changesFile
).readlines()
782 changeSet
.add(int(line
))
784 for change
in changeSet
:
785 changes
.append(change
)
789 output
= os
.popen("p4 changes %s...%s" % (self
.globalPrefix
, self
.changeRange
)).readlines()
792 changeNum
= line
.split(" ")[1]
793 changes
.append(changeNum
)
797 if len(changes
) == 0:
799 print "no changes to import!"
803 for change
in changes
:
804 description
= p4Cmd("describe %s" % change
)
807 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
812 files
= self
.extractFilesFromCommit(description
)
813 if self
.detectBranches
:
814 for branch
in self
.branchesForCommit(files
):
815 self
.knownBranches
.add(branch
)
816 branchPrefix
= self
.globalPrefix
+ branch
+ "/"
818 filesForCommit
= self
.extractFilesInCommitToBranch(files
, branchPrefix
)
822 ########### remove cnt!!!
823 if branch
not in self
.createdBranches
and cnt
> 2:
824 self
.createdBranches
.add(branch
)
825 parent
= self
.findBranchParent(branchPrefix
, files
)
828 # elif len(parent) > 0:
829 # print "%s branched off of %s" % (branch, parent)
832 merged
= self
.findBranchSourceHeuristic(filesForCommit
, branch
, branchPrefix
)
834 print "change %s could be a merge from %s into %s" % (description
["change"], merged
, branch
)
835 if not self
.changeIsBranchMerge(merged
, branch
, int(description
["change"])):
838 branch
= "refs/heads/" + branch
840 parent
= "refs/heads/" + parent
842 merged
= "refs/heads/" + merged
843 self
.commit(description
, files
, branch
, branchPrefix
, parent
, merged
)
845 self
.commit(description
, files
, self
.branch
, self
.globalPrefix
, self
.initialParent
)
846 self
.initialParent
= ""
848 print self
.gitError
.read()
854 self
.gitStream
.write("reset refs/tags/p4/%s\n" % self
.lastChange
)
855 self
.gitStream
.write("from %s\n\n" % self
.branch
);
858 self
.gitStream
.close()
859 self
.gitOutput
.close()
860 self
.gitError
.close()
862 os
.popen("git-repo-config p4.depotpath %s" % self
.globalPrefix
).read()
863 if len(self
.initialTag
) > 0:
864 os
.popen("git tag -d %s" % self
.initialTag
).read()
868 class HelpFormatter(optparse
.IndentedHelpFormatter
):
870 optparse
.IndentedHelpFormatter
.__init
__(self
)
872 def format_description(self
, description
):
874 return description
+ "\n"
878 def printUsage(commands
):
879 print "usage: %s <command> [options]" % sys
.argv
[0]
881 print "valid commands: %s" % ", ".join(commands
)
883 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
888 "clean-tags" : P4CleanTags(),
893 if len(sys
.argv
[1:]) == 0:
894 printUsage(commands
.keys())
898 cmdName
= sys
.argv
[1]
900 cmd
= commands
[cmdName
]
902 print "unknown command %s" % cmdName
904 printUsage(commands
.keys())
907 options
= cmd
.options
909 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
911 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
913 description
= cmd
.description
,
914 formatter
= HelpFormatter())
916 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
922 if not isValidGitDir(gitdir
):
923 if isValidGitDir(gitdir
+ "/.git"):
926 die("fatal: cannot locate git repository at %s" % gitdir
)
928 os
.environ
["GIT_DIR"] = gitdir
930 if not cmd
.run(args
):