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
= True
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 separatorLine
= "######## everything below this line is just the diff #######\n"
241 firstIteration
= True
242 while response
== "e":
243 if not firstIteration
:
244 response
= raw_input("Do you want to submit this change (y/e/n)? ")
245 firstIteration
= False
247 [handle
, fileName
] = tempfile
.mkstemp()
248 tmpFile
= os
.fdopen(handle
, "w+")
249 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
251 editor
= os
.environ
.get("EDITOR", "vi")
252 system(editor
+ " " + fileName
)
253 tmpFile
= open(fileName
, "r")
254 message
= tmpFile
.read()
257 submitTemplate
= message
[:message
.index(separatorLine
)]
259 if response
== "y" or response
== "yes":
262 raw_input("Press return to continue...")
264 pipe
= os
.popen("p4 submit -i", "w")
265 pipe
.write(submitTemplate
)
268 print "Not submitting!"
269 self
.interactive
= False
271 fileName
= "submit.txt"
272 file = open(fileName
, "w+")
273 file.write(self
.prepareLogMessage(template
, logMessage
))
275 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
279 self
.firstTime
= True
281 if len(self
.substFile
) > 0:
282 for line
in open(self
.substFile
, "r").readlines():
283 tokens
= line
[:-1].split("=")
284 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
286 if len(self
.master
) == 0:
287 self
.master
= currentGitBranch()
288 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
289 die("Detecting current git branch failed!")
292 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
293 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
298 commits
= self
.config
.get("commits", [])
300 while len(commits
) > 0:
301 self
.firstTime
= False
303 commits
= commits
[1:]
304 self
.config
["commits"] = commits
306 if not self
.interactive
:
311 if len(commits
) == 0:
313 print "No changes found to apply between %s and current HEAD" % self
.origin
315 print "All changes applied!"
316 if not self
.applyAsPatch
:
317 print "Deleting temporary p4-sync branch and going back to %s" % self
.master
318 system("git checkout %s" % self
.master
)
319 system("git branch -D p4-sync")
320 print "Cleaning out your perforce checkout by doing p4 edit ... ; p4 revert ..."
321 system("p4 edit ... >/dev/null")
322 system("p4 revert ... >/dev/null")
323 os
.remove(self
.configFile
)
327 class GitSync(Command
):
329 Command
.__init
__(self
)
331 optparse
.make_option("--branch", dest
="branch"),
332 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
333 optparse
.make_option("--changesfile", dest
="changesFile"),
334 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
335 optparse
.make_option("--known-branches", dest
="knownBranches"),
336 optparse
.make_option("--cache", dest
="doCache", action
="store_true"),
337 optparse
.make_option("--command-cache", dest
="commandCache", action
="store_true")
339 self
.description
= """Imports from Perforce into a git repository.\n
341 //depot/my/project/ -- to import the current head
342 //depot/my/project/@all -- to import everything
343 //depot/my/project/@1,6 -- to import only from revision 1 to 6
345 (a ... is not needed in the path p4 specification, it's added implicitly)"""
347 self
.usage
+= " //depot/path[@revRange]"
349 self
.dataCache
= False
350 self
.commandCache
= False
352 self
.knownBranches
= Set()
353 self
.createdBranches
= Set()
354 self
.committedChanges
= Set()
355 self
.branch
= "master"
356 self
.detectBranches
= False
357 self
.changesFile
= ""
359 def p4File(self
, depotPath
):
360 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
362 def extractFilesFromCommit(self
, commit
):
365 while commit
.has_key("depotFile%s" % fnum
):
366 path
= commit
["depotFile%s" % fnum
]
367 if not path
.startswith(self
.globalPrefix
):
368 # if not self.silent:
369 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.globalPrefix, change)
375 file["rev"] = commit
["rev%s" % fnum
]
376 file["action"] = commit
["action%s" % fnum
]
377 file["type"] = commit
["type%s" % fnum
]
382 def isSubPathOf(self
, first
, second
):
383 if not first
.startswith(second
):
387 return first
[len(second
)] == "/"
389 def branchesForCommit(self
, files
):
393 relativePath
= file["path"][len(self
.globalPrefix
):]
394 # strip off the filename
395 relativePath
= relativePath
[0:relativePath
.rfind("/")]
397 # if len(branches) == 0:
398 # branches.add(relativePath)
399 # knownBranches.add(relativePath)
402 ###### this needs more testing :)
404 for branch
in branches
:
405 if relativePath
== branch
:
408 # if relativePath.startswith(branch):
409 if self
.isSubPathOf(relativePath
, branch
):
412 # if branch.startswith(relativePath):
413 if self
.isSubPathOf(branch
, relativePath
):
414 branches
.remove(branch
)
420 for branch
in knownBranches
:
421 #if relativePath.startswith(branch):
422 if self
.isSubPathOf(relativePath
, branch
):
423 if len(branches
) == 0:
424 relativePath
= branch
432 branches
.add(relativePath
)
433 self
.knownBranches
.add(relativePath
)
437 def findBranchParent(self
, branchPrefix
, files
):
440 if not path
.startswith(branchPrefix
):
442 action
= file["action"]
443 if action
!= "integrate" and action
!= "branch":
446 depotPath
= path
+ "#" + rev
448 log
= p4CmdList("filelog \"%s\"" % depotPath
)
450 print "eek! I got confused by the filelog of %s" % depotPath
454 if log
["action0"] != action
:
455 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
458 branchAction
= log
["how0,0"]
459 # if branchAction == "branch into" or branchAction == "ignored":
460 # continue # ignore for branching
462 if not branchAction
.endswith(" from"):
463 continue # ignore for branching
464 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
467 source
= log
["file0,0"]
468 if source
.startswith(branchPrefix
):
471 lastSourceRev
= log
["erev0,0"]
473 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
474 if len(sourceLog
) != 1:
475 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
477 sourceLog
= sourceLog
[0]
479 relPath
= source
[len(self
.globalPrefix
):]
480 # strip off the filename
481 relPath
= relPath
[0:relPath
.rfind("/")]
483 for branch
in self
.knownBranches
:
484 if self
.isSubPathOf(relPath
, branch
):
485 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
488 # print "%s is not a subpath of branch %s" % (relPath, branch)
492 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= "", merged
= ""):
493 epoch
= details
["time"]
494 author
= details
["user"]
496 self
.gitStream
.write("commit %s\n" % branch
)
497 # gitStream.write("mark :%s\n" % details["change"])
498 self
.committedChanges
.add(int(details
["change"]))
500 if author
in self
.users
:
501 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
503 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
505 self
.gitStream
.write("committer %s\n" % committer
)
507 self
.gitStream
.write("data <<EOT\n")
508 self
.gitStream
.write(details
["desc"])
509 self
.gitStream
.write("\n[ imported from %s; change %s ]\n" % (branchPrefix
, details
["change"]))
510 self
.gitStream
.write("EOT\n\n")
513 self
.gitStream
.write("from %s\n" % parent
)
516 self
.gitStream
.write("merge %s\n" % merged
)
520 if not path
.startswith(branchPrefix
):
522 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
525 depotPath
= path
+ "#" + rev
526 relPath
= path
[len(branchPrefix
):]
527 action
= file["action"]
529 if file["type"] == "apple":
530 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
533 if action
== "delete":
534 self
.gitStream
.write("D %s\n" % relPath
)
537 if file["type"].startswith("x"):
540 data
= self
.p4File(depotPath
)
542 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
543 self
.gitStream
.write("data %s\n" % len(data
))
544 self
.gitStream
.write(data
)
545 self
.gitStream
.write("\n")
547 self
.gitStream
.write("\n")
549 self
.lastChange
= int(details
["change"])
551 def extractFilesInCommitToBranch(self
, files
, branchPrefix
):
556 if path
.startswith(branchPrefix
):
557 newFiles
.append(file)
561 def findBranchSourceHeuristic(self
, files
, branch
, branchPrefix
):
563 action
= file["action"]
564 if action
!= "integrate" and action
!= "branch":
568 depotPath
= path
+ "#" + rev
570 log
= p4CmdList("filelog \"%s\"" % depotPath
)
572 print "eek! I got confused by the filelog of %s" % depotPath
576 if log
["action0"] != action
:
577 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
580 branchAction
= log
["how0,0"]
582 if not branchAction
.endswith(" from"):
583 continue # ignore for branching
584 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
587 source
= log
["file0,0"]
588 if source
.startswith(branchPrefix
):
591 lastSourceRev
= log
["erev0,0"]
593 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
594 if len(sourceLog
) != 1:
595 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
597 sourceLog
= sourceLog
[0]
599 relPath
= source
[len(self
.globalPrefix
):]
600 # strip off the filename
601 relPath
= relPath
[0:relPath
.rfind("/")]
603 for candidate
in self
.knownBranches
:
604 if self
.isSubPathOf(relPath
, candidate
) and candidate
!= branch
:
609 def changeIsBranchMerge(self
, sourceBranch
, destinationBranch
, change
):
611 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ sourceBranch
+ "/", change
)):
612 if file["action"] == "delete":
614 sourceFiles
[file["depotFile"]] = file
616 destinationFiles
= {}
617 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ destinationBranch
+ "/", change
)):
618 destinationFiles
[file["depotFile"]] = file
620 for fileName
in sourceFiles
.keys():
624 for integration
in p4CmdList("integrated \"%s\"" % fileName
):
625 toFile
= integration
["fromFile"] # yes, it's true, it's fromFile
626 if not toFile
in destinationFiles
:
628 destFile
= destinationFiles
[toFile
]
629 if destFile
["action"] == "delete":
630 # print "file %s has been deleted in %s" % (fileName, toFile)
633 integrationCount
+= 1
634 if integration
["how"] == "branch from":
637 if int(integration
["change"]) == change
:
638 integrations
.append(integration
)
640 if int(integration
["change"]) > change
:
643 destRev
= int(destFile
["rev"])
645 startRev
= integration
["startFromRev"][1:]
646 if startRev
== "none":
649 startRev
= int(startRev
)
651 endRev
= integration
["endFromRev"][1:]
657 initialBranch
= (destRev
== 1 and integration
["how"] != "branch into")
658 inRange
= (destRev
>= startRev
and destRev
<= endRev
)
659 newer
= (destRev
> startRev
and destRev
> endRev
)
661 if initialBranch
or inRange
or newer
:
662 integrations
.append(integration
)
667 if len(integrations
) == 0 and integrationCount
> 1:
668 print "file %s was not integrated from %s into %s" % (fileName
, sourceBranch
, destinationBranch
)
673 def getUserMap(self
):
676 for output
in p4CmdList("users"):
677 if not output
.has_key("User"):
679 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
682 self
.branch
= "refs/heads/" + self
.branch
683 self
.globalPrefix
= self
.previousDepotPath
= os
.popen("git-repo-config --get p4.depotpath").read()
684 if len(self
.globalPrefix
) != 0:
685 self
.globalPrefix
= self
.globalPrefix
[:-1]
687 if len(args
) == 0 and len(self
.globalPrefix
) != 0:
689 print "[using previously specified depot path %s]" % self
.globalPrefix
693 if len(self
.globalPrefix
) != 0 and self
.globalPrefix
!= args
[0]:
694 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.globalPrefix
, args
[0])
696 self
.globalPrefix
= args
[0]
698 self
.changeRange
= ""
701 self
.initialParent
= ""
705 if self
.globalPrefix
.find("@") != -1:
706 atIdx
= self
.globalPrefix
.index("@")
707 self
.changeRange
= self
.globalPrefix
[atIdx
:]
708 if self
.changeRange
== "@all":
709 self
.changeRange
= ""
710 elif self
.changeRange
.find(",") == -1:
711 self
.revision
= self
.changeRange
712 self
.changeRange
= ""
713 self
.globalPrefix
= self
.globalPrefix
[0:atIdx
]
714 elif self
.globalPrefix
.find("#") != -1:
715 hashIdx
= self
.globalPrefix
.index("#")
716 self
.revision
= self
.globalPrefix
[hashIdx
:]
717 self
.globalPrefix
= self
.globalPrefix
[0:hashIdx
]
718 elif len(self
.previousDepotPath
) == 0:
719 self
.revision
= "#head"
721 if self
.globalPrefix
.endswith("..."):
722 self
.globalPrefix
= self
.globalPrefix
[:-3]
724 if not self
.globalPrefix
.endswith("/"):
725 self
.globalPrefix
+= "/"
729 if len(self
.changeRange
) == 0:
731 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % self
.branch
)
733 if output
.endswith("\n"):
735 tagIdx
= output
.index(" tags/p4/")
736 caretIdx
= output
.find("^")
740 self
.rev
= int(output
[tagIdx
+ 9 : endPos
]) + 1
741 self
.changeRange
= "@%s,#head" % self
.rev
742 self
.initialParent
= os
.popen("git-rev-parse %s" % self
.branch
).read()[:-1]
743 self
.initialTag
= "p4/%s" % (int(self
.rev
) - 1)
747 self
.tz
= - time
.timezone
/ 36
748 tzsign
= ("%s" % self
.tz
)[0]
749 if tzsign
!= '+' and tzsign
!= '-':
750 self
.tz
= "+" + ("%s" % self
.tz
)
752 self
.gitOutput
, self
.gitStream
, self
.gitError
= popen2
.popen3("git-fast-import")
754 if len(self
.revision
) > 0:
755 print "Doing initial import of %s from revision %s" % (self
.globalPrefix
, self
.revision
)
757 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
758 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.globalPrefix
, self
.revision
)
759 details
["change"] = self
.revision
763 for info
in p4CmdList("files %s...%s" % (self
.globalPrefix
, self
.revision
)):
764 change
= int(info
["change"])
765 if change
> newestRevision
:
766 newestRevision
= change
768 if info
["action"] == "delete":
769 fileCnt
= fileCnt
+ 1
772 for prop
in [ "depotFile", "rev", "action", "type" ]:
773 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
775 fileCnt
= fileCnt
+ 1
777 details
["change"] = newestRevision
780 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.globalPrefix
)
782 print self
.gitError
.read()
787 if len(self
.changesFile
) > 0:
788 output
= open(self
.changesFile
).readlines()
791 changeSet
.add(int(line
))
793 for change
in changeSet
:
794 changes
.append(change
)
798 output
= os
.popen("p4 changes %s...%s" % (self
.globalPrefix
, self
.changeRange
)).readlines()
801 changeNum
= line
.split(" ")[1]
802 changes
.append(changeNum
)
806 if len(changes
) == 0:
808 print "no changes to import!"
812 for change
in changes
:
813 description
= p4Cmd("describe %s" % change
)
816 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
821 files
= self
.extractFilesFromCommit(description
)
822 if self
.detectBranches
:
823 for branch
in self
.branchesForCommit(files
):
824 self
.knownBranches
.add(branch
)
825 branchPrefix
= self
.globalPrefix
+ branch
+ "/"
827 filesForCommit
= self
.extractFilesInCommitToBranch(files
, branchPrefix
)
831 ########### remove cnt!!!
832 if branch
not in self
.createdBranches
and cnt
> 2:
833 self
.createdBranches
.add(branch
)
834 parent
= self
.findBranchParent(branchPrefix
, files
)
837 # elif len(parent) > 0:
838 # print "%s branched off of %s" % (branch, parent)
841 merged
= self
.findBranchSourceHeuristic(filesForCommit
, branch
, branchPrefix
)
843 print "change %s could be a merge from %s into %s" % (description
["change"], merged
, branch
)
844 if not self
.changeIsBranchMerge(merged
, branch
, int(description
["change"])):
847 branch
= "refs/heads/" + branch
849 parent
= "refs/heads/" + parent
851 merged
= "refs/heads/" + merged
852 self
.commit(description
, files
, branch
, branchPrefix
, parent
, merged
)
854 self
.commit(description
, files
, self
.branch
, self
.globalPrefix
, self
.initialParent
)
855 self
.initialParent
= ""
857 print self
.gitError
.read()
863 self
.gitStream
.write("reset refs/tags/p4/%s\n" % self
.lastChange
)
864 self
.gitStream
.write("from %s\n\n" % self
.branch
);
867 self
.gitStream
.close()
868 self
.gitOutput
.close()
869 self
.gitError
.close()
871 os
.popen("git-repo-config p4.depotpath %s" % self
.globalPrefix
).read()
872 if len(self
.initialTag
) > 0:
873 os
.popen("git tag -d %s" % self
.initialTag
).read()
877 class HelpFormatter(optparse
.IndentedHelpFormatter
):
879 optparse
.IndentedHelpFormatter
.__init
__(self
)
881 def format_description(self
, description
):
883 return description
+ "\n"
887 def printUsage(commands
):
888 print "usage: %s <command> [options]" % sys
.argv
[0]
890 print "valid commands: %s" % ", ".join(commands
)
892 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
897 "clean-tags" : P4CleanTags(),
902 if len(sys
.argv
[1:]) == 0:
903 printUsage(commands
.keys())
907 cmdName
= sys
.argv
[1]
909 cmd
= commands
[cmdName
]
911 print "unknown command %s" % cmdName
913 printUsage(commands
.keys())
916 options
= cmd
.options
918 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
920 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
922 description
= cmd
.description
,
923 formatter
= HelpFormatter())
925 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
930 if not isValidGitDir(gitdir
):
931 cdup
= os
.popen("git-rev-parse --show-cdup").read()[:-1]
932 if isValidGitDir(cdup
+ "/" + gitdir
):
935 if not isValidGitDir(gitdir
):
936 if isValidGitDir(gitdir
+ "/.git"):
939 die("fatal: cannot locate git repository at %s" % gitdir
)
941 os
.environ
["GIT_DIR"] = gitdir
943 if not cmd
.run(args
):