3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
11 import optparse
, sys
, os
, marshal
, popen2
, subprocess
, shelve
12 import tempfile
, getopt
, sha
, os
.path
, time
, platform
23 sys
.stderr
.write(msg
+ "\n")
26 def write_pipe(c
, str):
28 sys
.stderr
.write('Writing pipe: %s\n' % c
)
30 pipe
= os
.popen(c
, 'w')
33 die('Command failed: %s' % c
)
37 def read_pipe(c
, ignore_error
=False):
39 sys
.stderr
.write('Reading pipe: %s\n' % c
)
41 pipe
= os
.popen(c
, 'rb')
43 if pipe
.close() and not ignore_error
:
44 die('Command failed: %s' % c
)
49 def read_pipe_lines(c
):
51 sys
.stderr
.write('Reading pipe: %s\n' % c
)
52 ## todo: check return status
53 pipe
= os
.popen(c
, 'rb')
54 val
= pipe
.readlines()
56 die('Command failed: %s' % c
)
62 sys
.stderr
.write("executing %s\n" % cmd
)
63 if os
.system(cmd
) != 0:
64 die("command failed: %s" % cmd
)
67 """Determine if a Perforce 'kind' should have execute permission
69 'p4 help filetypes' gives a list of the types. If it starts with 'x',
70 or x follows one of a few letters. Otherwise, if there is an 'x' after
71 a plus sign, it is also executable"""
72 return (re
.search(r
"(^[cku]?x)|\+.*x", kind
) != None)
74 def p4CmdList(cmd
, stdin
=None, stdin_mode
='w+b'):
75 cmd
= "p4 -G %s" % cmd
77 sys
.stderr
.write("Opening pipe: %s\n" % cmd
)
79 # Use a temporary file to avoid deadlocks without
80 # subprocess.communicate(), which would put another copy
81 # of stdout into memory.
84 stdin_file
= tempfile
.TemporaryFile(prefix
='p4-stdin', mode
=stdin_mode
)
85 stdin_file
.write(stdin
)
89 p4
= subprocess
.Popen(cmd
, shell
=True,
91 stdout
=subprocess
.PIPE
)
96 entry
= marshal
.load(p4
.stdout
)
103 entry
["p4ExitCode"] = exitCode
109 list = p4CmdList(cmd
)
115 def p4Where(depotPath
):
116 if not depotPath
.endswith("/"):
118 output
= p4Cmd("where %s..." % depotPath
)
119 if output
["code"] == "error":
123 clientPath
= output
.get("path")
124 elif "data" in output
:
125 data
= output
.get("data")
126 lastSpace
= data
.rfind(" ")
127 clientPath
= data
[lastSpace
+ 1:]
129 if clientPath
.endswith("..."):
130 clientPath
= clientPath
[:-3]
133 def currentGitBranch():
134 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
136 def isValidGitDir(path
):
137 if (os
.path
.exists(path
+ "/HEAD")
138 and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects")):
142 def parseRevision(ref
):
143 return read_pipe("git rev-parse %s" % ref
).strip()
145 def extractLogMessageFromGitCommit(commit
):
148 ## fixme: title is first line of commit, not 1st paragraph.
150 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
159 def extractSettingsGitLog(log
):
161 for line
in log
.split("\n"):
163 m
= re
.search (r
"^ *\[git-p4: (.*)\]$", line
)
167 assignments
= m
.group(1).split (':')
168 for a
in assignments
:
170 key
= vals
[0].strip()
171 val
= ('='.join (vals
[1:])).strip()
172 if val
.endswith ('\"') and val
.startswith('"'):
177 paths
= values
.get("depot-paths")
179 paths
= values
.get("depot-path")
181 values
['depot-paths'] = paths
.split(',')
184 def gitBranchExists(branch
):
185 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
186 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
187 return proc
.wait() == 0;
190 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
192 def p4BranchesInGit(branchesAreInRemotes
= True):
195 cmdline
= "git rev-parse --symbolic "
196 if branchesAreInRemotes
:
197 cmdline
+= " --remotes"
199 cmdline
+= " --branches"
201 for line
in read_pipe_lines(cmdline
):
204 ## only import to p4/
205 if not line
.startswith('p4/') or line
== "p4/HEAD":
210 branch
= re
.sub ("^p4/", "", line
)
212 branches
[branch
] = parseRevision(line
)
215 def findUpstreamBranchPoint(head
= "HEAD"):
216 branches
= p4BranchesInGit()
217 # map from depot-path to branch name
218 branchByDepotPath
= {}
219 for branch
in branches
.keys():
220 tip
= branches
[branch
]
221 log
= extractLogMessageFromGitCommit(tip
)
222 settings
= extractSettingsGitLog(log
)
223 if settings
.has_key("depot-paths"):
224 paths
= ",".join(settings
["depot-paths"])
225 branchByDepotPath
[paths
] = "remotes/p4/" + branch
229 while parent
< 65535:
230 commit
= head
+ "~%s" % parent
231 log
= extractLogMessageFromGitCommit(commit
)
232 settings
= extractSettingsGitLog(log
)
233 if settings
.has_key("depot-paths"):
234 paths
= ",".join(settings
["depot-paths"])
235 if branchByDepotPath
.has_key(paths
):
236 return [branchByDepotPath
[paths
], settings
]
240 return ["", settings
]
242 def createOrUpdateBranchesFromOrigin(localRefPrefix
= "refs/remotes/p4/", silent
=True):
244 print ("Creating/updating branch(es) in %s based on origin branch(es)"
247 originPrefix
= "origin/p4/"
249 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
251 if (not line
.startswith(originPrefix
)) or line
.endswith("HEAD"):
254 headName
= line
[len(originPrefix
):]
255 remoteHead
= localRefPrefix
+ headName
258 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
259 if (not original
.has_key('depot-paths')
260 or not original
.has_key('change')):
264 if not gitBranchExists(remoteHead
):
266 print "creating %s" % remoteHead
269 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
270 if settings
.has_key('change') > 0:
271 if settings
['depot-paths'] == original
['depot-paths']:
272 originP4Change
= int(original
['change'])
273 p4Change
= int(settings
['change'])
274 if originP4Change
> p4Change
:
275 print ("%s (%s) is newer than %s (%s). "
276 "Updating p4 branch from origin."
277 % (originHead
, originP4Change
,
278 remoteHead
, p4Change
))
281 print ("Ignoring: %s was imported from %s while "
282 "%s was imported from %s"
283 % (originHead
, ','.join(original
['depot-paths']),
284 remoteHead
, ','.join(settings
['depot-paths'])))
287 system("git update-ref %s %s" % (remoteHead
, originHead
))
289 def originP4BranchesExist():
290 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
292 def p4ChangesForPaths(depotPaths
, changeRange
):
294 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, changeRange
)
295 for p
in depotPaths
]))
299 changeNum
= line
.split(" ")[1]
300 changes
.append(int(changeNum
))
307 self
.usage
= "usage: %prog [options]"
310 class P4Debug(Command
):
312 Command
.__init
__(self
)
314 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
317 self
.description
= "A tool to debug the output of p4 -G."
318 self
.needsGit
= False
323 for output
in p4CmdList(" ".join(args
)):
324 print 'Element: %d' % j
329 class P4RollBack(Command
):
331 Command
.__init
__(self
)
333 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
334 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
336 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
338 self
.rollbackLocalBranches
= False
343 maxChange
= int(args
[0])
345 if "p4ExitCode" in p4Cmd("changes -m 1"):
346 die("Problems executing p4");
348 if self
.rollbackLocalBranches
:
349 refPrefix
= "refs/heads/"
350 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
352 refPrefix
= "refs/remotes/"
353 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
356 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
358 ref
= refPrefix
+ line
359 log
= extractLogMessageFromGitCommit(ref
)
360 settings
= extractSettingsGitLog(log
)
362 depotPaths
= settings
['depot-paths']
363 change
= settings
['change']
367 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
368 for p
in depotPaths
]))) == 0:
369 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
370 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
373 while change
and int(change
) > maxChange
:
376 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
377 system("git update-ref %s \"%s^\"" % (ref
, ref
))
378 log
= extractLogMessageFromGitCommit(ref
)
379 settings
= extractSettingsGitLog(log
)
382 depotPaths
= settings
['depot-paths']
383 change
= settings
['change']
386 print "%s rewound to %s" % (ref
, change
)
390 class P4Submit(Command
):
392 Command
.__init
__(self
)
394 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
395 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
396 optparse
.make_option("--origin", dest
="origin"),
397 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
398 optparse
.make_option("--log-substitutions", dest
="substFile"),
399 optparse
.make_option("--dry-run", action
="store_true"),
400 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
401 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
402 optparse
.make_option("-M", dest
="detectRename", action
="store_true"),
404 self
.description
= "Submit changes from git to the perforce depot."
405 self
.usage
+= " [name of git branch to submit into perforce depot]"
406 self
.firstTime
= True
408 self
.interactive
= True
411 self
.firstTime
= True
413 self
.directSubmit
= False
414 self
.trustMeLikeAFool
= False
415 self
.detectRename
= False
417 self
.isWindows
= (platform
.system() == "Windows")
419 self
.logSubstitutions
= {}
420 self
.logSubstitutions
["<enter description here>"] = "%log%"
421 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
424 if len(p4CmdList("opened ...")) > 0:
425 die("You have files opened with perforce! Close them before starting the sync.")
428 if len(self
.config
) > 0 and not self
.reset
:
429 die("Cannot start sync. Previous sync config found at %s\n"
430 "If you want to start submitting again from scratch "
431 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
434 if self
.directSubmit
:
437 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
438 commits
.append(line
.strip())
441 self
.config
["commits"] = commits
443 def prepareLogMessage(self
, template
, message
):
446 for line
in template
.split("\n"):
447 if line
.startswith("#"):
448 result
+= line
+ "\n"
452 for key
in self
.logSubstitutions
.keys():
453 if line
.find(key
) != -1:
454 value
= self
.logSubstitutions
[key
]
455 value
= value
.replace("%log%", message
)
456 if value
!= "@remove@":
457 result
+= line
.replace(key
, value
) + "\n"
462 result
+= line
+ "\n"
466 def prepareSubmitTemplate(self
):
467 # remove lines in the Files section that show changes to files outside the depot path we're committing into
469 inFilesSection
= False
470 for line
in read_pipe_lines("p4 change -o"):
472 if line
.startswith("\t"):
473 # path starts and ends with a tab
475 lastTab
= path
.rfind("\t")
477 path
= path
[:lastTab
]
478 if not path
.startswith(self
.depotPath
):
481 inFilesSection
= False
483 if line
.startswith("Files:"):
484 inFilesSection
= True
490 def applyCommit(self
, id):
491 if self
.directSubmit
:
492 print "Applying local change in working directory/index"
493 diff
= self
.diffStatus
495 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
496 diffOpts
= ("", "-M")[self
.detectRename
]
497 diff
= read_pipe_lines("git diff-tree -r --name-status %s \"%s^\" \"%s\"" % (diffOpts
, id, id))
499 filesToDelete
= set()
503 path
= line
[1:].strip()
505 system("p4 edit \"%s\"" % path
)
506 editedFiles
.add(path
)
507 elif modifier
== "A":
509 if path
in filesToDelete
:
510 filesToDelete
.remove(path
)
511 elif modifier
== "D":
512 filesToDelete
.add(path
)
513 if path
in filesToAdd
:
514 filesToAdd
.remove(path
)
515 elif modifier
== "R":
516 src
, dest
= line
.strip().split("\t")[1:3]
517 system("p4 integrate -Dt \"%s\" \"%s\"" % (src
, dest
))
518 system("p4 edit \"%s\"" % (dest
))
520 editedFiles
.add(dest
)
521 filesToDelete
.add(src
)
523 die("unknown modifier %s for %s" % (modifier
, path
))
525 if self
.directSubmit
:
526 diffcmd
= "cat \"%s\"" % self
.diffFile
528 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
529 patchcmd
= diffcmd
+ " | git apply "
530 tryPatchCmd
= patchcmd
+ "--check -"
531 applyPatchCmd
= patchcmd
+ "--check --apply -"
533 if os
.system(tryPatchCmd
) != 0:
534 print "Unfortunately applying the change failed!"
535 print "What do you want to do?"
537 while response
!= "s" and response
!= "a" and response
!= "w":
538 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
539 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
541 print "Skipping! Good luck with the next patches..."
542 for f
in editedFiles
:
543 system("p4 revert \"%s\"" % f
);
547 elif response
== "a":
548 os
.system(applyPatchCmd
)
549 if len(filesToAdd
) > 0:
550 print "You may also want to call p4 add on the following files:"
551 print " ".join(filesToAdd
)
552 if len(filesToDelete
):
553 print "The following files should be scheduled for deletion with p4 delete:"
554 print " ".join(filesToDelete
)
555 die("Please resolve and submit the conflict manually and "
556 + "continue afterwards with git-p4 submit --continue")
557 elif response
== "w":
558 system(diffcmd
+ " > patch.txt")
559 print "Patch saved to patch.txt in %s !" % self
.clientPath
560 die("Please resolve and submit the conflict manually and "
561 "continue afterwards with git-p4 submit --continue")
563 system(applyPatchCmd
)
566 system("p4 add \"%s\"" % f
)
567 for f
in filesToDelete
:
568 system("p4 revert \"%s\"" % f
)
569 system("p4 delete \"%s\"" % f
)
572 if not self
.directSubmit
:
573 logMessage
= extractLogMessageFromGitCommit(id)
574 logMessage
= logMessage
.replace("\n", "\n\t")
576 logMessage
= logMessage
.replace("\n", "\r\n")
577 logMessage
= logMessage
.strip()
579 template
= self
.prepareSubmitTemplate()
582 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
583 diff
= read_pipe("p4 diff -du ...")
585 for newFile
in filesToAdd
:
586 diff
+= "==== new file ====\n"
587 diff
+= "--- /dev/null\n"
588 diff
+= "+++ %s\n" % newFile
589 f
= open(newFile
, "r")
590 for line
in f
.readlines():
594 separatorLine
= "######## everything below this line is just the diff #######"
595 if platform
.system() == "Windows":
596 separatorLine
+= "\r"
597 separatorLine
+= "\n"
600 if self
.trustMeLikeAFool
:
603 firstIteration
= True
604 while response
== "e":
605 if not firstIteration
:
606 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
607 firstIteration
= False
609 [handle
, fileName
] = tempfile
.mkstemp()
610 tmpFile
= os
.fdopen(handle
, "w+")
611 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
614 if platform
.system() == "Windows":
615 defaultEditor
= "notepad"
616 editor
= os
.environ
.get("EDITOR", defaultEditor
);
617 system(editor
+ " " + fileName
)
618 tmpFile
= open(fileName
, "rb")
619 message
= tmpFile
.read()
622 submitTemplate
= message
[:message
.index(separatorLine
)]
624 submitTemplate
= submitTemplate
.replace("\r\n", "\n")
626 if response
== "y" or response
== "yes":
629 raw_input("Press return to continue...")
631 if self
.directSubmit
:
632 print "Submitting to git first"
633 os
.chdir(self
.oldWorkingDirectory
)
634 write_pipe("git commit -a -F -", submitTemplate
)
635 os
.chdir(self
.clientPath
)
637 write_pipe("p4 submit -i", submitTemplate
)
638 elif response
== "s":
639 for f
in editedFiles
:
640 system("p4 revert \"%s\"" % f
);
642 system("p4 revert \"%s\"" % f
);
644 for f
in filesToDelete
:
645 system("p4 delete \"%s\"" % f
);
648 print "Not submitting!"
649 self
.interactive
= False
651 fileName
= "submit.txt"
652 file = open(fileName
, "w+")
653 file.write(self
.prepareLogMessage(template
, logMessage
))
655 print ("Perforce submit template written as %s. "
656 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
657 % (fileName
, fileName
))
661 self
.master
= currentGitBranch()
662 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
663 die("Detecting current git branch failed!")
665 self
.master
= args
[0]
669 [upstream
, settings
] = findUpstreamBranchPoint()
670 self
.depotPath
= settings
['depot-paths'][0]
671 if len(self
.origin
) == 0:
672 self
.origin
= upstream
675 print "Origin branch is " + self
.origin
677 if len(self
.depotPath
) == 0:
678 print "Internal error: cannot locate perforce depot path from existing branches"
681 self
.clientPath
= p4Where(self
.depotPath
)
683 if len(self
.clientPath
) == 0:
684 print "Error: Cannot locate perforce checkout of %s in client view" % self
.depotPath
687 print "Perforce checkout for depot path %s located at %s" % (self
.depotPath
, self
.clientPath
)
688 self
.oldWorkingDirectory
= os
.getcwd()
690 if self
.directSubmit
:
691 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
692 if len(self
.diffStatus
) == 0:
693 print "No changes in working directory to submit."
695 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
696 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
697 f
= open(self
.diffFile
, "wb")
701 os
.chdir(self
.clientPath
)
702 print "Syncronizing p4 checkout..."
703 system("p4 sync ...")
706 self
.firstTime
= True
708 if len(self
.substFile
) > 0:
709 for line
in open(self
.substFile
, "r").readlines():
710 tokens
= line
.strip().split("=")
711 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
714 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
715 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
720 commits
= self
.config
.get("commits", [])
722 while len(commits
) > 0:
723 self
.firstTime
= False
725 commits
= commits
[1:]
726 self
.config
["commits"] = commits
727 self
.applyCommit(commit
)
728 if not self
.interactive
:
733 if self
.directSubmit
:
734 os
.remove(self
.diffFile
)
736 if len(commits
) == 0:
738 print "No changes found to apply between %s and current HEAD" % self
.origin
740 print "All changes applied!"
741 os
.chdir(self
.oldWorkingDirectory
)
746 response
= raw_input("Do you want to rebase current HEAD from Perforce now using git-p4 rebase? [y]es/[n]o ")
747 if response
== "y" or response
== "yes":
750 os
.remove(self
.configFile
)
754 class P4Sync(Command
):
756 Command
.__init
__(self
)
758 optparse
.make_option("--branch", dest
="branch"),
759 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
760 optparse
.make_option("--changesfile", dest
="changesFile"),
761 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
762 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
763 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
764 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
765 help="Import into refs/heads/ , not refs/remotes"),
766 optparse
.make_option("--max-changes", dest
="maxChanges"),
767 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
768 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
770 self
.description
= """Imports from Perforce into a git repository.\n
772 //depot/my/project/ -- to import the current head
773 //depot/my/project/@all -- to import everything
774 //depot/my/project/@1,6 -- to import only from revision 1 to 6
776 (a ... is not needed in the path p4 specification, it's added implicitly)"""
778 self
.usage
+= " //depot/path[@revRange]"
780 self
.createdBranches
= Set()
781 self
.committedChanges
= Set()
783 self
.detectBranches
= False
784 self
.detectLabels
= False
785 self
.changesFile
= ""
786 self
.syncWithOrigin
= True
788 self
.importIntoRemotes
= True
790 self
.isWindows
= (platform
.system() == "Windows")
791 self
.keepRepoPath
= False
792 self
.depotPaths
= None
793 self
.p4BranchesInGit
= []
795 if gitConfig("git-p4.syncFromOrigin") == "false":
796 self
.syncWithOrigin
= False
798 def extractFilesFromCommit(self
, commit
):
801 while commit
.has_key("depotFile%s" % fnum
):
802 path
= commit
["depotFile%s" % fnum
]
804 found
= [p
for p
in self
.depotPaths
805 if path
.startswith (p
)]
812 file["rev"] = commit
["rev%s" % fnum
]
813 file["action"] = commit
["action%s" % fnum
]
814 file["type"] = commit
["type%s" % fnum
]
819 def stripRepoPath(self
, path
, prefixes
):
820 if self
.keepRepoPath
:
821 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
824 if path
.startswith(p
):
829 def splitFilesIntoBranches(self
, commit
):
832 while commit
.has_key("depotFile%s" % fnum
):
833 path
= commit
["depotFile%s" % fnum
]
834 found
= [p
for p
in self
.depotPaths
835 if path
.startswith (p
)]
842 file["rev"] = commit
["rev%s" % fnum
]
843 file["action"] = commit
["action%s" % fnum
]
844 file["type"] = commit
["type%s" % fnum
]
847 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
849 for branch
in self
.knownBranches
.keys():
851 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
852 if relPath
.startswith(branch
+ "/"):
853 if branch
not in branches
:
854 branches
[branch
] = []
855 branches
[branch
].append(file)
860 ## Should move this out, doesn't use SELF.
861 def readP4Files(self
, files
):
862 files
= [f
for f
in files
863 if f
['action'] != 'delete']
868 filedata
= p4CmdList('-x - print',
869 stdin
='\n'.join(['%s#%s' % (f
['path'], f
['rev'])
872 if "p4ExitCode" in filedata
[0]:
873 die("Problems executing p4. Error: [%d]."
874 % (filedata
[0]['p4ExitCode']));
878 while j
< len(filedata
):
882 while j
< len(filedata
) and filedata
[j
]['code'] in ('text',
884 text
+= filedata
[j
]['data']
888 if not stat
.has_key('depotFile'):
889 sys
.stderr
.write("p4 print fails with: %s\n" % repr(stat
))
892 contents
[stat
['depotFile']] = text
895 assert not f
.has_key('data')
896 f
['data'] = contents
[f
['path']]
898 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
899 epoch
= details
["time"]
900 author
= details
["user"]
903 print "commit into %s" % branch
905 # start with reading files; if that fails, we should not
909 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
912 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
914 self
.readP4Files(files
)
919 self
.gitStream
.write("commit %s\n" % branch
)
920 # gitStream.write("mark :%s\n" % details["change"])
921 self
.committedChanges
.add(int(details
["change"]))
923 if author
not in self
.users
:
924 self
.getUserMapFromPerforceServer()
925 if author
in self
.users
:
926 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
928 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
930 self
.gitStream
.write("committer %s\n" % committer
)
932 self
.gitStream
.write("data <<EOT\n")
933 self
.gitStream
.write(details
["desc"])
934 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s"
935 % (','.join (branchPrefixes
), details
["change"]))
936 if len(details
['options']) > 0:
937 self
.gitStream
.write(": options = %s" % details
['options'])
938 self
.gitStream
.write("]\nEOT\n\n")
942 print "parent %s" % parent
943 self
.gitStream
.write("from %s\n" % parent
)
946 if file["type"] == "apple":
947 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
950 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
951 if file["action"] == "delete":
952 self
.gitStream
.write("D %s\n" % relPath
)
957 if isP4Exec(file["type"]):
959 elif file["type"] == "symlink":
961 # p4 print on a symlink contains "target\n", so strip it off
964 if self
.isWindows
and file["type"].endswith("text"):
965 data
= data
.replace("\r\n", "\n")
967 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
968 self
.gitStream
.write("data %s\n" % len(data
))
969 self
.gitStream
.write(data
)
970 self
.gitStream
.write("\n")
972 self
.gitStream
.write("\n")
974 change
= int(details
["change"])
976 if self
.labels
.has_key(change
):
977 label
= self
.labels
[change
]
978 labelDetails
= label
[0]
979 labelRevisions
= label
[1]
981 print "Change %s is labelled %s" % (change
, labelDetails
)
983 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
984 for p
in branchPrefixes
]))
986 if len(files
) == len(labelRevisions
):
990 if info
["action"] == "delete":
992 cleanedFiles
[info
["depotFile"]] = info
["rev"]
994 if cleanedFiles
== labelRevisions
:
995 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
996 self
.gitStream
.write("from %s\n" % branch
)
998 owner
= labelDetails
["Owner"]
1000 if author
in self
.users
:
1001 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
1003 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
1004 self
.gitStream
.write("tagger %s\n" % tagger
)
1005 self
.gitStream
.write("data <<EOT\n")
1006 self
.gitStream
.write(labelDetails
["Description"])
1007 self
.gitStream
.write("EOT\n\n")
1011 print ("Tag %s does not match with change %s: files do not match."
1012 % (labelDetails
["label"], change
))
1016 print ("Tag %s does not match with change %s: file count is different."
1017 % (labelDetails
["label"], change
))
1019 def getUserCacheFilename(self
):
1020 home
= os
.environ
.get("HOME", os
.environ
.get("USERPROFILE"))
1021 return home
+ "/.gitp4-usercache.txt"
1023 def getUserMapFromPerforceServer(self
):
1024 if self
.userMapFromPerforceServer
:
1028 for output
in p4CmdList("users"):
1029 if not output
.has_key("User"):
1031 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
1035 for (key
, val
) in self
.users
.items():
1036 s
+= "%s\t%s\n" % (key
, val
)
1038 open(self
.getUserCacheFilename(), "wb").write(s
)
1039 self
.userMapFromPerforceServer
= True
1041 def loadUserMapFromCache(self
):
1043 self
.userMapFromPerforceServer
= False
1045 cache
= open(self
.getUserCacheFilename(), "rb")
1046 lines
= cache
.readlines()
1049 entry
= line
.strip().split("\t")
1050 self
.users
[entry
[0]] = entry
[1]
1052 self
.getUserMapFromPerforceServer()
1054 def getLabels(self
):
1057 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
1058 if len(l
) > 0 and not self
.silent
:
1059 print "Finding files belonging to labels in %s" % `self
.depotPath`
1062 label
= output
["label"]
1066 print "Querying files for label %s" % label
1067 for file in p4CmdList("files "
1068 + ' '.join (["%s...@%s" % (p
, label
)
1069 for p
in self
.depotPaths
])):
1070 revisions
[file["depotFile"]] = file["rev"]
1071 change
= int(file["change"])
1072 if change
> newestChange
:
1073 newestChange
= change
1075 self
.labels
[newestChange
] = [output
, revisions
]
1078 print "Label changes: %s" % self
.labels
.keys()
1080 def guessProjectName(self
):
1081 for p
in self
.depotPaths
:
1084 p
= p
[p
.strip().rfind("/") + 1:]
1085 if not p
.endswith("/"):
1089 def getBranchMapping(self
):
1090 lostAndFoundBranches
= set()
1092 for info
in p4CmdList("branches"):
1093 details
= p4Cmd("branch -o %s" % info
["branch"])
1095 while details
.has_key("View%s" % viewIdx
):
1096 paths
= details
["View%s" % viewIdx
].split(" ")
1097 viewIdx
= viewIdx
+ 1
1098 # require standard //depot/foo/... //depot/bar/... mapping
1099 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
1102 destination
= paths
[1]
1104 if source
.startswith(self
.depotPaths
[0]) and destination
.startswith(self
.depotPaths
[0]):
1105 source
= source
[len(self
.depotPaths
[0]):-4]
1106 destination
= destination
[len(self
.depotPaths
[0]):-4]
1108 if destination
in self
.knownBranches
:
1110 print "p4 branch %s defines a mapping from %s to %s" % (info
["branch"], source
, destination
)
1111 print "but there exists another mapping from %s to %s already!" % (self
.knownBranches
[destination
], destination
)
1114 self
.knownBranches
[destination
] = source
1116 lostAndFoundBranches
.discard(destination
)
1118 if source
not in self
.knownBranches
:
1119 lostAndFoundBranches
.add(source
)
1122 for branch
in lostAndFoundBranches
:
1123 self
.knownBranches
[branch
] = branch
1125 def listExistingP4GitBranches(self
):
1126 # branches holds mapping from name to commit
1127 branches
= p4BranchesInGit(self
.importIntoRemotes
)
1128 self
.p4BranchesInGit
= branches
.keys()
1129 for branch
in branches
.keys():
1130 self
.initialParents
[self
.refPrefix
+ branch
] = branches
[branch
]
1132 def updateOptionDict(self
, d
):
1134 if self
.keepRepoPath
:
1135 option_keys
['keepRepoPath'] = 1
1137 d
["options"] = ' '.join(sorted(option_keys
.keys()))
1139 def readOptions(self
, d
):
1140 self
.keepRepoPath
= (d
.has_key('options')
1141 and ('keepRepoPath' in d
['options']))
1143 def gitRefForBranch(self
, branch
):
1144 if branch
== "main":
1145 return self
.refPrefix
+ "master"
1147 if len(branch
) <= 0:
1150 return self
.refPrefix
+ self
.projectName
+ branch
1152 def gitCommitByP4Change(self
, ref
, change
):
1154 print "looking in ref " + ref
+ " for change %s using bisect..." % change
1157 latestCommit
= parseRevision(ref
)
1161 print "trying: earliest %s latest %s" % (earliestCommit
, latestCommit
)
1162 next
= read_pipe("git rev-list --bisect %s %s" % (latestCommit
, earliestCommit
)).strip()
1167 log
= extractLogMessageFromGitCommit(next
)
1168 settings
= extractSettingsGitLog(log
)
1169 currentChange
= int(settings
['change'])
1171 print "current change %s" % currentChange
1173 if currentChange
== change
:
1175 print "found %s" % next
1178 if currentChange
< change
:
1179 earliestCommit
= "^%s" % next
1181 latestCommit
= "%s" % next
1185 def importNewBranch(self
, branch
, maxChange
):
1186 # make fast-import flush all changes to disk and update the refs using the checkpoint
1187 # command so that we can try to find the branch parent in the git history
1188 self
.gitStream
.write("checkpoint\n\n");
1189 self
.gitStream
.flush();
1190 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1191 range = "@1,%s" % maxChange
1192 #print "prefix" + branchPrefix
1193 changes
= p4ChangesForPaths([branchPrefix
], range)
1194 if len(changes
) <= 0:
1196 firstChange
= changes
[0]
1197 #print "first change in branch: %s" % firstChange
1198 sourceBranch
= self
.knownBranches
[branch
]
1199 sourceDepotPath
= self
.depotPaths
[0] + sourceBranch
1200 sourceRef
= self
.gitRefForBranch(sourceBranch
)
1201 #print "source " + sourceBranch
1203 branchParentChange
= int(p4Cmd("changes -m 1 %s...@1,%s" % (sourceDepotPath
, firstChange
))["change"])
1204 #print "branch parent: %s" % branchParentChange
1205 gitParent
= self
.gitCommitByP4Change(sourceRef
, branchParentChange
)
1206 if len(gitParent
) > 0:
1207 self
.initialParents
[self
.gitRefForBranch(branch
)] = gitParent
1208 #print "parent git commit: %s" % gitParent
1210 self
.importChanges(changes
)
1213 def importChanges(self
, changes
):
1215 for change
in changes
:
1216 description
= p4Cmd("describe %s" % change
)
1217 self
.updateOptionDict(description
)
1220 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1225 if self
.detectBranches
:
1226 branches
= self
.splitFilesIntoBranches(description
)
1227 for branch
in branches
.keys():
1229 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1233 filesForCommit
= branches
[branch
]
1236 print "branch is %s" % branch
1238 self
.updatedBranches
.add(branch
)
1240 if branch
not in self
.createdBranches
:
1241 self
.createdBranches
.add(branch
)
1242 parent
= self
.knownBranches
[branch
]
1243 if parent
== branch
:
1246 fullBranch
= self
.projectName
+ branch
1247 if fullBranch
not in self
.p4BranchesInGit
:
1249 print("\n Importing new branch %s" % fullBranch
);
1250 if self
.importNewBranch(branch
, change
- 1):
1252 self
.p4BranchesInGit
.append(fullBranch
)
1254 print("\n Resuming with change %s" % change
);
1257 print "parent determined through known branches: %s" % parent
1259 branch
= self
.gitRefForBranch(branch
)
1260 parent
= self
.gitRefForBranch(parent
)
1263 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1265 if len(parent
) == 0 and branch
in self
.initialParents
:
1266 parent
= self
.initialParents
[branch
]
1267 del self
.initialParents
[branch
]
1269 self
.commit(description
, filesForCommit
, branch
, [branchPrefix
], parent
)
1271 files
= self
.extractFilesFromCommit(description
)
1272 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1274 self
.initialParent
= ""
1276 print self
.gitError
.read()
1279 def importHeadRevision(self
, revision
):
1280 print "Doing initial import of %s from revision %s into %s" % (' '.join(self
.depotPaths
), revision
, self
.branch
)
1282 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1283 details
["desc"] = ("Initial import of %s from the state at revision %s"
1284 % (' '.join(self
.depotPaths
), revision
))
1285 details
["change"] = revision
1289 for info
in p4CmdList("files "
1290 + ' '.join(["%s...%s"
1292 for p
in self
.depotPaths
])):
1294 if info
['code'] == 'error':
1295 sys
.stderr
.write("p4 returned an error: %s\n"
1300 change
= int(info
["change"])
1301 if change
> newestRevision
:
1302 newestRevision
= change
1304 if info
["action"] == "delete":
1305 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1306 #fileCnt = fileCnt + 1
1309 for prop
in ["depotFile", "rev", "action", "type" ]:
1310 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1312 fileCnt
= fileCnt
+ 1
1314 details
["change"] = newestRevision
1315 self
.updateOptionDict(details
)
1317 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1319 print "IO error with git fast-import. Is your git version recent enough?"
1320 print self
.gitError
.read()
1323 def run(self
, args
):
1324 self
.depotPaths
= []
1325 self
.changeRange
= ""
1326 self
.initialParent
= ""
1327 self
.previousDepotPaths
= []
1329 # map from branch depot path to parent branch
1330 self
.knownBranches
= {}
1331 self
.initialParents
= {}
1332 self
.hasOrigin
= originP4BranchesExist()
1333 if not self
.syncWithOrigin
:
1334 self
.hasOrigin
= False
1336 if self
.importIntoRemotes
:
1337 self
.refPrefix
= "refs/remotes/p4/"
1339 self
.refPrefix
= "refs/heads/p4/"
1341 if self
.syncWithOrigin
and self
.hasOrigin
:
1343 print "Syncing with origin first by calling git fetch origin"
1344 system("git fetch origin")
1346 if len(self
.branch
) == 0:
1347 self
.branch
= self
.refPrefix
+ "master"
1348 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1349 system("git update-ref %s refs/heads/p4" % self
.branch
)
1350 system("git branch -D p4");
1351 # create it /after/ importing, when master exists
1352 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
and gitBranchExists(self
.branch
):
1353 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1355 # TODO: should always look at previous commits,
1356 # merge with previous imports, if possible.
1359 createOrUpdateBranchesFromOrigin(self
.refPrefix
, self
.silent
)
1360 self
.listExistingP4GitBranches()
1362 if len(self
.p4BranchesInGit
) > 1:
1364 print "Importing from/into multiple branches"
1365 self
.detectBranches
= True
1368 print "branches: %s" % self
.p4BranchesInGit
1371 for branch
in self
.p4BranchesInGit
:
1372 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1374 settings
= extractSettingsGitLog(logMsg
)
1376 self
.readOptions(settings
)
1377 if (settings
.has_key('depot-paths')
1378 and settings
.has_key ('change')):
1379 change
= int(settings
['change']) + 1
1380 p4Change
= max(p4Change
, change
)
1382 depotPaths
= sorted(settings
['depot-paths'])
1383 if self
.previousDepotPaths
== []:
1384 self
.previousDepotPaths
= depotPaths
1387 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1388 for i
in range(0, min(len(cur
), len(prev
))):
1389 if cur
[i
] <> prev
[i
]:
1393 paths
.append (cur
[:i
+ 1])
1395 self
.previousDepotPaths
= paths
1398 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1399 self
.changeRange
= "@%s,#head" % p4Change
1400 if not self
.detectBranches
:
1401 self
.initialParent
= parseRevision(self
.branch
)
1402 if not self
.silent
and not self
.detectBranches
:
1403 print "Performing incremental import into %s git branch" % self
.branch
1405 if not self
.branch
.startswith("refs/"):
1406 self
.branch
= "refs/heads/" + self
.branch
1408 if len(args
) == 0 and self
.depotPaths
:
1410 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1412 if self
.depotPaths
and self
.depotPaths
!= args
:
1413 print ("previous import used depot path %s and now %s was specified. "
1414 "This doesn't work!" % (' '.join (self
.depotPaths
),
1418 self
.depotPaths
= sorted(args
)
1424 for p
in self
.depotPaths
:
1425 if p
.find("@") != -1:
1426 atIdx
= p
.index("@")
1427 self
.changeRange
= p
[atIdx
:]
1428 if self
.changeRange
== "@all":
1429 self
.changeRange
= ""
1430 elif ',' not in self
.changeRange
:
1431 revision
= self
.changeRange
1432 self
.changeRange
= ""
1434 elif p
.find("#") != -1:
1435 hashIdx
= p
.index("#")
1436 revision
= p
[hashIdx
:]
1438 elif self
.previousDepotPaths
== []:
1441 p
= re
.sub ("\.\.\.$", "", p
)
1442 if not p
.endswith("/"):
1447 self
.depotPaths
= newPaths
1450 self
.loadUserMapFromCache()
1452 if self
.detectLabels
:
1455 if self
.detectBranches
:
1456 ## FIXME - what's a P4 projectName ?
1457 self
.projectName
= self
.guessProjectName()
1459 if not self
.hasOrigin
:
1460 self
.getBranchMapping();
1462 print "p4-git branches: %s" % self
.p4BranchesInGit
1463 print "initial parents: %s" % self
.initialParents
1464 for b
in self
.p4BranchesInGit
:
1468 b
= b
[len(self
.projectName
):]
1469 self
.createdBranches
.add(b
)
1471 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1473 importProcess
= subprocess
.Popen(["git", "fast-import"],
1474 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1475 stderr
=subprocess
.PIPE
);
1476 self
.gitOutput
= importProcess
.stdout
1477 self
.gitStream
= importProcess
.stdin
1478 self
.gitError
= importProcess
.stderr
1481 self
.importHeadRevision(revision
)
1485 if len(self
.changesFile
) > 0:
1486 output
= open(self
.changesFile
).readlines()
1489 changeSet
.add(int(line
))
1491 for change
in changeSet
:
1492 changes
.append(change
)
1497 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1499 changes
= p4ChangesForPaths(self
.depotPaths
, self
.changeRange
)
1501 if len(self
.maxChanges
) > 0:
1502 changes
= changes
[:min(int(self
.maxChanges
), len(changes
))]
1504 if len(changes
) == 0:
1506 print "No changes to import!"
1509 if not self
.silent
and not self
.detectBranches
:
1510 print "Import destination: %s" % self
.branch
1512 self
.updatedBranches
= set()
1514 self
.importChanges(changes
)
1518 if len(self
.updatedBranches
) > 0:
1519 sys
.stdout
.write("Updated branches: ")
1520 for b
in self
.updatedBranches
:
1521 sys
.stdout
.write("%s " % b
)
1522 sys
.stdout
.write("\n")
1524 self
.gitStream
.close()
1525 if importProcess
.wait() != 0:
1526 die("fast-import failed: %s" % self
.gitError
.read())
1527 self
.gitOutput
.close()
1528 self
.gitError
.close()
1532 class P4Rebase(Command
):
1534 Command
.__init
__(self
)
1536 self
.description
= ("Fetches the latest revision from perforce and "
1537 + "rebases the current work (branch) against it")
1538 self
.verbose
= False
1540 def run(self
, args
):
1544 return self
.rebase()
1547 [upstream
, settings
] = findUpstreamBranchPoint()
1548 if len(upstream
) == 0:
1549 die("Cannot find upstream branchpoint for rebase")
1551 # the branchpoint may be p4/foo~3, so strip off the parent
1552 upstream
= re
.sub("~[0-9]+$", "", upstream
)
1554 print "Rebasing the current branch onto %s" % upstream
1555 oldHead
= read_pipe("git rev-parse HEAD").strip()
1556 system("git rebase %s" % upstream
)
1557 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1560 class P4Clone(P4Sync
):
1562 P4Sync
.__init
__(self
)
1563 self
.description
= "Creates a new git repository and imports from Perforce into it"
1564 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1565 self
.options
.append(
1566 optparse
.make_option("--destination", dest
="cloneDestination",
1567 action
='store', default
=None,
1568 help="where to leave result of the clone"))
1569 self
.cloneDestination
= None
1570 self
.needsGit
= False
1572 def defaultDestination(self
, args
):
1573 ## TODO: use common prefix of args?
1575 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1576 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1577 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1578 depotDir
= re
.sub(r
"/$", "", depotDir
)
1579 return os
.path
.split(depotDir
)[1]
1581 def run(self
, args
):
1585 if self
.keepRepoPath
and not self
.cloneDestination
:
1586 sys
.stderr
.write("Must specify destination for --keep-path\n")
1591 if not self
.cloneDestination
and len(depotPaths
) > 1:
1592 self
.cloneDestination
= depotPaths
[-1]
1593 depotPaths
= depotPaths
[:-1]
1595 for p
in depotPaths
:
1596 if not p
.startswith("//"):
1599 if not self
.cloneDestination
:
1600 self
.cloneDestination
= self
.defaultDestination(args
)
1602 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1603 if not os
.path
.exists(self
.cloneDestination
):
1604 os
.makedirs(self
.cloneDestination
)
1605 os
.chdir(self
.cloneDestination
)
1607 self
.gitdir
= os
.getcwd() + "/.git"
1608 if not P4Sync
.run(self
, depotPaths
):
1610 if self
.branch
!= "master":
1611 if gitBranchExists("refs/remotes/p4/master"):
1612 system("git branch master refs/remotes/p4/master")
1613 system("git checkout -f")
1615 print "Could not detect main branch. No checkout/master branch created."
1619 class P4Branches(Command
):
1621 Command
.__init
__(self
)
1623 self
.description
= ("Shows the git branches that hold imports and their "
1624 + "corresponding perforce depot paths")
1625 self
.verbose
= False
1627 def run(self
, args
):
1628 if originP4BranchesExist():
1629 createOrUpdateBranchesFromOrigin()
1631 cmdline
= "git rev-parse --symbolic "
1632 cmdline
+= " --remotes"
1634 for line
in read_pipe_lines(cmdline
):
1637 if not line
.startswith('p4/') or line
== "p4/HEAD":
1641 log
= extractLogMessageFromGitCommit("refs/remotes/%s" % branch
)
1642 settings
= extractSettingsGitLog(log
)
1644 print "%s <= %s (%s)" % (branch
, ",".join(settings
["depot-paths"]), settings
["change"])
1647 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1649 optparse
.IndentedHelpFormatter
.__init
__(self
)
1651 def format_description(self
, description
):
1653 return description
+ "\n"
1657 def printUsage(commands
):
1658 print "usage: %s <command> [options]" % sys
.argv
[0]
1660 print "valid commands: %s" % ", ".join(commands
)
1662 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1667 "submit" : P4Submit
,
1668 "commit" : P4Submit
,
1670 "rebase" : P4Rebase
,
1672 "rollback" : P4RollBack
,
1673 "branches" : P4Branches
1678 if len(sys
.argv
[1:]) == 0:
1679 printUsage(commands
.keys())
1683 cmdName
= sys
.argv
[1]
1685 klass
= commands
[cmdName
]
1688 print "unknown command %s" % cmdName
1690 printUsage(commands
.keys())
1693 options
= cmd
.options
1694 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1698 if len(options
) > 0:
1699 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1701 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1703 description
= cmd
.description
,
1704 formatter
= HelpFormatter())
1706 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1708 verbose
= cmd
.verbose
1710 if cmd
.gitdir
== None:
1711 cmd
.gitdir
= os
.path
.abspath(".git")
1712 if not isValidGitDir(cmd
.gitdir
):
1713 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1714 if os
.path
.exists(cmd
.gitdir
):
1715 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1719 if not isValidGitDir(cmd
.gitdir
):
1720 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1721 cmd
.gitdir
+= "/.git"
1723 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1725 os
.environ
["GIT_DIR"] = cmd
.gitdir
1727 if not cmd
.run(args
):
1731 if __name__
== '__main__':