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
)
66 def p4CmdList(cmd
, stdin
=None, stdin_mode
='w+b'):
67 cmd
= "p4 -G %s" % cmd
69 sys
.stderr
.write("Opening pipe: %s\n" % cmd
)
71 # Use a temporary file to avoid deadlocks without
72 # subprocess.communicate(), which would put another copy
73 # of stdout into memory.
76 stdin_file
= tempfile
.TemporaryFile(prefix
='p4-stdin', mode
=stdin_mode
)
77 stdin_file
.write(stdin
)
81 p4
= subprocess
.Popen(cmd
, shell
=True,
83 stdout
=subprocess
.PIPE
)
88 entry
= marshal
.load(p4
.stdout
)
95 entry
["p4ExitCode"] = exitCode
101 list = p4CmdList(cmd
)
107 def p4Where(depotPath
):
108 if not depotPath
.endswith("/"):
110 output
= p4Cmd("where %s..." % depotPath
)
111 if output
["code"] == "error":
115 clientPath
= output
.get("path")
116 elif "data" in output
:
117 data
= output
.get("data")
118 lastSpace
= data
.rfind(" ")
119 clientPath
= data
[lastSpace
+ 1:]
121 if clientPath
.endswith("..."):
122 clientPath
= clientPath
[:-3]
125 def currentGitBranch():
126 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
128 def isValidGitDir(path
):
129 if (os
.path
.exists(path
+ "/HEAD")
130 and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects")):
134 def parseRevision(ref
):
135 return read_pipe("git rev-parse %s" % ref
).strip()
137 def extractLogMessageFromGitCommit(commit
):
140 ## fixme: title is first line of commit, not 1st paragraph.
142 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
151 def extractSettingsGitLog(log
):
153 for line
in log
.split("\n"):
155 m
= re
.search (r
"^ *\[git-p4: (.*)\]$", line
)
159 assignments
= m
.group(1).split (':')
160 for a
in assignments
:
162 key
= vals
[0].strip()
163 val
= ('='.join (vals
[1:])).strip()
164 if val
.endswith ('\"') and val
.startswith('"'):
169 paths
= values
.get("depot-paths")
171 paths
= values
.get("depot-path")
173 values
['depot-paths'] = paths
.split(',')
176 def gitBranchExists(branch
):
177 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
178 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
179 return proc
.wait() == 0;
182 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
184 def p4BranchesInGit(branchesAreInRemotes
= True):
187 cmdline
= "git rev-parse --symbolic "
188 if branchesAreInRemotes
:
189 cmdline
+= " --remotes"
191 cmdline
+= " --branches"
193 for line
in read_pipe_lines(cmdline
):
196 ## only import to p4/
197 if not line
.startswith('p4/') or line
== "p4/HEAD":
202 branch
= re
.sub ("^p4/", "", line
)
204 branches
[branch
] = parseRevision(line
)
207 def findUpstreamBranchPoint(head
= "HEAD"):
208 branches
= p4BranchesInGit()
209 # map from depot-path to branch name
210 branchByDepotPath
= {}
211 for branch
in branches
.keys():
212 tip
= branches
[branch
]
213 log
= extractLogMessageFromGitCommit(tip
)
214 settings
= extractSettingsGitLog(log
)
215 if settings
.has_key("depot-paths"):
216 paths
= ",".join(settings
["depot-paths"])
217 branchByDepotPath
[paths
] = "remotes/p4/" + branch
221 while parent
< 65535:
222 commit
= head
+ "~%s" % parent
223 log
= extractLogMessageFromGitCommit(commit
)
224 settings
= extractSettingsGitLog(log
)
225 if settings
.has_key("depot-paths"):
226 paths
= ",".join(settings
["depot-paths"])
227 if branchByDepotPath
.has_key(paths
):
228 return [branchByDepotPath
[paths
], settings
]
232 return ["", settings
]
234 def createOrUpdateBranchesFromOrigin(localRefPrefix
= "refs/remotes/p4/", silent
=True):
236 print ("Creating/updating branch(es) in %s based on origin branch(es)"
239 originPrefix
= "origin/p4/"
241 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
243 if (not line
.startswith(originPrefix
)) or line
.endswith("HEAD"):
246 headName
= line
[len(originPrefix
):]
247 remoteHead
= localRefPrefix
+ headName
250 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
251 if (not original
.has_key('depot-paths')
252 or not original
.has_key('change')):
256 if not gitBranchExists(remoteHead
):
258 print "creating %s" % remoteHead
261 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
262 if settings
.has_key('change') > 0:
263 if settings
['depot-paths'] == original
['depot-paths']:
264 originP4Change
= int(original
['change'])
265 p4Change
= int(settings
['change'])
266 if originP4Change
> p4Change
:
267 print ("%s (%s) is newer than %s (%s). "
268 "Updating p4 branch from origin."
269 % (originHead
, originP4Change
,
270 remoteHead
, p4Change
))
273 print ("Ignoring: %s was imported from %s while "
274 "%s was imported from %s"
275 % (originHead
, ','.join(original
['depot-paths']),
276 remoteHead
, ','.join(settings
['depot-paths'])))
279 system("git update-ref %s %s" % (remoteHead
, originHead
))
281 def originP4BranchesExist():
282 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
284 def p4ChangesForPaths(depotPaths
, changeRange
):
286 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, changeRange
)
287 for p
in depotPaths
]))
291 changeNum
= line
.split(" ")[1]
292 changes
.append(int(changeNum
))
299 self
.usage
= "usage: %prog [options]"
302 class P4Debug(Command
):
304 Command
.__init
__(self
)
306 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
309 self
.description
= "A tool to debug the output of p4 -G."
310 self
.needsGit
= False
315 for output
in p4CmdList(" ".join(args
)):
316 print 'Element: %d' % j
321 class P4RollBack(Command
):
323 Command
.__init
__(self
)
325 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
326 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
328 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
330 self
.rollbackLocalBranches
= False
335 maxChange
= int(args
[0])
337 if "p4ExitCode" in p4Cmd("changes -m 1"):
338 die("Problems executing p4");
340 if self
.rollbackLocalBranches
:
341 refPrefix
= "refs/heads/"
342 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
344 refPrefix
= "refs/remotes/"
345 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
348 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
350 ref
= refPrefix
+ line
351 log
= extractLogMessageFromGitCommit(ref
)
352 settings
= extractSettingsGitLog(log
)
354 depotPaths
= settings
['depot-paths']
355 change
= settings
['change']
359 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
360 for p
in depotPaths
]))) == 0:
361 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
362 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
365 while change
and int(change
) > maxChange
:
368 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
369 system("git update-ref %s \"%s^\"" % (ref
, ref
))
370 log
= extractLogMessageFromGitCommit(ref
)
371 settings
= extractSettingsGitLog(log
)
374 depotPaths
= settings
['depot-paths']
375 change
= settings
['change']
378 print "%s rewound to %s" % (ref
, change
)
382 class P4Submit(Command
):
384 Command
.__init
__(self
)
386 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
387 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
388 optparse
.make_option("--origin", dest
="origin"),
389 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
390 optparse
.make_option("--log-substitutions", dest
="substFile"),
391 optparse
.make_option("--dry-run", action
="store_true"),
392 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
393 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
395 self
.description
= "Submit changes from git to the perforce depot."
396 self
.usage
+= " [name of git branch to submit into perforce depot]"
397 self
.firstTime
= True
399 self
.interactive
= True
402 self
.firstTime
= True
404 self
.directSubmit
= False
405 self
.trustMeLikeAFool
= False
407 self
.isWindows
= (platform
.system() == "Windows")
409 self
.logSubstitutions
= {}
410 self
.logSubstitutions
["<enter description here>"] = "%log%"
411 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
414 if len(p4CmdList("opened ...")) > 0:
415 die("You have files opened with perforce! Close them before starting the sync.")
418 if len(self
.config
) > 0 and not self
.reset
:
419 die("Cannot start sync. Previous sync config found at %s\n"
420 "If you want to start submitting again from scratch "
421 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
424 if self
.directSubmit
:
427 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
428 commits
.append(line
.strip())
431 self
.config
["commits"] = commits
433 def prepareLogMessage(self
, template
, message
):
436 for line
in template
.split("\n"):
437 if line
.startswith("#"):
438 result
+= line
+ "\n"
442 for key
in self
.logSubstitutions
.keys():
443 if line
.find(key
) != -1:
444 value
= self
.logSubstitutions
[key
]
445 value
= value
.replace("%log%", message
)
446 if value
!= "@remove@":
447 result
+= line
.replace(key
, value
) + "\n"
452 result
+= line
+ "\n"
456 def prepareSubmitTemplate(self
):
457 # remove lines in the Files section that show changes to files outside the depot path we're committing into
459 inFilesSection
= False
460 for line
in read_pipe_lines("p4 change -o"):
462 if line
.startswith("\t"):
463 # path starts and ends with a tab
465 lastTab
= path
.rfind("\t")
467 path
= path
[:lastTab
]
468 if not path
.startswith(self
.depotPath
):
471 inFilesSection
= False
473 if line
.startswith("Files:"):
474 inFilesSection
= True
480 def applyCommit(self
, id):
481 if self
.directSubmit
:
482 print "Applying local change in working directory/index"
483 diff
= self
.diffStatus
485 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
486 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
488 filesToDelete
= set()
492 path
= line
[1:].strip()
494 system("p4 edit \"%s\"" % path
)
495 editedFiles
.add(path
)
496 elif modifier
== "A":
498 if path
in filesToDelete
:
499 filesToDelete
.remove(path
)
500 elif modifier
== "D":
501 filesToDelete
.add(path
)
502 if path
in filesToAdd
:
503 filesToAdd
.remove(path
)
505 die("unknown modifier %s for %s" % (modifier
, path
))
507 if self
.directSubmit
:
508 diffcmd
= "cat \"%s\"" % self
.diffFile
510 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
511 patchcmd
= diffcmd
+ " | git apply "
512 tryPatchCmd
= patchcmd
+ "--check -"
513 applyPatchCmd
= patchcmd
+ "--check --apply -"
515 if os
.system(tryPatchCmd
) != 0:
516 print "Unfortunately applying the change failed!"
517 print "What do you want to do?"
519 while response
!= "s" and response
!= "a" and response
!= "w":
520 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
521 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
523 print "Skipping! Good luck with the next patches..."
525 elif response
== "a":
526 os
.system(applyPatchCmd
)
527 if len(filesToAdd
) > 0:
528 print "You may also want to call p4 add on the following files:"
529 print " ".join(filesToAdd
)
530 if len(filesToDelete
):
531 print "The following files should be scheduled for deletion with p4 delete:"
532 print " ".join(filesToDelete
)
533 die("Please resolve and submit the conflict manually and "
534 + "continue afterwards with git-p4 submit --continue")
535 elif response
== "w":
536 system(diffcmd
+ " > patch.txt")
537 print "Patch saved to patch.txt in %s !" % self
.clientPath
538 die("Please resolve and submit the conflict manually and "
539 "continue afterwards with git-p4 submit --continue")
541 system(applyPatchCmd
)
544 system("p4 add \"%s\"" % f
)
545 for f
in filesToDelete
:
546 system("p4 revert \"%s\"" % f
)
547 system("p4 delete \"%s\"" % f
)
550 if not self
.directSubmit
:
551 logMessage
= extractLogMessageFromGitCommit(id)
552 logMessage
= logMessage
.replace("\n", "\n\t")
554 logMessage
= logMessage
.replace("\n", "\r\n")
555 logMessage
= logMessage
.strip()
557 template
= self
.prepareSubmitTemplate()
560 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
561 diff
= read_pipe("p4 diff -du ...")
563 for newFile
in filesToAdd
:
564 diff
+= "==== new file ====\n"
565 diff
+= "--- /dev/null\n"
566 diff
+= "+++ %s\n" % newFile
567 f
= open(newFile
, "r")
568 for line
in f
.readlines():
572 separatorLine
= "######## everything below this line is just the diff #######"
573 if platform
.system() == "Windows":
574 separatorLine
+= "\r"
575 separatorLine
+= "\n"
578 if self
.trustMeLikeAFool
:
581 firstIteration
= True
582 while response
== "e":
583 if not firstIteration
:
584 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
585 firstIteration
= False
587 [handle
, fileName
] = tempfile
.mkstemp()
588 tmpFile
= os
.fdopen(handle
, "w+")
589 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
592 if platform
.system() == "Windows":
593 defaultEditor
= "notepad"
594 editor
= os
.environ
.get("EDITOR", defaultEditor
);
595 system(editor
+ " " + fileName
)
596 tmpFile
= open(fileName
, "rb")
597 message
= tmpFile
.read()
600 submitTemplate
= message
[:message
.index(separatorLine
)]
602 submitTemplate
= submitTemplate
.replace("\r\n", "\n")
604 if response
== "y" or response
== "yes":
607 raw_input("Press return to continue...")
609 if self
.directSubmit
:
610 print "Submitting to git first"
611 os
.chdir(self
.oldWorkingDirectory
)
612 write_pipe("git commit -a -F -", submitTemplate
)
613 os
.chdir(self
.clientPath
)
615 write_pipe("p4 submit -i", submitTemplate
)
616 elif response
== "s":
617 for f
in editedFiles
:
618 system("p4 revert \"%s\"" % f
);
620 system("p4 revert \"%s\"" % f
);
622 for f
in filesToDelete
:
623 system("p4 delete \"%s\"" % f
);
626 print "Not submitting!"
627 self
.interactive
= False
629 fileName
= "submit.txt"
630 file = open(fileName
, "w+")
631 file.write(self
.prepareLogMessage(template
, logMessage
))
633 print ("Perforce submit template written as %s. "
634 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
635 % (fileName
, fileName
))
639 self
.master
= currentGitBranch()
640 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
641 die("Detecting current git branch failed!")
643 self
.master
= args
[0]
647 [upstream
, settings
] = findUpstreamBranchPoint()
648 self
.depotPath
= settings
['depot-paths'][0]
649 if len(self
.origin
) == 0:
650 self
.origin
= upstream
653 print "Origin branch is " + self
.origin
655 if len(self
.depotPath
) == 0:
656 print "Internal error: cannot locate perforce depot path from existing branches"
659 self
.clientPath
= p4Where(self
.depotPath
)
661 if len(self
.clientPath
) == 0:
662 print "Error: Cannot locate perforce checkout of %s in client view" % self
.depotPath
665 print "Perforce checkout for depot path %s located at %s" % (self
.depotPath
, self
.clientPath
)
666 self
.oldWorkingDirectory
= os
.getcwd()
668 if self
.directSubmit
:
669 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
670 if len(self
.diffStatus
) == 0:
671 print "No changes in working directory to submit."
673 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
674 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
675 f
= open(self
.diffFile
, "wb")
679 os
.chdir(self
.clientPath
)
680 print "Syncronizing p4 checkout..."
681 system("p4 sync ...")
684 self
.firstTime
= True
686 if len(self
.substFile
) > 0:
687 for line
in open(self
.substFile
, "r").readlines():
688 tokens
= line
.strip().split("=")
689 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
692 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
693 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
698 commits
= self
.config
.get("commits", [])
700 while len(commits
) > 0:
701 self
.firstTime
= False
703 commits
= commits
[1:]
704 self
.config
["commits"] = commits
705 self
.applyCommit(commit
)
706 if not self
.interactive
:
711 if self
.directSubmit
:
712 os
.remove(self
.diffFile
)
714 if len(commits
) == 0:
716 print "No changes found to apply between %s and current HEAD" % self
.origin
718 print "All changes applied!"
719 os
.chdir(self
.oldWorkingDirectory
)
724 response
= raw_input("Do you want to rebase current HEAD from Perforce now using git-p4 rebase? [y]es/[n]o ")
725 if response
== "y" or response
== "yes":
728 os
.remove(self
.configFile
)
732 class P4Sync(Command
):
734 Command
.__init
__(self
)
736 optparse
.make_option("--branch", dest
="branch"),
737 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
738 optparse
.make_option("--changesfile", dest
="changesFile"),
739 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
740 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
741 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
742 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
743 help="Import into refs/heads/ , not refs/remotes"),
744 optparse
.make_option("--max-changes", dest
="maxChanges"),
745 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
746 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
748 self
.description
= """Imports from Perforce into a git repository.\n
750 //depot/my/project/ -- to import the current head
751 //depot/my/project/@all -- to import everything
752 //depot/my/project/@1,6 -- to import only from revision 1 to 6
754 (a ... is not needed in the path p4 specification, it's added implicitly)"""
756 self
.usage
+= " //depot/path[@revRange]"
758 self
.createdBranches
= Set()
759 self
.committedChanges
= Set()
761 self
.detectBranches
= False
762 self
.detectLabels
= False
763 self
.changesFile
= ""
764 self
.syncWithOrigin
= True
766 self
.importIntoRemotes
= True
768 self
.isWindows
= (platform
.system() == "Windows")
769 self
.keepRepoPath
= False
770 self
.depotPaths
= None
771 self
.p4BranchesInGit
= []
773 if gitConfig("git-p4.syncFromOrigin") == "false":
774 self
.syncWithOrigin
= False
776 def extractFilesFromCommit(self
, commit
):
779 while commit
.has_key("depotFile%s" % fnum
):
780 path
= commit
["depotFile%s" % fnum
]
782 found
= [p
for p
in self
.depotPaths
783 if path
.startswith (p
)]
790 file["rev"] = commit
["rev%s" % fnum
]
791 file["action"] = commit
["action%s" % fnum
]
792 file["type"] = commit
["type%s" % fnum
]
797 def stripRepoPath(self
, path
, prefixes
):
798 if self
.keepRepoPath
:
799 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
802 if path
.startswith(p
):
807 def splitFilesIntoBranches(self
, commit
):
810 while commit
.has_key("depotFile%s" % fnum
):
811 path
= commit
["depotFile%s" % fnum
]
812 found
= [p
for p
in self
.depotPaths
813 if path
.startswith (p
)]
820 file["rev"] = commit
["rev%s" % fnum
]
821 file["action"] = commit
["action%s" % fnum
]
822 file["type"] = commit
["type%s" % fnum
]
825 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
827 for branch
in self
.knownBranches
.keys():
829 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
830 if relPath
.startswith(branch
+ "/"):
831 if branch
not in branches
:
832 branches
[branch
] = []
833 branches
[branch
].append(file)
838 ## Should move this out, doesn't use SELF.
839 def readP4Files(self
, files
):
840 files
= [f
for f
in files
841 if f
['action'] != 'delete']
846 filedata
= p4CmdList('-x - print',
847 stdin
='\n'.join(['%s#%s' % (f
['path'], f
['rev'])
850 if "p4ExitCode" in filedata
[0]:
851 die("Problems executing p4. Error: [%d]."
852 % (filedata
[0]['p4ExitCode']));
856 while j
< len(filedata
):
860 while j
< len(filedata
) and filedata
[j
]['code'] in ('text',
862 text
+= filedata
[j
]['data']
866 if not stat
.has_key('depotFile'):
867 sys
.stderr
.write("p4 print fails with: %s\n" % repr(stat
))
870 contents
[stat
['depotFile']] = text
873 assert not f
.has_key('data')
874 f
['data'] = contents
[f
['path']]
876 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
877 epoch
= details
["time"]
878 author
= details
["user"]
881 print "commit into %s" % branch
883 # start with reading files; if that fails, we should not
887 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
890 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
892 self
.readP4Files(files
)
897 self
.gitStream
.write("commit %s\n" % branch
)
898 # gitStream.write("mark :%s\n" % details["change"])
899 self
.committedChanges
.add(int(details
["change"]))
901 if author
not in self
.users
:
902 self
.getUserMapFromPerforceServer()
903 if author
in self
.users
:
904 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
906 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
908 self
.gitStream
.write("committer %s\n" % committer
)
910 self
.gitStream
.write("data <<EOT\n")
911 self
.gitStream
.write(details
["desc"])
912 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s"
913 % (','.join (branchPrefixes
), details
["change"]))
914 if len(details
['options']) > 0:
915 self
.gitStream
.write(": options = %s" % details
['options'])
916 self
.gitStream
.write("]\nEOT\n\n")
920 print "parent %s" % parent
921 self
.gitStream
.write("from %s\n" % parent
)
924 if file["type"] == "apple":
925 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
928 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
929 if file["action"] == "delete":
930 self
.gitStream
.write("D %s\n" % relPath
)
935 if file["type"].startswith("x"):
937 elif file["type"] == "symlink":
939 # p4 print on a symlink contains "target\n", so strip it off
942 if self
.isWindows
and file["type"].endswith("text"):
943 data
= data
.replace("\r\n", "\n")
945 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
946 self
.gitStream
.write("data %s\n" % len(data
))
947 self
.gitStream
.write(data
)
948 self
.gitStream
.write("\n")
950 self
.gitStream
.write("\n")
952 change
= int(details
["change"])
954 if self
.labels
.has_key(change
):
955 label
= self
.labels
[change
]
956 labelDetails
= label
[0]
957 labelRevisions
= label
[1]
959 print "Change %s is labelled %s" % (change
, labelDetails
)
961 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
962 for p
in branchPrefixes
]))
964 if len(files
) == len(labelRevisions
):
968 if info
["action"] == "delete":
970 cleanedFiles
[info
["depotFile"]] = info
["rev"]
972 if cleanedFiles
== labelRevisions
:
973 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
974 self
.gitStream
.write("from %s\n" % branch
)
976 owner
= labelDetails
["Owner"]
978 if author
in self
.users
:
979 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
981 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
982 self
.gitStream
.write("tagger %s\n" % tagger
)
983 self
.gitStream
.write("data <<EOT\n")
984 self
.gitStream
.write(labelDetails
["Description"])
985 self
.gitStream
.write("EOT\n\n")
989 print ("Tag %s does not match with change %s: files do not match."
990 % (labelDetails
["label"], change
))
994 print ("Tag %s does not match with change %s: file count is different."
995 % (labelDetails
["label"], change
))
997 def getUserCacheFilename(self
):
998 home
= os
.environ
.get("HOME", os
.environ
.get("USERPROFILE"))
999 return home
+ "/.gitp4-usercache.txt"
1001 def getUserMapFromPerforceServer(self
):
1002 if self
.userMapFromPerforceServer
:
1006 for output
in p4CmdList("users"):
1007 if not output
.has_key("User"):
1009 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
1013 for (key
, val
) in self
.users
.items():
1014 s
+= "%s\t%s\n" % (key
, val
)
1016 open(self
.getUserCacheFilename(), "wb").write(s
)
1017 self
.userMapFromPerforceServer
= True
1019 def loadUserMapFromCache(self
):
1021 self
.userMapFromPerforceServer
= False
1023 cache
= open(self
.getUserCacheFilename(), "rb")
1024 lines
= cache
.readlines()
1027 entry
= line
.strip().split("\t")
1028 self
.users
[entry
[0]] = entry
[1]
1030 self
.getUserMapFromPerforceServer()
1032 def getLabels(self
):
1035 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
1036 if len(l
) > 0 and not self
.silent
:
1037 print "Finding files belonging to labels in %s" % `self
.depotPath`
1040 label
= output
["label"]
1044 print "Querying files for label %s" % label
1045 for file in p4CmdList("files "
1046 + ' '.join (["%s...@%s" % (p
, label
)
1047 for p
in self
.depotPaths
])):
1048 revisions
[file["depotFile"]] = file["rev"]
1049 change
= int(file["change"])
1050 if change
> newestChange
:
1051 newestChange
= change
1053 self
.labels
[newestChange
] = [output
, revisions
]
1056 print "Label changes: %s" % self
.labels
.keys()
1058 def guessProjectName(self
):
1059 for p
in self
.depotPaths
:
1062 p
= p
[p
.strip().rfind("/") + 1:]
1063 if not p
.endswith("/"):
1067 def getBranchMapping(self
):
1068 lostAndFoundBranches
= set()
1070 for info
in p4CmdList("branches"):
1071 details
= p4Cmd("branch -o %s" % info
["branch"])
1073 while details
.has_key("View%s" % viewIdx
):
1074 paths
= details
["View%s" % viewIdx
].split(" ")
1075 viewIdx
= viewIdx
+ 1
1076 # require standard //depot/foo/... //depot/bar/... mapping
1077 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
1080 destination
= paths
[1]
1082 if source
.startswith(self
.depotPaths
[0]) and destination
.startswith(self
.depotPaths
[0]):
1083 source
= source
[len(self
.depotPaths
[0]):-4]
1084 destination
= destination
[len(self
.depotPaths
[0]):-4]
1086 if destination
in self
.knownBranches
:
1088 print "p4 branch %s defines a mapping from %s to %s" % (info
["branch"], source
, destination
)
1089 print "but there exists another mapping from %s to %s already!" % (self
.knownBranches
[destination
], destination
)
1092 self
.knownBranches
[destination
] = source
1094 lostAndFoundBranches
.discard(destination
)
1096 if source
not in self
.knownBranches
:
1097 lostAndFoundBranches
.add(source
)
1100 for branch
in lostAndFoundBranches
:
1101 self
.knownBranches
[branch
] = branch
1103 def listExistingP4GitBranches(self
):
1104 # branches holds mapping from name to commit
1105 branches
= p4BranchesInGit(self
.importIntoRemotes
)
1106 self
.p4BranchesInGit
= branches
.keys()
1107 for branch
in branches
.keys():
1108 self
.initialParents
[self
.refPrefix
+ branch
] = branches
[branch
]
1110 def updateOptionDict(self
, d
):
1112 if self
.keepRepoPath
:
1113 option_keys
['keepRepoPath'] = 1
1115 d
["options"] = ' '.join(sorted(option_keys
.keys()))
1117 def readOptions(self
, d
):
1118 self
.keepRepoPath
= (d
.has_key('options')
1119 and ('keepRepoPath' in d
['options']))
1121 def gitRefForBranch(self
, branch
):
1122 if branch
== "main":
1123 return self
.refPrefix
+ "master"
1125 if len(branch
) <= 0:
1128 return self
.refPrefix
+ self
.projectName
+ branch
1130 def gitCommitByP4Change(self
, ref
, change
):
1132 print "looking in ref " + ref
+ " for change %s using bisect..." % change
1135 latestCommit
= parseRevision(ref
)
1139 print "trying: earliest %s latest %s" % (earliestCommit
, latestCommit
)
1140 next
= read_pipe("git rev-list --bisect %s %s" % (latestCommit
, earliestCommit
)).strip()
1145 log
= extractLogMessageFromGitCommit(next
)
1146 settings
= extractSettingsGitLog(log
)
1147 currentChange
= int(settings
['change'])
1149 print "current change %s" % currentChange
1151 if currentChange
== change
:
1153 print "found %s" % next
1156 if currentChange
< change
:
1157 earliestCommit
= "^%s" % next
1159 latestCommit
= "%s" % next
1163 def importNewBranch(self
, branch
, maxChange
):
1164 # make fast-import flush all changes to disk and update the refs using the checkpoint
1165 # command so that we can try to find the branch parent in the git history
1166 self
.gitStream
.write("checkpoint\n\n");
1167 self
.gitStream
.flush();
1168 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1169 range = "@1,%s" % maxChange
1170 #print "prefix" + branchPrefix
1171 changes
= p4ChangesForPaths([branchPrefix
], range)
1172 if len(changes
) <= 0:
1174 firstChange
= changes
[0]
1175 #print "first change in branch: %s" % firstChange
1176 sourceBranch
= self
.knownBranches
[branch
]
1177 sourceDepotPath
= self
.depotPaths
[0] + sourceBranch
1178 sourceRef
= self
.gitRefForBranch(sourceBranch
)
1179 #print "source " + sourceBranch
1181 branchParentChange
= int(p4Cmd("changes -m 1 %s...@1,%s" % (sourceDepotPath
, firstChange
))["change"])
1182 #print "branch parent: %s" % branchParentChange
1183 gitParent
= self
.gitCommitByP4Change(sourceRef
, branchParentChange
)
1184 if len(gitParent
) > 0:
1185 self
.initialParents
[self
.gitRefForBranch(branch
)] = gitParent
1186 #print "parent git commit: %s" % gitParent
1188 self
.importChanges(changes
)
1191 def importChanges(self
, changes
):
1193 for change
in changes
:
1194 description
= p4Cmd("describe %s" % change
)
1195 self
.updateOptionDict(description
)
1198 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1203 if self
.detectBranches
:
1204 branches
= self
.splitFilesIntoBranches(description
)
1205 for branch
in branches
.keys():
1207 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1211 filesForCommit
= branches
[branch
]
1214 print "branch is %s" % branch
1216 self
.updatedBranches
.add(branch
)
1218 if branch
not in self
.createdBranches
:
1219 self
.createdBranches
.add(branch
)
1220 parent
= self
.knownBranches
[branch
]
1221 if parent
== branch
:
1224 fullBranch
= self
.projectName
+ branch
1225 if fullBranch
not in self
.p4BranchesInGit
:
1227 print("\n Importing new branch %s" % fullBranch
);
1228 if self
.importNewBranch(branch
, change
- 1):
1230 self
.p4BranchesInGit
.append(fullBranch
)
1232 print("\n Resuming with change %s" % change
);
1235 print "parent determined through known branches: %s" % parent
1237 branch
= self
.gitRefForBranch(branch
)
1238 parent
= self
.gitRefForBranch(parent
)
1241 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1243 if len(parent
) == 0 and branch
in self
.initialParents
:
1244 parent
= self
.initialParents
[branch
]
1245 del self
.initialParents
[branch
]
1247 self
.commit(description
, filesForCommit
, branch
, [branchPrefix
], parent
)
1249 files
= self
.extractFilesFromCommit(description
)
1250 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1252 self
.initialParent
= ""
1254 print self
.gitError
.read()
1257 def importHeadRevision(self
, revision
):
1258 print "Doing initial import of %s from revision %s into %s" % (' '.join(self
.depotPaths
), revision
, self
.branch
)
1260 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1261 details
["desc"] = ("Initial import of %s from the state at revision %s"
1262 % (' '.join(self
.depotPaths
), revision
))
1263 details
["change"] = revision
1267 for info
in p4CmdList("files "
1268 + ' '.join(["%s...%s"
1270 for p
in self
.depotPaths
])):
1272 if info
['code'] == 'error':
1273 sys
.stderr
.write("p4 returned an error: %s\n"
1278 change
= int(info
["change"])
1279 if change
> newestRevision
:
1280 newestRevision
= change
1282 if info
["action"] == "delete":
1283 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1284 #fileCnt = fileCnt + 1
1287 for prop
in ["depotFile", "rev", "action", "type" ]:
1288 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1290 fileCnt
= fileCnt
+ 1
1292 details
["change"] = newestRevision
1293 self
.updateOptionDict(details
)
1295 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1297 print "IO error with git fast-import. Is your git version recent enough?"
1298 print self
.gitError
.read()
1301 def run(self
, args
):
1302 self
.depotPaths
= []
1303 self
.changeRange
= ""
1304 self
.initialParent
= ""
1305 self
.previousDepotPaths
= []
1307 # map from branch depot path to parent branch
1308 self
.knownBranches
= {}
1309 self
.initialParents
= {}
1310 self
.hasOrigin
= originP4BranchesExist()
1311 if not self
.syncWithOrigin
:
1312 self
.hasOrigin
= False
1314 if self
.importIntoRemotes
:
1315 self
.refPrefix
= "refs/remotes/p4/"
1317 self
.refPrefix
= "refs/heads/p4/"
1319 if self
.syncWithOrigin
and self
.hasOrigin
:
1321 print "Syncing with origin first by calling git fetch origin"
1322 system("git fetch origin")
1324 if len(self
.branch
) == 0:
1325 self
.branch
= self
.refPrefix
+ "master"
1326 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1327 system("git update-ref %s refs/heads/p4" % self
.branch
)
1328 system("git branch -D p4");
1329 # create it /after/ importing, when master exists
1330 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
and gitBranchExists(self
.branch
):
1331 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1333 # TODO: should always look at previous commits,
1334 # merge with previous imports, if possible.
1337 createOrUpdateBranchesFromOrigin(self
.refPrefix
, self
.silent
)
1338 self
.listExistingP4GitBranches()
1340 if len(self
.p4BranchesInGit
) > 1:
1342 print "Importing from/into multiple branches"
1343 self
.detectBranches
= True
1346 print "branches: %s" % self
.p4BranchesInGit
1349 for branch
in self
.p4BranchesInGit
:
1350 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1352 settings
= extractSettingsGitLog(logMsg
)
1354 self
.readOptions(settings
)
1355 if (settings
.has_key('depot-paths')
1356 and settings
.has_key ('change')):
1357 change
= int(settings
['change']) + 1
1358 p4Change
= max(p4Change
, change
)
1360 depotPaths
= sorted(settings
['depot-paths'])
1361 if self
.previousDepotPaths
== []:
1362 self
.previousDepotPaths
= depotPaths
1365 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1366 for i
in range(0, min(len(cur
), len(prev
))):
1367 if cur
[i
] <> prev
[i
]:
1371 paths
.append (cur
[:i
+ 1])
1373 self
.previousDepotPaths
= paths
1376 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1377 self
.changeRange
= "@%s,#head" % p4Change
1378 if not self
.detectBranches
:
1379 self
.initialParent
= parseRevision(self
.branch
)
1380 if not self
.silent
and not self
.detectBranches
:
1381 print "Performing incremental import into %s git branch" % self
.branch
1383 if not self
.branch
.startswith("refs/"):
1384 self
.branch
= "refs/heads/" + self
.branch
1386 if len(args
) == 0 and self
.depotPaths
:
1388 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1390 if self
.depotPaths
and self
.depotPaths
!= args
:
1391 print ("previous import used depot path %s and now %s was specified. "
1392 "This doesn't work!" % (' '.join (self
.depotPaths
),
1396 self
.depotPaths
= sorted(args
)
1402 for p
in self
.depotPaths
:
1403 if p
.find("@") != -1:
1404 atIdx
= p
.index("@")
1405 self
.changeRange
= p
[atIdx
:]
1406 if self
.changeRange
== "@all":
1407 self
.changeRange
= ""
1408 elif ',' not in self
.changeRange
:
1409 revision
= self
.changeRange
1410 self
.changeRange
= ""
1412 elif p
.find("#") != -1:
1413 hashIdx
= p
.index("#")
1414 revision
= p
[hashIdx
:]
1416 elif self
.previousDepotPaths
== []:
1419 p
= re
.sub ("\.\.\.$", "", p
)
1420 if not p
.endswith("/"):
1425 self
.depotPaths
= newPaths
1428 self
.loadUserMapFromCache()
1430 if self
.detectLabels
:
1433 if self
.detectBranches
:
1434 ## FIXME - what's a P4 projectName ?
1435 self
.projectName
= self
.guessProjectName()
1437 if not self
.hasOrigin
:
1438 self
.getBranchMapping();
1440 print "p4-git branches: %s" % self
.p4BranchesInGit
1441 print "initial parents: %s" % self
.initialParents
1442 for b
in self
.p4BranchesInGit
:
1446 b
= b
[len(self
.projectName
):]
1447 self
.createdBranches
.add(b
)
1449 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1451 importProcess
= subprocess
.Popen(["git", "fast-import"],
1452 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1453 stderr
=subprocess
.PIPE
);
1454 self
.gitOutput
= importProcess
.stdout
1455 self
.gitStream
= importProcess
.stdin
1456 self
.gitError
= importProcess
.stderr
1459 self
.importHeadRevision(revision
)
1463 if len(self
.changesFile
) > 0:
1464 output
= open(self
.changesFile
).readlines()
1467 changeSet
.add(int(line
))
1469 for change
in changeSet
:
1470 changes
.append(change
)
1475 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1477 changes
= p4ChangesForPaths(self
.depotPaths
, self
.changeRange
)
1479 if len(self
.maxChanges
) > 0:
1480 changes
= changes
[:min(int(self
.maxChanges
), len(changes
))]
1482 if len(changes
) == 0:
1484 print "No changes to import!"
1487 if not self
.silent
and not self
.detectBranches
:
1488 print "Import destination: %s" % self
.branch
1490 self
.updatedBranches
= set()
1492 self
.importChanges(changes
)
1496 if len(self
.updatedBranches
) > 0:
1497 sys
.stdout
.write("Updated branches: ")
1498 for b
in self
.updatedBranches
:
1499 sys
.stdout
.write("%s " % b
)
1500 sys
.stdout
.write("\n")
1502 self
.gitStream
.close()
1503 if importProcess
.wait() != 0:
1504 die("fast-import failed: %s" % self
.gitError
.read())
1505 self
.gitOutput
.close()
1506 self
.gitError
.close()
1510 class P4Rebase(Command
):
1512 Command
.__init
__(self
)
1514 self
.description
= ("Fetches the latest revision from perforce and "
1515 + "rebases the current work (branch) against it")
1516 self
.verbose
= False
1518 def run(self
, args
):
1522 return self
.rebase()
1525 [upstream
, settings
] = findUpstreamBranchPoint()
1526 if len(upstream
) == 0:
1527 die("Cannot find upstream branchpoint for rebase")
1529 # the branchpoint may be p4/foo~3, so strip off the parent
1530 upstream
= re
.sub("~[0-9]+$", "", upstream
)
1532 print "Rebasing the current branch onto %s" % upstream
1533 oldHead
= read_pipe("git rev-parse HEAD").strip()
1534 system("git rebase %s" % upstream
)
1535 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1538 class P4Clone(P4Sync
):
1540 P4Sync
.__init
__(self
)
1541 self
.description
= "Creates a new git repository and imports from Perforce into it"
1542 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1543 self
.options
.append(
1544 optparse
.make_option("--destination", dest
="cloneDestination",
1545 action
='store', default
=None,
1546 help="where to leave result of the clone"))
1547 self
.cloneDestination
= None
1548 self
.needsGit
= False
1550 def defaultDestination(self
, args
):
1551 ## TODO: use common prefix of args?
1553 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1554 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1555 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1556 depotDir
= re
.sub(r
"/$", "", depotDir
)
1557 return os
.path
.split(depotDir
)[1]
1559 def run(self
, args
):
1563 if self
.keepRepoPath
and not self
.cloneDestination
:
1564 sys
.stderr
.write("Must specify destination for --keep-path\n")
1569 if not self
.cloneDestination
and len(depotPaths
) > 1:
1570 self
.cloneDestination
= depotPaths
[-1]
1571 depotPaths
= depotPaths
[:-1]
1573 for p
in depotPaths
:
1574 if not p
.startswith("//"):
1577 if not self
.cloneDestination
:
1578 self
.cloneDestination
= self
.defaultDestination(args
)
1580 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1581 if not os
.path
.exists(self
.cloneDestination
):
1582 os
.makedirs(self
.cloneDestination
)
1583 os
.chdir(self
.cloneDestination
)
1585 self
.gitdir
= os
.getcwd() + "/.git"
1586 if not P4Sync
.run(self
, depotPaths
):
1588 if self
.branch
!= "master":
1589 if gitBranchExists("refs/remotes/p4/master"):
1590 system("git branch master refs/remotes/p4/master")
1591 system("git checkout -f")
1593 print "Could not detect main branch. No checkout/master branch created."
1597 class P4Branches(Command
):
1599 Command
.__init
__(self
)
1601 self
.description
= ("Shows the git branches that hold imports and their "
1602 + "corresponding perforce depot paths")
1603 self
.verbose
= False
1605 def run(self
, args
):
1606 if originP4BranchesExist():
1607 createOrUpdateBranchesFromOrigin()
1609 cmdline
= "git rev-parse --symbolic "
1610 cmdline
+= " --remotes"
1612 for line
in read_pipe_lines(cmdline
):
1615 if not line
.startswith('p4/') or line
== "p4/HEAD":
1619 log
= extractLogMessageFromGitCommit("refs/remotes/%s" % branch
)
1620 settings
= extractSettingsGitLog(log
)
1622 print "%s <= %s (%s)" % (branch
, ",".join(settings
["depot-paths"]), settings
["change"])
1625 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1627 optparse
.IndentedHelpFormatter
.__init
__(self
)
1629 def format_description(self
, description
):
1631 return description
+ "\n"
1635 def printUsage(commands
):
1636 print "usage: %s <command> [options]" % sys
.argv
[0]
1638 print "valid commands: %s" % ", ".join(commands
)
1640 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1645 "submit" : P4Submit
,
1647 "rebase" : P4Rebase
,
1649 "rollback" : P4RollBack
,
1650 "branches" : P4Branches
1655 if len(sys
.argv
[1:]) == 0:
1656 printUsage(commands
.keys())
1660 cmdName
= sys
.argv
[1]
1662 klass
= commands
[cmdName
]
1665 print "unknown command %s" % cmdName
1667 printUsage(commands
.keys())
1670 options
= cmd
.options
1671 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1675 if len(options
) > 0:
1676 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1678 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1680 description
= cmd
.description
,
1681 formatter
= HelpFormatter())
1683 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1685 verbose
= cmd
.verbose
1687 if cmd
.gitdir
== None:
1688 cmd
.gitdir
= os
.path
.abspath(".git")
1689 if not isValidGitDir(cmd
.gitdir
):
1690 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1691 if os
.path
.exists(cmd
.gitdir
):
1692 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1696 if not isValidGitDir(cmd
.gitdir
):
1697 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1698 cmd
.gitdir
+= "/.git"
1700 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1702 os
.environ
["GIT_DIR"] = cmd
.gitdir
1704 if not cmd
.run(args
):
1708 if __name__
== '__main__':