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
)
55 def extractLogMessageFromGitCommit(commit
):
58 for log
in os
.popen("git-cat-file commit %s" % commit
).readlines():
67 def extractDepotPathAndChangeFromGitLog(log
):
69 for line
in log
.split("\n"):
71 if line
.startswith("[git-p4:") and line
.endswith("]"):
72 line
= line
[8:-1].strip()
73 for assignment
in line
.split(":"):
74 variable
= assignment
.strip()
76 equalPos
= assignment
.find("=")
78 variable
= assignment
[:equalPos
].strip()
79 value
= assignment
[equalPos
+ 1:].strip()
80 if value
.startswith("\"") and value
.endswith("\""):
82 values
[variable
] = value
84 return values
.get("depot-path"), values
.get("change")
86 def gitBranchExists(branch
):
87 return os
.system("git-rev-parse %s 2>/dev/null >/dev/null") == 0
91 self
.usage
= "usage: %prog [options]"
93 class P4Debug(Command
):
95 Command
.__init
__(self
)
98 self
.description
= "A tool to debug the output of p4 -G."
101 for output
in p4CmdList(" ".join(args
)):
105 class P4CleanTags(Command
):
107 Command
.__init
__(self
)
109 # optparse.make_option("--branch", dest="branch", default="refs/heads/master")
111 self
.description
= "A tool to remove stale unused tags from incremental perforce imports."
113 branch
= currentGitBranch()
114 print "Cleaning out stale p4 import tags..."
115 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % branch
)
118 tagIdx
= output
.index(" tags/p4/")
120 print "Cannot find any p4/* tag. Nothing to do."
124 caretIdx
= output
.index("^")
126 caretIdx
= len(output
) - 1
127 rev
= int(output
[tagIdx
+ 9 : caretIdx
])
129 allTags
= os
.popen("git tag -l p4/").readlines()
130 for i
in range(len(allTags
)):
131 allTags
[i
] = int(allTags
[i
][3:-1])
138 print os
.popen("git tag -d p4/%s" % rev
).read()
140 print "%s tags removed." % len(allTags
)
143 class P4Sync(Command
):
145 Command
.__init
__(self
)
147 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
148 optparse
.make_option("--origin", dest
="origin"),
149 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
150 optparse
.make_option("--master", dest
="master"),
151 optparse
.make_option("--log-substitutions", dest
="substFile"),
152 optparse
.make_option("--noninteractive", action
="store_false"),
153 optparse
.make_option("--dry-run", action
="store_true"),
154 optparse
.make_option("--apply-as-patch", action
="store_true", dest
="applyAsPatch")
156 self
.description
= "Submit changes from git to the perforce depot."
157 self
.firstTime
= True
159 self
.interactive
= True
162 self
.firstTime
= True
163 self
.origin
= "origin"
165 self
.applyAsPatch
= True
167 self
.logSubstitutions
= {}
168 self
.logSubstitutions
["<enter description here>"] = "%log%"
169 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
172 if len(p4CmdList("opened ...")) > 0:
173 die("You have files opened with perforce! Close them before starting the sync.")
176 if len(self
.config
) > 0 and not self
.reset
:
177 die("Cannot start sync. Previous sync config found at %s" % self
.configFile
)
180 for line
in os
.popen("git-rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
181 commits
.append(line
[:-1])
184 self
.config
["commits"] = commits
186 if not self
.applyAsPatch
:
187 print "Creating temporary p4-sync branch from %s ..." % self
.origin
188 system("git checkout -f -b p4-sync %s" % self
.origin
)
190 def prepareLogMessage(self
, template
, message
):
193 for line
in template
.split("\n"):
194 if line
.startswith("#"):
195 result
+= line
+ "\n"
199 for key
in self
.logSubstitutions
.keys():
200 if line
.find(key
) != -1:
201 value
= self
.logSubstitutions
[key
]
202 value
= value
.replace("%log%", message
)
203 if value
!= "@remove@":
204 result
+= line
.replace(key
, value
) + "\n"
209 result
+= line
+ "\n"
214 print "Applying %s" % (os
.popen("git-log --max-count=1 --pretty=oneline %s" % id).read())
215 diff
= os
.popen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
217 filesToDelete
= set()
220 path
= line
[1:].strip()
222 system("p4 edit %s" % path
)
223 elif modifier
== "A":
225 if path
in filesToDelete
:
226 filesToDelete
.remove(path
)
227 elif modifier
== "D":
228 filesToDelete
.add(path
)
229 if path
in filesToAdd
:
230 filesToAdd
.remove(path
)
232 die("unknown modifier %s for %s" % (modifier
, path
))
234 if self
.applyAsPatch
:
235 system("git-diff-tree -p --diff-filter=ACMRTUXB \"%s^\" \"%s\" | patch -p1" % (id, id))
237 system("git-diff-files --name-only -z | git-update-index --remove -z --stdin")
238 system("git cherry-pick --no-commit \"%s\"" % id)
241 system("p4 add %s" % f
)
242 for f
in filesToDelete
:
243 system("p4 revert %s" % f
)
244 system("p4 delete %s" % f
)
246 logMessage
= extractLogMessageFromGitCommit(id)
247 logMessage
= logMessage
.replace("\n", "\n\t")
248 logMessage
= logMessage
[:-1]
250 template
= os
.popen("p4 change -o").read()
253 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
254 diff
= os
.popen("p4 diff -du ...").read()
256 for newFile
in filesToAdd
:
257 diff
+= "==== new file ====\n"
258 diff
+= "--- /dev/null\n"
259 diff
+= "+++ %s\n" % newFile
260 f
= open(newFile
, "r")
261 for line
in f
.readlines():
265 separatorLine
= "######## everything below this line is just the diff #######\n"
268 firstIteration
= True
269 while response
== "e":
270 if not firstIteration
:
271 response
= raw_input("Do you want to submit this change (y/e/n)? ")
272 firstIteration
= False
274 [handle
, fileName
] = tempfile
.mkstemp()
275 tmpFile
= os
.fdopen(handle
, "w+")
276 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
278 editor
= os
.environ
.get("EDITOR", "vi")
279 system(editor
+ " " + fileName
)
280 tmpFile
= open(fileName
, "r")
281 message
= tmpFile
.read()
284 submitTemplate
= message
[:message
.index(separatorLine
)]
286 if response
== "y" or response
== "yes":
289 raw_input("Press return to continue...")
291 pipe
= os
.popen("p4 submit -i", "w")
292 pipe
.write(submitTemplate
)
295 print "Not submitting!"
296 self
.interactive
= False
298 fileName
= "submit.txt"
299 file = open(fileName
, "w+")
300 file.write(self
.prepareLogMessage(template
, logMessage
))
302 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
306 self
.firstTime
= True
308 if len(self
.substFile
) > 0:
309 for line
in open(self
.substFile
, "r").readlines():
310 tokens
= line
[:-1].split("=")
311 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
313 if len(self
.master
) == 0:
314 self
.master
= currentGitBranch()
315 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
316 die("Detecting current git branch failed!")
319 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
320 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
325 commits
= self
.config
.get("commits", [])
327 while len(commits
) > 0:
328 self
.firstTime
= False
330 commits
= commits
[1:]
331 self
.config
["commits"] = commits
333 if not self
.interactive
:
338 if len(commits
) == 0:
340 print "No changes found to apply between %s and current HEAD" % self
.origin
342 print "All changes applied!"
343 if not self
.applyAsPatch
:
344 print "Deleting temporary p4-sync branch and going back to %s" % self
.master
345 system("git checkout %s" % self
.master
)
346 system("git branch -D p4-sync")
347 print "Cleaning out your perforce checkout by doing p4 edit ... ; p4 revert ..."
348 system("p4 edit ... >/dev/null")
349 system("p4 revert ... >/dev/null")
350 os
.remove(self
.configFile
)
354 class GitSync(Command
):
356 Command
.__init
__(self
)
358 optparse
.make_option("--branch", dest
="branch"),
359 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
360 optparse
.make_option("--changesfile", dest
="changesFile"),
361 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
362 optparse
.make_option("--known-branches", dest
="knownBranches"),
363 optparse
.make_option("--cache", dest
="doCache", action
="store_true"),
364 optparse
.make_option("--command-cache", dest
="commandCache", action
="store_true")
366 self
.description
= """Imports from Perforce into a git repository.\n
368 //depot/my/project/ -- to import the current head
369 //depot/my/project/@all -- to import everything
370 //depot/my/project/@1,6 -- to import only from revision 1 to 6
372 (a ... is not needed in the path p4 specification, it's added implicitly)"""
374 self
.usage
+= " //depot/path[@revRange]"
376 self
.dataCache
= False
377 self
.commandCache
= False
379 self
.knownBranches
= Set()
380 self
.createdBranches
= Set()
381 self
.committedChanges
= Set()
383 self
.detectBranches
= False
384 self
.changesFile
= ""
386 def p4File(self
, depotPath
):
387 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
389 def extractFilesFromCommit(self
, commit
):
392 while commit
.has_key("depotFile%s" % fnum
):
393 path
= commit
["depotFile%s" % fnum
]
394 if not path
.startswith(self
.globalPrefix
):
395 # if not self.silent:
396 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.globalPrefix, change)
402 file["rev"] = commit
["rev%s" % fnum
]
403 file["action"] = commit
["action%s" % fnum
]
404 file["type"] = commit
["type%s" % fnum
]
409 def isSubPathOf(self
, first
, second
):
410 if not first
.startswith(second
):
414 return first
[len(second
)] == "/"
416 def branchesForCommit(self
, files
):
420 relativePath
= file["path"][len(self
.globalPrefix
):]
421 # strip off the filename
422 relativePath
= relativePath
[0:relativePath
.rfind("/")]
424 # if len(branches) == 0:
425 # branches.add(relativePath)
426 # knownBranches.add(relativePath)
429 ###### this needs more testing :)
431 for branch
in branches
:
432 if relativePath
== branch
:
435 # if relativePath.startswith(branch):
436 if self
.isSubPathOf(relativePath
, branch
):
439 # if branch.startswith(relativePath):
440 if self
.isSubPathOf(branch
, relativePath
):
441 branches
.remove(branch
)
447 for branch
in knownBranches
:
448 #if relativePath.startswith(branch):
449 if self
.isSubPathOf(relativePath
, branch
):
450 if len(branches
) == 0:
451 relativePath
= branch
459 branches
.add(relativePath
)
460 self
.knownBranches
.add(relativePath
)
464 def findBranchParent(self
, branchPrefix
, files
):
467 if not path
.startswith(branchPrefix
):
469 action
= file["action"]
470 if action
!= "integrate" and action
!= "branch":
473 depotPath
= path
+ "#" + rev
475 log
= p4CmdList("filelog \"%s\"" % depotPath
)
477 print "eek! I got confused by the filelog of %s" % depotPath
481 if log
["action0"] != action
:
482 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
485 branchAction
= log
["how0,0"]
486 # if branchAction == "branch into" or branchAction == "ignored":
487 # continue # ignore for branching
489 if not branchAction
.endswith(" from"):
490 continue # ignore for branching
491 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
494 source
= log
["file0,0"]
495 if source
.startswith(branchPrefix
):
498 lastSourceRev
= log
["erev0,0"]
500 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
501 if len(sourceLog
) != 1:
502 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
504 sourceLog
= sourceLog
[0]
506 relPath
= source
[len(self
.globalPrefix
):]
507 # strip off the filename
508 relPath
= relPath
[0:relPath
.rfind("/")]
510 for branch
in self
.knownBranches
:
511 if self
.isSubPathOf(relPath
, branch
):
512 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
515 # print "%s is not a subpath of branch %s" % (relPath, branch)
519 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= "", merged
= ""):
520 epoch
= details
["time"]
521 author
= details
["user"]
523 self
.gitStream
.write("commit %s\n" % branch
)
524 # gitStream.write("mark :%s\n" % details["change"])
525 self
.committedChanges
.add(int(details
["change"]))
527 if author
in self
.users
:
528 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
530 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
532 self
.gitStream
.write("committer %s\n" % committer
)
534 self
.gitStream
.write("data <<EOT\n")
535 self
.gitStream
.write(details
["desc"])
536 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
537 self
.gitStream
.write("EOT\n\n")
540 self
.gitStream
.write("from %s\n" % parent
)
543 self
.gitStream
.write("merge %s\n" % merged
)
547 if not path
.startswith(branchPrefix
):
549 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
552 depotPath
= path
+ "#" + rev
553 relPath
= path
[len(branchPrefix
):]
554 action
= file["action"]
556 if file["type"] == "apple":
557 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
560 if action
== "delete":
561 self
.gitStream
.write("D %s\n" % relPath
)
564 if file["type"].startswith("x"):
567 data
= self
.p4File(depotPath
)
569 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
570 self
.gitStream
.write("data %s\n" % len(data
))
571 self
.gitStream
.write(data
)
572 self
.gitStream
.write("\n")
574 self
.gitStream
.write("\n")
576 self
.lastChange
= int(details
["change"])
578 def extractFilesInCommitToBranch(self
, files
, branchPrefix
):
583 if path
.startswith(branchPrefix
):
584 newFiles
.append(file)
588 def findBranchSourceHeuristic(self
, files
, branch
, branchPrefix
):
590 action
= file["action"]
591 if action
!= "integrate" and action
!= "branch":
595 depotPath
= path
+ "#" + rev
597 log
= p4CmdList("filelog \"%s\"" % depotPath
)
599 print "eek! I got confused by the filelog of %s" % depotPath
603 if log
["action0"] != action
:
604 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
607 branchAction
= log
["how0,0"]
609 if not branchAction
.endswith(" from"):
610 continue # ignore for branching
611 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
614 source
= log
["file0,0"]
615 if source
.startswith(branchPrefix
):
618 lastSourceRev
= log
["erev0,0"]
620 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
621 if len(sourceLog
) != 1:
622 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
624 sourceLog
= sourceLog
[0]
626 relPath
= source
[len(self
.globalPrefix
):]
627 # strip off the filename
628 relPath
= relPath
[0:relPath
.rfind("/")]
630 for candidate
in self
.knownBranches
:
631 if self
.isSubPathOf(relPath
, candidate
) and candidate
!= branch
:
636 def changeIsBranchMerge(self
, sourceBranch
, destinationBranch
, change
):
638 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ sourceBranch
+ "/", change
)):
639 if file["action"] == "delete":
641 sourceFiles
[file["depotFile"]] = file
643 destinationFiles
= {}
644 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ destinationBranch
+ "/", change
)):
645 destinationFiles
[file["depotFile"]] = file
647 for fileName
in sourceFiles
.keys():
651 for integration
in p4CmdList("integrated \"%s\"" % fileName
):
652 toFile
= integration
["fromFile"] # yes, it's true, it's fromFile
653 if not toFile
in destinationFiles
:
655 destFile
= destinationFiles
[toFile
]
656 if destFile
["action"] == "delete":
657 # print "file %s has been deleted in %s" % (fileName, toFile)
660 integrationCount
+= 1
661 if integration
["how"] == "branch from":
664 if int(integration
["change"]) == change
:
665 integrations
.append(integration
)
667 if int(integration
["change"]) > change
:
670 destRev
= int(destFile
["rev"])
672 startRev
= integration
["startFromRev"][1:]
673 if startRev
== "none":
676 startRev
= int(startRev
)
678 endRev
= integration
["endFromRev"][1:]
684 initialBranch
= (destRev
== 1 and integration
["how"] != "branch into")
685 inRange
= (destRev
>= startRev
and destRev
<= endRev
)
686 newer
= (destRev
> startRev
and destRev
> endRev
)
688 if initialBranch
or inRange
or newer
:
689 integrations
.append(integration
)
694 if len(integrations
) == 0 and integrationCount
> 1:
695 print "file %s was not integrated from %s into %s" % (fileName
, sourceBranch
, destinationBranch
)
700 def getUserMap(self
):
703 for output
in p4CmdList("users"):
704 if not output
.has_key("User"):
706 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
709 if len(self
.branch
) == 0:
712 self
.branch
= "refs/heads/" + self
.branch
713 self
.globalPrefix
= self
.previousDepotPath
= os
.popen("git-repo-config --get p4.depotpath").read()
714 if len(self
.globalPrefix
) != 0:
715 self
.globalPrefix
= self
.globalPrefix
[:-1]
717 if len(args
) == 0 and len(self
.globalPrefix
) != 0:
719 print "[using previously specified depot path %s]" % self
.globalPrefix
723 if len(self
.globalPrefix
) != 0 and self
.globalPrefix
!= args
[0]:
724 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.globalPrefix
, args
[0])
726 self
.globalPrefix
= args
[0]
728 self
.changeRange
= ""
731 self
.initialParent
= ""
735 if self
.globalPrefix
.find("@") != -1:
736 atIdx
= self
.globalPrefix
.index("@")
737 self
.changeRange
= self
.globalPrefix
[atIdx
:]
738 if self
.changeRange
== "@all":
739 self
.changeRange
= ""
740 elif self
.changeRange
.find(",") == -1:
741 self
.revision
= self
.changeRange
742 self
.changeRange
= ""
743 self
.globalPrefix
= self
.globalPrefix
[0:atIdx
]
744 elif self
.globalPrefix
.find("#") != -1:
745 hashIdx
= self
.globalPrefix
.index("#")
746 self
.revision
= self
.globalPrefix
[hashIdx
:]
747 self
.globalPrefix
= self
.globalPrefix
[0:hashIdx
]
748 elif len(self
.previousDepotPath
) == 0:
749 self
.revision
= "#head"
751 if self
.globalPrefix
.endswith("..."):
752 self
.globalPrefix
= self
.globalPrefix
[:-3]
754 if not self
.globalPrefix
.endswith("/"):
755 self
.globalPrefix
+= "/"
759 if len(self
.changeRange
) == 0:
761 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % self
.branch
)
763 if output
.endswith("\n"):
765 tagIdx
= output
.index(" tags/p4/")
766 caretIdx
= output
.find("^")
770 self
.rev
= int(output
[tagIdx
+ 9 : endPos
]) + 1
771 self
.changeRange
= "@%s,#head" % self
.rev
772 self
.initialParent
= os
.popen("git-rev-parse %s" % self
.branch
).read()[:-1]
773 self
.initialTag
= "p4/%s" % (int(self
.rev
) - 1)
777 self
.tz
= - time
.timezone
/ 36
778 tzsign
= ("%s" % self
.tz
)[0]
779 if tzsign
!= '+' and tzsign
!= '-':
780 self
.tz
= "+" + ("%s" % self
.tz
)
782 self
.gitOutput
, self
.gitStream
, self
.gitError
= popen2
.popen3("git-fast-import")
784 if len(self
.revision
) > 0:
785 print "Doing initial import of %s from revision %s" % (self
.globalPrefix
, self
.revision
)
787 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
788 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.globalPrefix
, self
.revision
)
789 details
["change"] = self
.revision
793 for info
in p4CmdList("files %s...%s" % (self
.globalPrefix
, self
.revision
)):
794 change
= int(info
["change"])
795 if change
> newestRevision
:
796 newestRevision
= change
798 if info
["action"] == "delete":
799 fileCnt
= fileCnt
+ 1
802 for prop
in [ "depotFile", "rev", "action", "type" ]:
803 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
805 fileCnt
= fileCnt
+ 1
807 details
["change"] = newestRevision
810 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.globalPrefix
)
812 print self
.gitError
.read()
817 if len(self
.changesFile
) > 0:
818 output
= open(self
.changesFile
).readlines()
821 changeSet
.add(int(line
))
823 for change
in changeSet
:
824 changes
.append(change
)
828 output
= os
.popen("p4 changes %s...%s" % (self
.globalPrefix
, self
.changeRange
)).readlines()
831 changeNum
= line
.split(" ")[1]
832 changes
.append(changeNum
)
836 if len(changes
) == 0:
838 print "no changes to import!"
842 for change
in changes
:
843 description
= p4Cmd("describe %s" % change
)
846 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
851 files
= self
.extractFilesFromCommit(description
)
852 if self
.detectBranches
:
853 for branch
in self
.branchesForCommit(files
):
854 self
.knownBranches
.add(branch
)
855 branchPrefix
= self
.globalPrefix
+ branch
+ "/"
857 filesForCommit
= self
.extractFilesInCommitToBranch(files
, branchPrefix
)
861 ########### remove cnt!!!
862 if branch
not in self
.createdBranches
and cnt
> 2:
863 self
.createdBranches
.add(branch
)
864 parent
= self
.findBranchParent(branchPrefix
, files
)
867 # elif len(parent) > 0:
868 # print "%s branched off of %s" % (branch, parent)
871 merged
= self
.findBranchSourceHeuristic(filesForCommit
, branch
, branchPrefix
)
873 print "change %s could be a merge from %s into %s" % (description
["change"], merged
, branch
)
874 if not self
.changeIsBranchMerge(merged
, branch
, int(description
["change"])):
877 branch
= "refs/heads/" + branch
879 parent
= "refs/heads/" + parent
881 merged
= "refs/heads/" + merged
882 self
.commit(description
, files
, branch
, branchPrefix
, parent
, merged
)
884 self
.commit(description
, files
, self
.branch
, self
.globalPrefix
, self
.initialParent
)
885 self
.initialParent
= ""
887 print self
.gitError
.read()
893 self
.gitStream
.write("reset refs/tags/p4/%s\n" % self
.lastChange
)
894 self
.gitStream
.write("from %s\n\n" % self
.branch
);
897 self
.gitStream
.close()
898 self
.gitOutput
.close()
899 self
.gitError
.close()
901 os
.popen("git-repo-config p4.depotpath %s" % self
.globalPrefix
).read()
902 if len(self
.initialTag
) > 0:
903 os
.popen("git tag -d %s" % self
.initialTag
).read()
907 class HelpFormatter(optparse
.IndentedHelpFormatter
):
909 optparse
.IndentedHelpFormatter
.__init
__(self
)
911 def format_description(self
, description
):
913 return description
+ "\n"
917 def printUsage(commands
):
918 print "usage: %s <command> [options]" % sys
.argv
[0]
920 print "valid commands: %s" % ", ".join(commands
)
922 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
927 "clean-tags" : P4CleanTags(),
932 if len(sys
.argv
[1:]) == 0:
933 printUsage(commands
.keys())
937 cmdName
= sys
.argv
[1]
939 cmd
= commands
[cmdName
]
941 print "unknown command %s" % cmdName
943 printUsage(commands
.keys())
946 options
= cmd
.options
948 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
950 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
952 description
= cmd
.description
,
953 formatter
= HelpFormatter())
955 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
960 if not isValidGitDir(gitdir
):
961 cdup
= os
.popen("git-rev-parse --show-cdup").read()[:-1]
962 if isValidGitDir(cdup
+ "/" + gitdir
):
965 if not isValidGitDir(gitdir
):
966 if isValidGitDir(gitdir
+ "/.git"):
969 die("fatal: cannot locate git repository at %s" % gitdir
)
971 os
.environ
["GIT_DIR"] = gitdir
973 if not cmd
.run(args
):