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 self
.branch
= "refs/heads/" + self
.branch
710 self
.globalPrefix
= self
.previousDepotPath
= os
.popen("git-repo-config --get p4.depotpath").read()
711 if len(self
.globalPrefix
) != 0:
712 self
.globalPrefix
= self
.globalPrefix
[:-1]
714 if len(args
) == 0 and len(self
.globalPrefix
) != 0:
716 print "[using previously specified depot path %s]" % self
.globalPrefix
720 if len(self
.globalPrefix
) != 0 and self
.globalPrefix
!= args
[0]:
721 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.globalPrefix
, args
[0])
723 self
.globalPrefix
= args
[0]
725 self
.changeRange
= ""
728 self
.initialParent
= ""
732 if self
.globalPrefix
.find("@") != -1:
733 atIdx
= self
.globalPrefix
.index("@")
734 self
.changeRange
= self
.globalPrefix
[atIdx
:]
735 if self
.changeRange
== "@all":
736 self
.changeRange
= ""
737 elif self
.changeRange
.find(",") == -1:
738 self
.revision
= self
.changeRange
739 self
.changeRange
= ""
740 self
.globalPrefix
= self
.globalPrefix
[0:atIdx
]
741 elif self
.globalPrefix
.find("#") != -1:
742 hashIdx
= self
.globalPrefix
.index("#")
743 self
.revision
= self
.globalPrefix
[hashIdx
:]
744 self
.globalPrefix
= self
.globalPrefix
[0:hashIdx
]
745 elif len(self
.previousDepotPath
) == 0:
746 self
.revision
= "#head"
748 if self
.globalPrefix
.endswith("..."):
749 self
.globalPrefix
= self
.globalPrefix
[:-3]
751 if not self
.globalPrefix
.endswith("/"):
752 self
.globalPrefix
+= "/"
756 if len(self
.changeRange
) == 0:
758 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % self
.branch
)
760 if output
.endswith("\n"):
762 tagIdx
= output
.index(" tags/p4/")
763 caretIdx
= output
.find("^")
767 self
.rev
= int(output
[tagIdx
+ 9 : endPos
]) + 1
768 self
.changeRange
= "@%s,#head" % self
.rev
769 self
.initialParent
= os
.popen("git-rev-parse %s" % self
.branch
).read()[:-1]
770 self
.initialTag
= "p4/%s" % (int(self
.rev
) - 1)
774 self
.tz
= - time
.timezone
/ 36
775 tzsign
= ("%s" % self
.tz
)[0]
776 if tzsign
!= '+' and tzsign
!= '-':
777 self
.tz
= "+" + ("%s" % self
.tz
)
779 self
.gitOutput
, self
.gitStream
, self
.gitError
= popen2
.popen3("git-fast-import")
781 if len(self
.revision
) > 0:
782 print "Doing initial import of %s from revision %s" % (self
.globalPrefix
, self
.revision
)
784 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
785 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.globalPrefix
, self
.revision
)
786 details
["change"] = self
.revision
790 for info
in p4CmdList("files %s...%s" % (self
.globalPrefix
, self
.revision
)):
791 change
= int(info
["change"])
792 if change
> newestRevision
:
793 newestRevision
= change
795 if info
["action"] == "delete":
796 fileCnt
= fileCnt
+ 1
799 for prop
in [ "depotFile", "rev", "action", "type" ]:
800 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
802 fileCnt
= fileCnt
+ 1
804 details
["change"] = newestRevision
807 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.globalPrefix
)
809 print self
.gitError
.read()
814 if len(self
.changesFile
) > 0:
815 output
= open(self
.changesFile
).readlines()
818 changeSet
.add(int(line
))
820 for change
in changeSet
:
821 changes
.append(change
)
825 output
= os
.popen("p4 changes %s...%s" % (self
.globalPrefix
, self
.changeRange
)).readlines()
828 changeNum
= line
.split(" ")[1]
829 changes
.append(changeNum
)
833 if len(changes
) == 0:
835 print "no changes to import!"
839 for change
in changes
:
840 description
= p4Cmd("describe %s" % change
)
843 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
848 files
= self
.extractFilesFromCommit(description
)
849 if self
.detectBranches
:
850 for branch
in self
.branchesForCommit(files
):
851 self
.knownBranches
.add(branch
)
852 branchPrefix
= self
.globalPrefix
+ branch
+ "/"
854 filesForCommit
= self
.extractFilesInCommitToBranch(files
, branchPrefix
)
858 ########### remove cnt!!!
859 if branch
not in self
.createdBranches
and cnt
> 2:
860 self
.createdBranches
.add(branch
)
861 parent
= self
.findBranchParent(branchPrefix
, files
)
864 # elif len(parent) > 0:
865 # print "%s branched off of %s" % (branch, parent)
868 merged
= self
.findBranchSourceHeuristic(filesForCommit
, branch
, branchPrefix
)
870 print "change %s could be a merge from %s into %s" % (description
["change"], merged
, branch
)
871 if not self
.changeIsBranchMerge(merged
, branch
, int(description
["change"])):
874 branch
= "refs/heads/" + branch
876 parent
= "refs/heads/" + parent
878 merged
= "refs/heads/" + merged
879 self
.commit(description
, files
, branch
, branchPrefix
, parent
, merged
)
881 self
.commit(description
, files
, self
.branch
, self
.globalPrefix
, self
.initialParent
)
882 self
.initialParent
= ""
884 print self
.gitError
.read()
890 self
.gitStream
.write("reset refs/tags/p4/%s\n" % self
.lastChange
)
891 self
.gitStream
.write("from %s\n\n" % self
.branch
);
894 self
.gitStream
.close()
895 self
.gitOutput
.close()
896 self
.gitError
.close()
898 os
.popen("git-repo-config p4.depotpath %s" % self
.globalPrefix
).read()
899 if len(self
.initialTag
) > 0:
900 os
.popen("git tag -d %s" % self
.initialTag
).read()
904 class HelpFormatter(optparse
.IndentedHelpFormatter
):
906 optparse
.IndentedHelpFormatter
.__init
__(self
)
908 def format_description(self
, description
):
910 return description
+ "\n"
914 def printUsage(commands
):
915 print "usage: %s <command> [options]" % sys
.argv
[0]
917 print "valid commands: %s" % ", ".join(commands
)
919 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
924 "clean-tags" : P4CleanTags(),
929 if len(sys
.argv
[1:]) == 0:
930 printUsage(commands
.keys())
934 cmdName
= sys
.argv
[1]
936 cmd
= commands
[cmdName
]
938 print "unknown command %s" % cmdName
940 printUsage(commands
.keys())
943 options
= cmd
.options
945 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
947 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
949 description
= cmd
.description
,
950 formatter
= HelpFormatter())
952 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
957 if not isValidGitDir(gitdir
):
958 cdup
= os
.popen("git-rev-parse --show-cdup").read()[:-1]
959 if isValidGitDir(cdup
+ "/" + gitdir
):
962 if not isValidGitDir(gitdir
):
963 if isValidGitDir(gitdir
+ "/.git"):
966 die("fatal: cannot locate git repository at %s" % gitdir
)
968 os
.environ
["GIT_DIR"] = gitdir
970 if not cmd
.run(args
):