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"),
119 optparse
.make_option("--apply-as-patch", action
="store_true", dest
="applyAsPatch")
121 self
.description
= "Submit changes from git to the perforce depot."
122 self
.firstTime
= True
124 self
.interactive
= True
127 self
.firstTime
= True
128 self
.origin
= "origin"
130 self
.applyAsPatch
= False
132 self
.logSubstitutions
= {}
133 self
.logSubstitutions
["<enter description here>"] = "%log%"
134 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
137 if len(p4CmdList("opened ...")) > 0:
138 die("You have files opened with perforce! Close them before starting the sync.")
141 if len(self
.config
) > 0 and not self
.reset
:
142 die("Cannot start sync. Previous sync config found at %s" % self
.configFile
)
145 for line
in os
.popen("git-rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
146 commits
.append(line
[:-1])
149 self
.config
["commits"] = commits
151 if not self
.applyAsPatch
:
152 print "Creating temporary p4-sync branch from %s ..." % self
.origin
153 system("git checkout -f -b p4-sync %s" % self
.origin
)
155 def prepareLogMessage(self
, template
, message
):
158 for line
in template
.split("\n"):
159 if line
.startswith("#"):
160 result
+= line
+ "\n"
164 for key
in self
.logSubstitutions
.keys():
165 if line
.find(key
) != -1:
166 value
= self
.logSubstitutions
[key
]
167 value
= value
.replace("%log%", message
)
168 if value
!= "@remove@":
169 result
+= line
.replace(key
, value
) + "\n"
174 result
+= line
+ "\n"
179 print "Applying %s" % (os
.popen("git-log --max-count=1 --pretty=oneline %s" % id).read())
180 diff
= os
.popen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
182 filesToDelete
= set()
185 path
= line
[1:].strip()
187 system("p4 edit %s" % path
)
188 elif modifier
== "A":
190 if path
in filesToDelete
:
191 filesToDelete
.remove(path
)
192 elif modifier
== "D":
193 filesToDelete
.add(path
)
194 if path
in filesToAdd
:
195 filesToAdd
.remove(path
)
197 die("unknown modifier %s for %s" % (modifier
, path
))
199 if self
.applyAsPatch
:
200 system("git-diff-tree -p --diff-filter=ACMRTUXB \"%s^\" \"%s\" | patch -p1" % (id, id))
202 system("git-diff-files --name-only -z | git-update-index --remove -z --stdin")
203 system("git cherry-pick --no-commit \"%s\"" % id)
206 system("p4 add %s" % f
)
207 for f
in filesToDelete
:
208 system("p4 revert %s" % f
)
209 system("p4 delete %s" % f
)
213 for log
in os
.popen("git-cat-file commit %s" % id).readlines():
219 if len(logMessage
) > 0:
223 template
= os
.popen("p4 change -o").read()
226 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
227 diff
= os
.popen("p4 diff -du ...").read()
229 for newFile
in filesToAdd
:
230 diff
+= "==== new file ====\n"
231 diff
+= "--- /dev/null\n"
232 diff
+= "+++ %s\n" % newFile
233 f
= open(newFile
, "r")
234 for line
in f
.readlines():
238 pipe
= os
.popen("less", "w")
239 pipe
.write(submitTemplate
+ diff
)
243 while response
== "e":
244 response
= raw_input("Do you want to submit this change (y/e/n)? ")
246 [handle
, fileName
] = tempfile
.mkstemp()
247 tmpFile
= os
.fdopen(handle
, "w+")
248 tmpFile
.write(submitTemplate
)
250 editor
= os
.environ
.get("EDITOR", "vi")
251 system(editor
+ " " + fileName
)
252 tmpFile
= open(fileName
, "r")
253 submitTemplate
= tmpFile
.read()
257 if response
== "y" or response
== "yes":
260 raw_input("Press return to continue...")
262 pipe
= os
.popen("p4 submit -i", "w")
263 pipe
.write(submitTemplate
)
266 print "Not submitting!"
267 self
.interactive
= False
269 fileName
= "submit.txt"
270 file = open(fileName
, "w+")
271 file.write(self
.prepareLogMessage(template
, logMessage
))
273 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
277 self
.firstTime
= True
279 if len(self
.substFile
) > 0:
280 for line
in open(self
.substFile
, "r").readlines():
281 tokens
= line
[:-1].split("=")
282 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
284 if len(self
.master
) == 0:
285 self
.master
= currentGitBranch()
286 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
287 die("Detecting current git branch failed!")
290 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
291 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
296 commits
= self
.config
.get("commits", [])
298 while len(commits
) > 0:
299 self
.firstTime
= False
301 commits
= commits
[1:]
302 self
.config
["commits"] = commits
304 if not self
.interactive
:
309 if len(commits
) == 0:
311 print "No changes found to apply between %s and current HEAD" % self
.origin
313 print "All changes applied!"
314 if not self
.applyAsPatch
:
315 print "Deleting temporary p4-sync branch and going back to %s" % self
.master
316 system("git checkout %s" % self
.master
)
317 system("git branch -D p4-sync")
318 print "Cleaning out your perforce checkout by doing p4 edit ... ; p4 revert ..."
319 system("p4 edit ... >/dev/null")
320 system("p4 revert ... >/dev/null")
321 os
.remove(self
.configFile
)
325 class GitSync(Command
):
327 Command
.__init
__(self
)
329 optparse
.make_option("--branch", dest
="branch"),
330 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
331 optparse
.make_option("--changesfile", dest
="changesFile"),
332 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
333 optparse
.make_option("--known-branches", dest
="knownBranches"),
334 optparse
.make_option("--cache", dest
="doCache", action
="store_true"),
335 optparse
.make_option("--command-cache", dest
="commandCache", action
="store_true")
337 self
.description
= """Imports from Perforce into a git repository.\n
339 //depot/my/project/ -- to import the current head
340 //depot/my/project/@all -- to import everything
341 //depot/my/project/@1,6 -- to import only from revision 1 to 6
343 (a ... is not needed in the path p4 specification, it's added implicitly)"""
345 self
.usage
+= " //depot/path[@revRange]"
347 self
.dataCache
= False
348 self
.commandCache
= False
350 self
.knownBranches
= Set()
351 self
.createdBranches
= Set()
352 self
.committedChanges
= Set()
353 self
.branch
= "master"
354 self
.detectBranches
= False
355 self
.changesFile
= ""
357 def p4File(self
, depotPath
):
358 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
360 def extractFilesFromCommit(self
, commit
):
363 while commit
.has_key("depotFile%s" % fnum
):
364 path
= commit
["depotFile%s" % fnum
]
365 if not path
.startswith(self
.globalPrefix
):
366 # if not self.silent:
367 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.globalPrefix, change)
373 file["rev"] = commit
["rev%s" % fnum
]
374 file["action"] = commit
["action%s" % fnum
]
375 file["type"] = commit
["type%s" % fnum
]
380 def isSubPathOf(self
, first
, second
):
381 if not first
.startswith(second
):
385 return first
[len(second
)] == "/"
387 def branchesForCommit(self
, files
):
391 relativePath
= file["path"][len(self
.globalPrefix
):]
392 # strip off the filename
393 relativePath
= relativePath
[0:relativePath
.rfind("/")]
395 # if len(branches) == 0:
396 # branches.add(relativePath)
397 # knownBranches.add(relativePath)
400 ###### this needs more testing :)
402 for branch
in branches
:
403 if relativePath
== branch
:
406 # if relativePath.startswith(branch):
407 if self
.isSubPathOf(relativePath
, branch
):
410 # if branch.startswith(relativePath):
411 if self
.isSubPathOf(branch
, relativePath
):
412 branches
.remove(branch
)
418 for branch
in knownBranches
:
419 #if relativePath.startswith(branch):
420 if self
.isSubPathOf(relativePath
, branch
):
421 if len(branches
) == 0:
422 relativePath
= branch
430 branches
.add(relativePath
)
431 self
.knownBranches
.add(relativePath
)
435 def findBranchParent(self
, branchPrefix
, files
):
438 if not path
.startswith(branchPrefix
):
440 action
= file["action"]
441 if action
!= "integrate" and action
!= "branch":
444 depotPath
= path
+ "#" + rev
446 log
= p4CmdList("filelog \"%s\"" % depotPath
)
448 print "eek! I got confused by the filelog of %s" % depotPath
452 if log
["action0"] != action
:
453 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
456 branchAction
= log
["how0,0"]
457 # if branchAction == "branch into" or branchAction == "ignored":
458 # continue # ignore for branching
460 if not branchAction
.endswith(" from"):
461 continue # ignore for branching
462 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
465 source
= log
["file0,0"]
466 if source
.startswith(branchPrefix
):
469 lastSourceRev
= log
["erev0,0"]
471 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
472 if len(sourceLog
) != 1:
473 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
475 sourceLog
= sourceLog
[0]
477 relPath
= source
[len(self
.globalPrefix
):]
478 # strip off the filename
479 relPath
= relPath
[0:relPath
.rfind("/")]
481 for branch
in self
.knownBranches
:
482 if self
.isSubPathOf(relPath
, branch
):
483 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
486 # print "%s is not a subpath of branch %s" % (relPath, branch)
490 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= "", merged
= ""):
491 epoch
= details
["time"]
492 author
= details
["user"]
494 self
.gitStream
.write("commit %s\n" % branch
)
495 # gitStream.write("mark :%s\n" % details["change"])
496 self
.committedChanges
.add(int(details
["change"]))
498 if author
in self
.users
:
499 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
501 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
503 self
.gitStream
.write("committer %s\n" % committer
)
505 self
.gitStream
.write("data <<EOT\n")
506 self
.gitStream
.write(details
["desc"])
507 self
.gitStream
.write("\n[ imported from %s; change %s ]\n" % (branchPrefix
, details
["change"]))
508 self
.gitStream
.write("EOT\n\n")
511 self
.gitStream
.write("from %s\n" % parent
)
514 self
.gitStream
.write("merge %s\n" % merged
)
518 if not path
.startswith(branchPrefix
):
520 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
523 depotPath
= path
+ "#" + rev
524 relPath
= path
[len(branchPrefix
):]
525 action
= file["action"]
527 if file["type"] == "apple":
528 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
531 if action
== "delete":
532 self
.gitStream
.write("D %s\n" % relPath
)
535 if file["type"].startswith("x"):
538 data
= self
.p4File(depotPath
)
540 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
541 self
.gitStream
.write("data %s\n" % len(data
))
542 self
.gitStream
.write(data
)
543 self
.gitStream
.write("\n")
545 self
.gitStream
.write("\n")
547 self
.lastChange
= int(details
["change"])
549 def extractFilesInCommitToBranch(self
, files
, branchPrefix
):
554 if path
.startswith(branchPrefix
):
555 newFiles
.append(file)
559 def findBranchSourceHeuristic(self
, files
, branch
, branchPrefix
):
561 action
= file["action"]
562 if action
!= "integrate" and action
!= "branch":
566 depotPath
= path
+ "#" + rev
568 log
= p4CmdList("filelog \"%s\"" % depotPath
)
570 print "eek! I got confused by the filelog of %s" % depotPath
574 if log
["action0"] != action
:
575 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
578 branchAction
= log
["how0,0"]
580 if not branchAction
.endswith(" from"):
581 continue # ignore for branching
582 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
585 source
= log
["file0,0"]
586 if source
.startswith(branchPrefix
):
589 lastSourceRev
= log
["erev0,0"]
591 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
592 if len(sourceLog
) != 1:
593 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
595 sourceLog
= sourceLog
[0]
597 relPath
= source
[len(self
.globalPrefix
):]
598 # strip off the filename
599 relPath
= relPath
[0:relPath
.rfind("/")]
601 for candidate
in self
.knownBranches
:
602 if self
.isSubPathOf(relPath
, candidate
) and candidate
!= branch
:
607 def changeIsBranchMerge(self
, sourceBranch
, destinationBranch
, change
):
609 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ sourceBranch
+ "/", change
)):
610 if file["action"] == "delete":
612 sourceFiles
[file["depotFile"]] = file
614 destinationFiles
= {}
615 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ destinationBranch
+ "/", change
)):
616 destinationFiles
[file["depotFile"]] = file
618 for fileName
in sourceFiles
.keys():
622 for integration
in p4CmdList("integrated \"%s\"" % fileName
):
623 toFile
= integration
["fromFile"] # yes, it's true, it's fromFile
624 if not toFile
in destinationFiles
:
626 destFile
= destinationFiles
[toFile
]
627 if destFile
["action"] == "delete":
628 # print "file %s has been deleted in %s" % (fileName, toFile)
631 integrationCount
+= 1
632 if integration
["how"] == "branch from":
635 if int(integration
["change"]) == change
:
636 integrations
.append(integration
)
638 if int(integration
["change"]) > change
:
641 destRev
= int(destFile
["rev"])
643 startRev
= integration
["startFromRev"][1:]
644 if startRev
== "none":
647 startRev
= int(startRev
)
649 endRev
= integration
["endFromRev"][1:]
655 initialBranch
= (destRev
== 1 and integration
["how"] != "branch into")
656 inRange
= (destRev
>= startRev
and destRev
<= endRev
)
657 newer
= (destRev
> startRev
and destRev
> endRev
)
659 if initialBranch
or inRange
or newer
:
660 integrations
.append(integration
)
665 if len(integrations
) == 0 and integrationCount
> 1:
666 print "file %s was not integrated from %s into %s" % (fileName
, sourceBranch
, destinationBranch
)
671 def getUserMap(self
):
674 for output
in p4CmdList("users"):
675 if not output
.has_key("User"):
677 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
680 self
.branch
= "refs/heads/" + self
.branch
681 self
.globalPrefix
= self
.previousDepotPath
= os
.popen("git-repo-config --get p4.depotpath").read()
682 if len(self
.globalPrefix
) != 0:
683 self
.globalPrefix
= self
.globalPrefix
[:-1]
685 if len(args
) == 0 and len(self
.globalPrefix
) != 0:
687 print "[using previously specified depot path %s]" % self
.globalPrefix
691 if len(self
.globalPrefix
) != 0 and self
.globalPrefix
!= args
[0]:
692 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.globalPrefix
, args
[0])
694 self
.globalPrefix
= args
[0]
696 self
.changeRange
= ""
699 self
.initialParent
= ""
703 if self
.globalPrefix
.find("@") != -1:
704 atIdx
= self
.globalPrefix
.index("@")
705 self
.changeRange
= self
.globalPrefix
[atIdx
:]
706 if self
.changeRange
== "@all":
707 self
.changeRange
= ""
708 elif self
.changeRange
.find(",") == -1:
709 self
.revision
= self
.changeRange
710 self
.changeRange
= ""
711 self
.globalPrefix
= self
.globalPrefix
[0:atIdx
]
712 elif self
.globalPrefix
.find("#") != -1:
713 hashIdx
= self
.globalPrefix
.index("#")
714 self
.revision
= self
.globalPrefix
[hashIdx
:]
715 self
.globalPrefix
= self
.globalPrefix
[0:hashIdx
]
716 elif len(self
.previousDepotPath
) == 0:
717 self
.revision
= "#head"
719 if self
.globalPrefix
.endswith("..."):
720 self
.globalPrefix
= self
.globalPrefix
[:-3]
722 if not self
.globalPrefix
.endswith("/"):
723 self
.globalPrefix
+= "/"
727 if len(self
.changeRange
) == 0:
729 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % self
.branch
)
731 if output
.endswith("\n"):
733 tagIdx
= output
.index(" tags/p4/")
734 caretIdx
= output
.find("^")
738 self
.rev
= int(output
[tagIdx
+ 9 : endPos
]) + 1
739 self
.changeRange
= "@%s,#head" % self
.rev
740 self
.initialParent
= os
.popen("git-rev-parse %s" % self
.branch
).read()[:-1]
741 self
.initialTag
= "p4/%s" % (int(self
.rev
) - 1)
745 self
.tz
= - time
.timezone
/ 36
746 tzsign
= ("%s" % self
.tz
)[0]
747 if tzsign
!= '+' and tzsign
!= '-':
748 self
.tz
= "+" + ("%s" % self
.tz
)
750 self
.gitOutput
, self
.gitStream
, self
.gitError
= popen2
.popen3("git-fast-import")
752 if len(self
.revision
) > 0:
753 print "Doing initial import of %s from revision %s" % (self
.globalPrefix
, self
.revision
)
755 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
756 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.globalPrefix
, self
.revision
)
757 details
["change"] = self
.revision
761 for info
in p4CmdList("files %s...%s" % (self
.globalPrefix
, self
.revision
)):
762 change
= int(info
["change"])
763 if change
> newestRevision
:
764 newestRevision
= change
766 if info
["action"] == "delete":
767 fileCnt
= fileCnt
+ 1
770 for prop
in [ "depotFile", "rev", "action", "type" ]:
771 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
773 fileCnt
= fileCnt
+ 1
775 details
["change"] = newestRevision
778 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.globalPrefix
)
780 print self
.gitError
.read()
785 if len(self
.changesFile
) > 0:
786 output
= open(self
.changesFile
).readlines()
789 changeSet
.add(int(line
))
791 for change
in changeSet
:
792 changes
.append(change
)
796 output
= os
.popen("p4 changes %s...%s" % (self
.globalPrefix
, self
.changeRange
)).readlines()
799 changeNum
= line
.split(" ")[1]
800 changes
.append(changeNum
)
804 if len(changes
) == 0:
806 print "no changes to import!"
810 for change
in changes
:
811 description
= p4Cmd("describe %s" % change
)
814 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
819 files
= self
.extractFilesFromCommit(description
)
820 if self
.detectBranches
:
821 for branch
in self
.branchesForCommit(files
):
822 self
.knownBranches
.add(branch
)
823 branchPrefix
= self
.globalPrefix
+ branch
+ "/"
825 filesForCommit
= self
.extractFilesInCommitToBranch(files
, branchPrefix
)
829 ########### remove cnt!!!
830 if branch
not in self
.createdBranches
and cnt
> 2:
831 self
.createdBranches
.add(branch
)
832 parent
= self
.findBranchParent(branchPrefix
, files
)
835 # elif len(parent) > 0:
836 # print "%s branched off of %s" % (branch, parent)
839 merged
= self
.findBranchSourceHeuristic(filesForCommit
, branch
, branchPrefix
)
841 print "change %s could be a merge from %s into %s" % (description
["change"], merged
, branch
)
842 if not self
.changeIsBranchMerge(merged
, branch
, int(description
["change"])):
845 branch
= "refs/heads/" + branch
847 parent
= "refs/heads/" + parent
849 merged
= "refs/heads/" + merged
850 self
.commit(description
, files
, branch
, branchPrefix
, parent
, merged
)
852 self
.commit(description
, files
, self
.branch
, self
.globalPrefix
, self
.initialParent
)
853 self
.initialParent
= ""
855 print self
.gitError
.read()
861 self
.gitStream
.write("reset refs/tags/p4/%s\n" % self
.lastChange
)
862 self
.gitStream
.write("from %s\n\n" % self
.branch
);
865 self
.gitStream
.close()
866 self
.gitOutput
.close()
867 self
.gitError
.close()
869 os
.popen("git-repo-config p4.depotpath %s" % self
.globalPrefix
).read()
870 if len(self
.initialTag
) > 0:
871 os
.popen("git tag -d %s" % self
.initialTag
).read()
875 class HelpFormatter(optparse
.IndentedHelpFormatter
):
877 optparse
.IndentedHelpFormatter
.__init
__(self
)
879 def format_description(self
, description
):
881 return description
+ "\n"
885 def printUsage(commands
):
886 print "usage: %s <command> [options]" % sys
.argv
[0]
888 print "valid commands: %s" % ", ".join(commands
)
890 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
895 "clean-tags" : P4CleanTags(),
900 if len(sys
.argv
[1:]) == 0:
901 printUsage(commands
.keys())
905 cmdName
= sys
.argv
[1]
907 cmd
= commands
[cmdName
]
909 print "unknown command %s" % cmdName
911 printUsage(commands
.keys())
914 options
= cmd
.options
916 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
918 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
920 description
= cmd
.description
,
921 formatter
= HelpFormatter())
923 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
929 if not isValidGitDir(gitdir
):
930 if isValidGitDir(gitdir
+ "/.git"):
933 die("fatal: cannot locate git repository at %s" % gitdir
)
935 os
.environ
["GIT_DIR"] = gitdir
937 if not cmd
.run(args
):