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")
88 self
.usage
= "usage: %prog [options]"
90 class P4Debug(Command
):
92 Command
.__init
__(self
)
95 self
.description
= "A tool to debug the output of p4 -G."
98 for output
in p4CmdList(" ".join(args
)):
102 class P4CleanTags(Command
):
104 Command
.__init
__(self
)
106 # optparse.make_option("--branch", dest="branch", default="refs/heads/master")
108 self
.description
= "A tool to remove stale unused tags from incremental perforce imports."
110 branch
= currentGitBranch()
111 print "Cleaning out stale p4 import tags..."
112 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % branch
)
115 tagIdx
= output
.index(" tags/p4/")
117 print "Cannot find any p4/* tag. Nothing to do."
121 caretIdx
= output
.index("^")
123 caretIdx
= len(output
) - 1
124 rev
= int(output
[tagIdx
+ 9 : caretIdx
])
126 allTags
= os
.popen("git tag -l p4/").readlines()
127 for i
in range(len(allTags
)):
128 allTags
[i
] = int(allTags
[i
][3:-1])
135 print os
.popen("git tag -d p4/%s" % rev
).read()
137 print "%s tags removed." % len(allTags
)
140 class P4Sync(Command
):
142 Command
.__init
__(self
)
144 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
145 optparse
.make_option("--origin", dest
="origin"),
146 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
147 optparse
.make_option("--master", dest
="master"),
148 optparse
.make_option("--log-substitutions", dest
="substFile"),
149 optparse
.make_option("--noninteractive", action
="store_false"),
150 optparse
.make_option("--dry-run", action
="store_true"),
151 optparse
.make_option("--apply-as-patch", action
="store_true", dest
="applyAsPatch")
153 self
.description
= "Submit changes from git to the perforce depot."
154 self
.firstTime
= True
156 self
.interactive
= True
159 self
.firstTime
= True
160 self
.origin
= "origin"
162 self
.applyAsPatch
= True
164 self
.logSubstitutions
= {}
165 self
.logSubstitutions
["<enter description here>"] = "%log%"
166 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
169 if len(p4CmdList("opened ...")) > 0:
170 die("You have files opened with perforce! Close them before starting the sync.")
173 if len(self
.config
) > 0 and not self
.reset
:
174 die("Cannot start sync. Previous sync config found at %s" % self
.configFile
)
177 for line
in os
.popen("git-rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
178 commits
.append(line
[:-1])
181 self
.config
["commits"] = commits
183 if not self
.applyAsPatch
:
184 print "Creating temporary p4-sync branch from %s ..." % self
.origin
185 system("git checkout -f -b p4-sync %s" % self
.origin
)
187 def prepareLogMessage(self
, template
, message
):
190 for line
in template
.split("\n"):
191 if line
.startswith("#"):
192 result
+= line
+ "\n"
196 for key
in self
.logSubstitutions
.keys():
197 if line
.find(key
) != -1:
198 value
= self
.logSubstitutions
[key
]
199 value
= value
.replace("%log%", message
)
200 if value
!= "@remove@":
201 result
+= line
.replace(key
, value
) + "\n"
206 result
+= line
+ "\n"
211 print "Applying %s" % (os
.popen("git-log --max-count=1 --pretty=oneline %s" % id).read())
212 diff
= os
.popen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
214 filesToDelete
= set()
217 path
= line
[1:].strip()
219 system("p4 edit %s" % path
)
220 elif modifier
== "A":
222 if path
in filesToDelete
:
223 filesToDelete
.remove(path
)
224 elif modifier
== "D":
225 filesToDelete
.add(path
)
226 if path
in filesToAdd
:
227 filesToAdd
.remove(path
)
229 die("unknown modifier %s for %s" % (modifier
, path
))
231 if self
.applyAsPatch
:
232 system("git-diff-tree -p --diff-filter=ACMRTUXB \"%s^\" \"%s\" | patch -p1" % (id, id))
234 system("git-diff-files --name-only -z | git-update-index --remove -z --stdin")
235 system("git cherry-pick --no-commit \"%s\"" % id)
238 system("p4 add %s" % f
)
239 for f
in filesToDelete
:
240 system("p4 revert %s" % f
)
241 system("p4 delete %s" % f
)
243 logMessage
= extractLogMessageFromGitCommit(id)
244 logMessage
= logMessage
.replace("\n", "\n\t")
245 logMessage
= logMessage
[:-1]
247 template
= os
.popen("p4 change -o").read()
250 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
251 diff
= os
.popen("p4 diff -du ...").read()
253 for newFile
in filesToAdd
:
254 diff
+= "==== new file ====\n"
255 diff
+= "--- /dev/null\n"
256 diff
+= "+++ %s\n" % newFile
257 f
= open(newFile
, "r")
258 for line
in f
.readlines():
262 separatorLine
= "######## everything below this line is just the diff #######\n"
265 firstIteration
= True
266 while response
== "e":
267 if not firstIteration
:
268 response
= raw_input("Do you want to submit this change (y/e/n)? ")
269 firstIteration
= False
271 [handle
, fileName
] = tempfile
.mkstemp()
272 tmpFile
= os
.fdopen(handle
, "w+")
273 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
275 editor
= os
.environ
.get("EDITOR", "vi")
276 system(editor
+ " " + fileName
)
277 tmpFile
= open(fileName
, "r")
278 message
= tmpFile
.read()
281 submitTemplate
= message
[:message
.index(separatorLine
)]
283 if response
== "y" or response
== "yes":
286 raw_input("Press return to continue...")
288 pipe
= os
.popen("p4 submit -i", "w")
289 pipe
.write(submitTemplate
)
292 print "Not submitting!"
293 self
.interactive
= False
295 fileName
= "submit.txt"
296 file = open(fileName
, "w+")
297 file.write(self
.prepareLogMessage(template
, logMessage
))
299 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
303 self
.firstTime
= True
305 if len(self
.substFile
) > 0:
306 for line
in open(self
.substFile
, "r").readlines():
307 tokens
= line
[:-1].split("=")
308 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
310 if len(self
.master
) == 0:
311 self
.master
= currentGitBranch()
312 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
313 die("Detecting current git branch failed!")
316 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
317 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
322 commits
= self
.config
.get("commits", [])
324 while len(commits
) > 0:
325 self
.firstTime
= False
327 commits
= commits
[1:]
328 self
.config
["commits"] = commits
330 if not self
.interactive
:
335 if len(commits
) == 0:
337 print "No changes found to apply between %s and current HEAD" % self
.origin
339 print "All changes applied!"
340 if not self
.applyAsPatch
:
341 print "Deleting temporary p4-sync branch and going back to %s" % self
.master
342 system("git checkout %s" % self
.master
)
343 system("git branch -D p4-sync")
344 print "Cleaning out your perforce checkout by doing p4 edit ... ; p4 revert ..."
345 system("p4 edit ... >/dev/null")
346 system("p4 revert ... >/dev/null")
347 os
.remove(self
.configFile
)
351 class GitSync(Command
):
353 Command
.__init
__(self
)
355 optparse
.make_option("--branch", dest
="branch"),
356 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
357 optparse
.make_option("--changesfile", dest
="changesFile"),
358 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
359 optparse
.make_option("--known-branches", dest
="knownBranches"),
360 optparse
.make_option("--cache", dest
="doCache", action
="store_true"),
361 optparse
.make_option("--command-cache", dest
="commandCache", action
="store_true")
363 self
.description
= """Imports from Perforce into a git repository.\n
365 //depot/my/project/ -- to import the current head
366 //depot/my/project/@all -- to import everything
367 //depot/my/project/@1,6 -- to import only from revision 1 to 6
369 (a ... is not needed in the path p4 specification, it's added implicitly)"""
371 self
.usage
+= " //depot/path[@revRange]"
373 self
.dataCache
= False
374 self
.commandCache
= False
376 self
.knownBranches
= Set()
377 self
.createdBranches
= Set()
378 self
.committedChanges
= Set()
380 self
.detectBranches
= False
381 self
.changesFile
= ""
383 def p4File(self
, depotPath
):
384 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
386 def extractFilesFromCommit(self
, commit
):
389 while commit
.has_key("depotFile%s" % fnum
):
390 path
= commit
["depotFile%s" % fnum
]
391 if not path
.startswith(self
.globalPrefix
):
392 # if not self.silent:
393 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.globalPrefix, change)
399 file["rev"] = commit
["rev%s" % fnum
]
400 file["action"] = commit
["action%s" % fnum
]
401 file["type"] = commit
["type%s" % fnum
]
406 def isSubPathOf(self
, first
, second
):
407 if not first
.startswith(second
):
411 return first
[len(second
)] == "/"
413 def branchesForCommit(self
, files
):
417 relativePath
= file["path"][len(self
.globalPrefix
):]
418 # strip off the filename
419 relativePath
= relativePath
[0:relativePath
.rfind("/")]
421 # if len(branches) == 0:
422 # branches.add(relativePath)
423 # knownBranches.add(relativePath)
426 ###### this needs more testing :)
428 for branch
in branches
:
429 if relativePath
== branch
:
432 # if relativePath.startswith(branch):
433 if self
.isSubPathOf(relativePath
, branch
):
436 # if branch.startswith(relativePath):
437 if self
.isSubPathOf(branch
, relativePath
):
438 branches
.remove(branch
)
444 for branch
in knownBranches
:
445 #if relativePath.startswith(branch):
446 if self
.isSubPathOf(relativePath
, branch
):
447 if len(branches
) == 0:
448 relativePath
= branch
456 branches
.add(relativePath
)
457 self
.knownBranches
.add(relativePath
)
461 def findBranchParent(self
, branchPrefix
, files
):
464 if not path
.startswith(branchPrefix
):
466 action
= file["action"]
467 if action
!= "integrate" and action
!= "branch":
470 depotPath
= path
+ "#" + rev
472 log
= p4CmdList("filelog \"%s\"" % depotPath
)
474 print "eek! I got confused by the filelog of %s" % depotPath
478 if log
["action0"] != action
:
479 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
482 branchAction
= log
["how0,0"]
483 # if branchAction == "branch into" or branchAction == "ignored":
484 # continue # ignore for branching
486 if not branchAction
.endswith(" from"):
487 continue # ignore for branching
488 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
491 source
= log
["file0,0"]
492 if source
.startswith(branchPrefix
):
495 lastSourceRev
= log
["erev0,0"]
497 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
498 if len(sourceLog
) != 1:
499 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
501 sourceLog
= sourceLog
[0]
503 relPath
= source
[len(self
.globalPrefix
):]
504 # strip off the filename
505 relPath
= relPath
[0:relPath
.rfind("/")]
507 for branch
in self
.knownBranches
:
508 if self
.isSubPathOf(relPath
, branch
):
509 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
512 # print "%s is not a subpath of branch %s" % (relPath, branch)
516 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= "", merged
= ""):
517 epoch
= details
["time"]
518 author
= details
["user"]
520 self
.gitStream
.write("commit %s\n" % branch
)
521 # gitStream.write("mark :%s\n" % details["change"])
522 self
.committedChanges
.add(int(details
["change"]))
524 if author
in self
.users
:
525 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
527 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
529 self
.gitStream
.write("committer %s\n" % committer
)
531 self
.gitStream
.write("data <<EOT\n")
532 self
.gitStream
.write(details
["desc"])
533 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
534 self
.gitStream
.write("EOT\n\n")
537 self
.gitStream
.write("from %s\n" % parent
)
540 self
.gitStream
.write("merge %s\n" % merged
)
544 if not path
.startswith(branchPrefix
):
546 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
549 depotPath
= path
+ "#" + rev
550 relPath
= path
[len(branchPrefix
):]
551 action
= file["action"]
553 if file["type"] == "apple":
554 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
557 if action
== "delete":
558 self
.gitStream
.write("D %s\n" % relPath
)
561 if file["type"].startswith("x"):
564 data
= self
.p4File(depotPath
)
566 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
567 self
.gitStream
.write("data %s\n" % len(data
))
568 self
.gitStream
.write(data
)
569 self
.gitStream
.write("\n")
571 self
.gitStream
.write("\n")
573 self
.lastChange
= int(details
["change"])
575 def extractFilesInCommitToBranch(self
, files
, branchPrefix
):
580 if path
.startswith(branchPrefix
):
581 newFiles
.append(file)
585 def findBranchSourceHeuristic(self
, files
, branch
, branchPrefix
):
587 action
= file["action"]
588 if action
!= "integrate" and action
!= "branch":
592 depotPath
= path
+ "#" + rev
594 log
= p4CmdList("filelog \"%s\"" % depotPath
)
596 print "eek! I got confused by the filelog of %s" % depotPath
600 if log
["action0"] != action
:
601 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
604 branchAction
= log
["how0,0"]
606 if not branchAction
.endswith(" from"):
607 continue # ignore for branching
608 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
611 source
= log
["file0,0"]
612 if source
.startswith(branchPrefix
):
615 lastSourceRev
= log
["erev0,0"]
617 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
618 if len(sourceLog
) != 1:
619 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
621 sourceLog
= sourceLog
[0]
623 relPath
= source
[len(self
.globalPrefix
):]
624 # strip off the filename
625 relPath
= relPath
[0:relPath
.rfind("/")]
627 for candidate
in self
.knownBranches
:
628 if self
.isSubPathOf(relPath
, candidate
) and candidate
!= branch
:
633 def changeIsBranchMerge(self
, sourceBranch
, destinationBranch
, change
):
635 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ sourceBranch
+ "/", change
)):
636 if file["action"] == "delete":
638 sourceFiles
[file["depotFile"]] = file
640 destinationFiles
= {}
641 for file in p4CmdList("files %s...@%s" % (self
.globalPrefix
+ destinationBranch
+ "/", change
)):
642 destinationFiles
[file["depotFile"]] = file
644 for fileName
in sourceFiles
.keys():
648 for integration
in p4CmdList("integrated \"%s\"" % fileName
):
649 toFile
= integration
["fromFile"] # yes, it's true, it's fromFile
650 if not toFile
in destinationFiles
:
652 destFile
= destinationFiles
[toFile
]
653 if destFile
["action"] == "delete":
654 # print "file %s has been deleted in %s" % (fileName, toFile)
657 integrationCount
+= 1
658 if integration
["how"] == "branch from":
661 if int(integration
["change"]) == change
:
662 integrations
.append(integration
)
664 if int(integration
["change"]) > change
:
667 destRev
= int(destFile
["rev"])
669 startRev
= integration
["startFromRev"][1:]
670 if startRev
== "none":
673 startRev
= int(startRev
)
675 endRev
= integration
["endFromRev"][1:]
681 initialBranch
= (destRev
== 1 and integration
["how"] != "branch into")
682 inRange
= (destRev
>= startRev
and destRev
<= endRev
)
683 newer
= (destRev
> startRev
and destRev
> endRev
)
685 if initialBranch
or inRange
or newer
:
686 integrations
.append(integration
)
691 if len(integrations
) == 0 and integrationCount
> 1:
692 print "file %s was not integrated from %s into %s" % (fileName
, sourceBranch
, destinationBranch
)
697 def getUserMap(self
):
700 for output
in p4CmdList("users"):
701 if not output
.has_key("User"):
703 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
706 self
.branch
= "refs/heads/" + self
.branch
707 self
.globalPrefix
= self
.previousDepotPath
= os
.popen("git-repo-config --get p4.depotpath").read()
708 if len(self
.globalPrefix
) != 0:
709 self
.globalPrefix
= self
.globalPrefix
[:-1]
711 if len(args
) == 0 and len(self
.globalPrefix
) != 0:
713 print "[using previously specified depot path %s]" % self
.globalPrefix
717 if len(self
.globalPrefix
) != 0 and self
.globalPrefix
!= args
[0]:
718 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.globalPrefix
, args
[0])
720 self
.globalPrefix
= args
[0]
722 self
.changeRange
= ""
725 self
.initialParent
= ""
729 if self
.globalPrefix
.find("@") != -1:
730 atIdx
= self
.globalPrefix
.index("@")
731 self
.changeRange
= self
.globalPrefix
[atIdx
:]
732 if self
.changeRange
== "@all":
733 self
.changeRange
= ""
734 elif self
.changeRange
.find(",") == -1:
735 self
.revision
= self
.changeRange
736 self
.changeRange
= ""
737 self
.globalPrefix
= self
.globalPrefix
[0:atIdx
]
738 elif self
.globalPrefix
.find("#") != -1:
739 hashIdx
= self
.globalPrefix
.index("#")
740 self
.revision
= self
.globalPrefix
[hashIdx
:]
741 self
.globalPrefix
= self
.globalPrefix
[0:hashIdx
]
742 elif len(self
.previousDepotPath
) == 0:
743 self
.revision
= "#head"
745 if self
.globalPrefix
.endswith("..."):
746 self
.globalPrefix
= self
.globalPrefix
[:-3]
748 if not self
.globalPrefix
.endswith("/"):
749 self
.globalPrefix
+= "/"
753 if len(self
.changeRange
) == 0:
755 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % self
.branch
)
757 if output
.endswith("\n"):
759 tagIdx
= output
.index(" tags/p4/")
760 caretIdx
= output
.find("^")
764 self
.rev
= int(output
[tagIdx
+ 9 : endPos
]) + 1
765 self
.changeRange
= "@%s,#head" % self
.rev
766 self
.initialParent
= os
.popen("git-rev-parse %s" % self
.branch
).read()[:-1]
767 self
.initialTag
= "p4/%s" % (int(self
.rev
) - 1)
771 self
.tz
= - time
.timezone
/ 36
772 tzsign
= ("%s" % self
.tz
)[0]
773 if tzsign
!= '+' and tzsign
!= '-':
774 self
.tz
= "+" + ("%s" % self
.tz
)
776 self
.gitOutput
, self
.gitStream
, self
.gitError
= popen2
.popen3("git-fast-import")
778 if len(self
.revision
) > 0:
779 print "Doing initial import of %s from revision %s" % (self
.globalPrefix
, self
.revision
)
781 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
782 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.globalPrefix
, self
.revision
)
783 details
["change"] = self
.revision
787 for info
in p4CmdList("files %s...%s" % (self
.globalPrefix
, self
.revision
)):
788 change
= int(info
["change"])
789 if change
> newestRevision
:
790 newestRevision
= change
792 if info
["action"] == "delete":
793 fileCnt
= fileCnt
+ 1
796 for prop
in [ "depotFile", "rev", "action", "type" ]:
797 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
799 fileCnt
= fileCnt
+ 1
801 details
["change"] = newestRevision
804 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.globalPrefix
)
806 print self
.gitError
.read()
811 if len(self
.changesFile
) > 0:
812 output
= open(self
.changesFile
).readlines()
815 changeSet
.add(int(line
))
817 for change
in changeSet
:
818 changes
.append(change
)
822 output
= os
.popen("p4 changes %s...%s" % (self
.globalPrefix
, self
.changeRange
)).readlines()
825 changeNum
= line
.split(" ")[1]
826 changes
.append(changeNum
)
830 if len(changes
) == 0:
832 print "no changes to import!"
836 for change
in changes
:
837 description
= p4Cmd("describe %s" % change
)
840 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
845 files
= self
.extractFilesFromCommit(description
)
846 if self
.detectBranches
:
847 for branch
in self
.branchesForCommit(files
):
848 self
.knownBranches
.add(branch
)
849 branchPrefix
= self
.globalPrefix
+ branch
+ "/"
851 filesForCommit
= self
.extractFilesInCommitToBranch(files
, branchPrefix
)
855 ########### remove cnt!!!
856 if branch
not in self
.createdBranches
and cnt
> 2:
857 self
.createdBranches
.add(branch
)
858 parent
= self
.findBranchParent(branchPrefix
, files
)
861 # elif len(parent) > 0:
862 # print "%s branched off of %s" % (branch, parent)
865 merged
= self
.findBranchSourceHeuristic(filesForCommit
, branch
, branchPrefix
)
867 print "change %s could be a merge from %s into %s" % (description
["change"], merged
, branch
)
868 if not self
.changeIsBranchMerge(merged
, branch
, int(description
["change"])):
871 branch
= "refs/heads/" + branch
873 parent
= "refs/heads/" + parent
875 merged
= "refs/heads/" + merged
876 self
.commit(description
, files
, branch
, branchPrefix
, parent
, merged
)
878 self
.commit(description
, files
, self
.branch
, self
.globalPrefix
, self
.initialParent
)
879 self
.initialParent
= ""
881 print self
.gitError
.read()
887 self
.gitStream
.write("reset refs/tags/p4/%s\n" % self
.lastChange
)
888 self
.gitStream
.write("from %s\n\n" % self
.branch
);
891 self
.gitStream
.close()
892 self
.gitOutput
.close()
893 self
.gitError
.close()
895 os
.popen("git-repo-config p4.depotpath %s" % self
.globalPrefix
).read()
896 if len(self
.initialTag
) > 0:
897 os
.popen("git tag -d %s" % self
.initialTag
).read()
901 class HelpFormatter(optparse
.IndentedHelpFormatter
):
903 optparse
.IndentedHelpFormatter
.__init
__(self
)
905 def format_description(self
, description
):
907 return description
+ "\n"
911 def printUsage(commands
):
912 print "usage: %s <command> [options]" % sys
.argv
[0]
914 print "valid commands: %s" % ", ".join(commands
)
916 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
921 "clean-tags" : P4CleanTags(),
926 if len(sys
.argv
[1:]) == 0:
927 printUsage(commands
.keys())
931 cmdName
= sys
.argv
[1]
933 cmd
= commands
[cmdName
]
935 print "unknown command %s" % cmdName
937 printUsage(commands
.keys())
940 options
= cmd
.options
942 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
944 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
946 description
= cmd
.description
,
947 formatter
= HelpFormatter())
949 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
954 if not isValidGitDir(gitdir
):
955 cdup
= os
.popen("git-rev-parse --show-cdup").read()[:-1]
956 if isValidGitDir(cdup
+ "/" + gitdir
):
959 if not isValidGitDir(gitdir
):
960 if isValidGitDir(gitdir
+ "/.git"):
963 die("fatal: cannot locate git repository at %s" % gitdir
)
965 os
.environ
["GIT_DIR"] = gitdir
967 if not cmd
.run(args
):