Load the user map from p4 only once at run-time.
[git/git.git] / contrib / fast-import / git-p4
CommitLineData
86949eef
SH
1#!/usr/bin/env python
2#
3# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
4#
5# Author: Simon Hausmann <hausmann@kde.org>
83dce55a
SH
6# Copyright: 2007 Simon Hausmann <hausmann@kde.org>
7# 2007 Trolltech ASA
86949eef
SH
8# License: MIT <http://www.opensource.org/licenses/mit-license.php>
9#
5834684d 10# TODO: * Consider making --with-origin the default, assuming that the git
341dc1c1 11# protocol is always more efficient. (needs manual testing first :)
24f7b53f 12#
86949eef 13
08483580 14import optparse, sys, os, marshal, popen2, subprocess, shelve
25df95cc 15import tempfile, getopt, sha, os.path, time, platform
b984733c 16from sets import Set;
4f5cf76a
SH
17
18gitdir = os.environ.get("GIT_DIR", "")
86949eef 19
caace111
SH
20def mypopen(command):
21 return os.popen(command, "rb");
22
86949eef
SH
23def p4CmdList(cmd):
24 cmd = "p4 -G %s" % cmd
25 pipe = os.popen(cmd, "rb")
26
27 result = []
28 try:
29 while True:
30 entry = marshal.load(pipe)
31 result.append(entry)
32 except EOFError:
33 pass
a6d5da36
SH
34 exitCode = pipe.close()
35 if exitCode != None:
ac3e0d79
SH
36 entry = {}
37 entry["p4ExitCode"] = exitCode
38 result.append(entry)
86949eef
SH
39
40 return result
41
42def p4Cmd(cmd):
43 list = p4CmdList(cmd)
44 result = {}
45 for entry in list:
46 result.update(entry)
47 return result;
48
cb2c9db5
SH
49def p4Where(depotPath):
50 if not depotPath.endswith("/"):
51 depotPath += "/"
52 output = p4Cmd("where %s..." % depotPath)
dc524036
SH
53 if output["code"] == "error":
54 return ""
cb2c9db5
SH
55 clientPath = ""
56 if "path" in output:
57 clientPath = output.get("path")
58 elif "data" in output:
59 data = output.get("data")
60 lastSpace = data.rfind(" ")
61 clientPath = data[lastSpace + 1:]
62
63 if clientPath.endswith("..."):
64 clientPath = clientPath[:-3]
65 return clientPath
66
86949eef
SH
67def die(msg):
68 sys.stderr.write(msg + "\n")
69 sys.exit(1)
70
71def currentGitBranch():
caace111 72 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
86949eef 73
4f5cf76a
SH
74def isValidGitDir(path):
75 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
76 return True;
77 return False
78
463e8af6
SH
79def parseRevision(ref):
80 return mypopen("git rev-parse %s" % ref).read()[:-1]
81
4f5cf76a
SH
82def system(cmd):
83 if os.system(cmd) != 0:
84 die("command failed: %s" % cmd)
85
6ae8de88
SH
86def extractLogMessageFromGitCommit(commit):
87 logMessage = ""
88 foundTitle = False
caace111 89 for log in mypopen("git cat-file commit %s" % commit).readlines():
6ae8de88
SH
90 if not foundTitle:
91 if len(log) == 1:
1c094184 92 foundTitle = True
6ae8de88
SH
93 continue
94
95 logMessage += log
96 return logMessage
97
98def extractDepotPathAndChangeFromGitLog(log):
99 values = {}
100 for line in log.split("\n"):
101 line = line.strip()
102 if line.startswith("[git-p4:") and line.endswith("]"):
103 line = line[8:-1].strip()
104 for assignment in line.split(":"):
105 variable = assignment.strip()
106 value = ""
107 equalPos = assignment.find("=")
108 if equalPos != -1:
109 variable = assignment[:equalPos].strip()
110 value = assignment[equalPos + 1:].strip()
111 if value.startswith("\"") and value.endswith("\""):
112 value = value[1:-1]
113 values[variable] = value
114
115 return values.get("depot-path"), values.get("change")
116
8136a639 117def gitBranchExists(branch):
caace111
SH
118 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
119 return proc.wait() == 0;
8136a639 120
b984733c
SH
121class Command:
122 def __init__(self):
123 self.usage = "usage: %prog [options]"
8910ac0e 124 self.needsGit = True
b984733c
SH
125
126class P4Debug(Command):
86949eef 127 def __init__(self):
6ae8de88 128 Command.__init__(self)
86949eef
SH
129 self.options = [
130 ]
c8c39116 131 self.description = "A tool to debug the output of p4 -G."
8910ac0e 132 self.needsGit = False
86949eef
SH
133
134 def run(self, args):
135 for output in p4CmdList(" ".join(args)):
136 print output
b984733c 137 return True
86949eef 138
5834684d
SH
139class P4RollBack(Command):
140 def __init__(self):
141 Command.__init__(self)
142 self.options = [
0c66a783
SH
143 optparse.make_option("--verbose", dest="verbose", action="store_true"),
144 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
5834684d
SH
145 ]
146 self.description = "A tool to debug the multi-branch import. Don't use :)"
52102d47 147 self.verbose = False
0c66a783 148 self.rollbackLocalBranches = False
5834684d
SH
149
150 def run(self, args):
151 if len(args) != 1:
152 return False
153 maxChange = int(args[0])
0c66a783 154
ad192f28 155 if "p4ExitCode" in p4Cmd("changes -m 1"):
66a2f523
SH
156 die("Problems executing p4");
157
0c66a783
SH
158 if self.rollbackLocalBranches:
159 refPrefix = "refs/heads/"
160 lines = mypopen("git rev-parse --symbolic --branches").readlines()
161 else:
162 refPrefix = "refs/remotes/"
163 lines = mypopen("git rev-parse --symbolic --remotes").readlines()
164
165 for line in lines:
166 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
167 ref = refPrefix + line[:-1]
5834684d
SH
168 log = extractLogMessageFromGitCommit(ref)
169 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
170 changed = False
52102d47
SH
171
172 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
173 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
174 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
175 continue
176
5834684d
SH
177 while len(change) > 0 and int(change) > maxChange:
178 changed = True
52102d47
SH
179 if self.verbose:
180 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
5834684d
SH
181 system("git update-ref %s \"%s^\"" % (ref, ref))
182 log = extractLogMessageFromGitCommit(ref)
183 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
184
185 if changed:
52102d47 186 print "%s rewound to %s" % (ref, change)
5834684d
SH
187
188 return True
189
711544b0 190class P4Submit(Command):
4f5cf76a 191 def __init__(self):
b984733c 192 Command.__init__(self)
4f5cf76a
SH
193 self.options = [
194 optparse.make_option("--continue", action="store_false", dest="firstTime"),
195 optparse.make_option("--origin", dest="origin"),
196 optparse.make_option("--reset", action="store_true", dest="reset"),
4f5cf76a
SH
197 optparse.make_option("--log-substitutions", dest="substFile"),
198 optparse.make_option("--noninteractive", action="store_false"),
04219c04 199 optparse.make_option("--dry-run", action="store_true"),
c1b296b9 200 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
4f5cf76a
SH
201 ]
202 self.description = "Submit changes from git to the perforce depot."
c9b50e63 203 self.usage += " [name of git branch to submit into perforce depot]"
4f5cf76a
SH
204 self.firstTime = True
205 self.reset = False
206 self.interactive = True
207 self.dryRun = False
208 self.substFile = ""
209 self.firstTime = True
9512497b 210 self.origin = ""
c1b296b9 211 self.directSubmit = False
4f5cf76a
SH
212
213 self.logSubstitutions = {}
214 self.logSubstitutions["<enter description here>"] = "%log%"
215 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
216
217 def check(self):
218 if len(p4CmdList("opened ...")) > 0:
219 die("You have files opened with perforce! Close them before starting the sync.")
220
221 def start(self):
222 if len(self.config) > 0 and not self.reset:
c3c46244 223 die("Cannot start sync. Previous sync config found at %s\nIf you want to start submitting again from scratch maybe you want to call git-p4 submit --reset" % self.configFile)
4f5cf76a
SH
224
225 commits = []
c1b296b9
SH
226 if self.directSubmit:
227 commits.append("0")
228 else:
229 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
230 commits.append(line[:-1])
231 commits.reverse()
4f5cf76a
SH
232
233 self.config["commits"] = commits
234
4f5cf76a
SH
235 def prepareLogMessage(self, template, message):
236 result = ""
237
238 for line in template.split("\n"):
239 if line.startswith("#"):
240 result += line + "\n"
241 continue
242
243 substituted = False
244 for key in self.logSubstitutions.keys():
245 if line.find(key) != -1:
246 value = self.logSubstitutions[key]
247 value = value.replace("%log%", message)
248 if value != "@remove@":
249 result += line.replace(key, value) + "\n"
250 substituted = True
251 break
252
253 if not substituted:
254 result += line + "\n"
255
256 return result
257
258 def apply(self, id):
c1b296b9
SH
259 if self.directSubmit:
260 print "Applying local change in working directory/index"
261 diff = self.diffStatus
262 else:
263 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
264 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
4f5cf76a
SH
265 filesToAdd = set()
266 filesToDelete = set()
d336c158 267 editedFiles = set()
4f5cf76a
SH
268 for line in diff:
269 modifier = line[0]
270 path = line[1:].strip()
271 if modifier == "M":
d336c158
SH
272 system("p4 edit \"%s\"" % path)
273 editedFiles.add(path)
4f5cf76a
SH
274 elif modifier == "A":
275 filesToAdd.add(path)
276 if path in filesToDelete:
277 filesToDelete.remove(path)
278 elif modifier == "D":
279 filesToDelete.add(path)
280 if path in filesToAdd:
281 filesToAdd.remove(path)
282 else:
283 die("unknown modifier %s for %s" % (modifier, path))
284
c1b296b9
SH
285 if self.directSubmit:
286 diffcmd = "cat \"%s\"" % self.diffFile
287 else:
288 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
47a130b7 289 patchcmd = diffcmd + " | git apply "
c1b296b9
SH
290 tryPatchCmd = patchcmd + "--check -"
291 applyPatchCmd = patchcmd + "--check --apply -"
51a2640a 292
47a130b7 293 if os.system(tryPatchCmd) != 0:
51a2640a
SH
294 print "Unfortunately applying the change failed!"
295 print "What do you want to do?"
296 response = "x"
297 while response != "s" and response != "a" and response != "w":
298 response = raw_input("[s]kip this patch / [a]pply the patch forcibly and with .rej files / [w]rite the patch to a file (patch.txt) ")
299 if response == "s":
300 print "Skipping! Good luck with the next patches..."
301 return
302 elif response == "a":
47a130b7 303 os.system(applyPatchCmd)
51a2640a
SH
304 if len(filesToAdd) > 0:
305 print "You may also want to call p4 add on the following files:"
306 print " ".join(filesToAdd)
307 if len(filesToDelete):
308 print "The following files should be scheduled for deletion with p4 delete:"
309 print " ".join(filesToDelete)
310 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
311 elif response == "w":
312 system(diffcmd + " > patch.txt")
313 print "Patch saved to patch.txt in %s !" % self.clientPath
314 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
315
47a130b7 316 system(applyPatchCmd)
4f5cf76a
SH
317
318 for f in filesToAdd:
319 system("p4 add %s" % f)
320 for f in filesToDelete:
321 system("p4 revert %s" % f)
322 system("p4 delete %s" % f)
323
c1b296b9
SH
324 logMessage = ""
325 if not self.directSubmit:
326 logMessage = extractLogMessageFromGitCommit(id)
327 logMessage = logMessage.replace("\n", "\n\t")
328 logMessage = logMessage[:-1]
4f5cf76a 329
caace111 330 template = mypopen("p4 change -o").read()
4f5cf76a
SH
331
332 if self.interactive:
333 submitTemplate = self.prepareLogMessage(template, logMessage)
caace111 334 diff = mypopen("p4 diff -du ...").read()
4f5cf76a
SH
335
336 for newFile in filesToAdd:
337 diff += "==== new file ====\n"
338 diff += "--- /dev/null\n"
339 diff += "+++ %s\n" % newFile
340 f = open(newFile, "r")
341 for line in f.readlines():
342 diff += "+" + line
343 f.close()
344
25df95cc
SH
345 separatorLine = "######## everything below this line is just the diff #######"
346 if platform.system() == "Windows":
347 separatorLine += "\r"
348 separatorLine += "\n"
4f5cf76a
SH
349
350 response = "e"
53150250 351 firstIteration = True
4f5cf76a 352 while response == "e":
53150250 353 if not firstIteration:
d336c158 354 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
53150250 355 firstIteration = False
4f5cf76a
SH
356 if response == "e":
357 [handle, fileName] = tempfile.mkstemp()
358 tmpFile = os.fdopen(handle, "w+")
53150250 359 tmpFile.write(submitTemplate + separatorLine + diff)
4f5cf76a 360 tmpFile.close()
25df95cc
SH
361 defaultEditor = "vi"
362 if platform.system() == "Windows":
363 defaultEditor = "notepad"
364 editor = os.environ.get("EDITOR", defaultEditor);
4f5cf76a 365 system(editor + " " + fileName)
25df95cc 366 tmpFile = open(fileName, "rb")
53150250 367 message = tmpFile.read()
4f5cf76a
SH
368 tmpFile.close()
369 os.remove(fileName)
53150250 370 submitTemplate = message[:message.index(separatorLine)]
4f5cf76a
SH
371
372 if response == "y" or response == "yes":
373 if self.dryRun:
374 print submitTemplate
375 raw_input("Press return to continue...")
376 else:
7944f142
SH
377 if self.directSubmit:
378 print "Submitting to git first"
379 os.chdir(self.oldWorkingDirectory)
380 pipe = os.popen("git commit -a -F -", "wb")
381 pipe.write(submitTemplate)
382 pipe.close()
383 os.chdir(self.clientPath)
384
385 pipe = os.popen("p4 submit -i", "wb")
386 pipe.write(submitTemplate)
387 pipe.close()
d336c158
SH
388 elif response == "s":
389 for f in editedFiles:
390 system("p4 revert \"%s\"" % f);
391 for f in filesToAdd:
392 system("p4 revert \"%s\"" % f);
393 system("rm %s" %f)
394 for f in filesToDelete:
395 system("p4 delete \"%s\"" % f);
396 return
4f5cf76a
SH
397 else:
398 print "Not submitting!"
399 self.interactive = False
400 else:
401 fileName = "submit.txt"
402 file = open(fileName, "w+")
403 file.write(self.prepareLogMessage(template, logMessage))
404 file.close()
405 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
406
407 def run(self, args):
9512497b
SH
408 global gitdir
409 # make gitdir absolute so we can cd out into the perforce checkout
410 gitdir = os.path.abspath(gitdir)
411 os.environ["GIT_DIR"] = gitdir
c9b50e63
SH
412
413 if len(args) == 0:
414 self.master = currentGitBranch()
415 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
416 die("Detecting current git branch failed!")
417 elif len(args) == 1:
418 self.master = args[0]
419 else:
420 return False
421
9512497b
SH
422 depotPath = ""
423 if gitBranchExists("p4"):
424 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
425 if len(depotPath) == 0 and gitBranchExists("origin"):
426 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
427
428 if len(depotPath) == 0:
429 print "Internal error: cannot locate perforce depot path from existing branches"
430 sys.exit(128)
431
51a2640a 432 self.clientPath = p4Where(depotPath)
9512497b 433
51a2640a 434 if len(self.clientPath) == 0:
9512497b
SH
435 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
436 sys.exit(128)
437
51a2640a 438 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
7944f142 439 self.oldWorkingDirectory = os.getcwd()
c1b296b9
SH
440
441 if self.directSubmit:
442 self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
cbf5efa6
SH
443 if len(self.diffStatus) == 0:
444 print "No changes in working directory to submit."
445 return True
c1b296b9
SH
446 patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
447 self.diffFile = gitdir + "/p4-git-diff"
448 f = open(self.diffFile, "wb")
449 f.write(patch)
450 f.close();
451
51a2640a
SH
452 os.chdir(self.clientPath)
453 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
9512497b
SH
454 if response == "y" or response == "yes":
455 system("p4 sync ...")
456
457 if len(self.origin) == 0:
458 if gitBranchExists("p4"):
459 self.origin = "p4"
460 else:
461 self.origin = "origin"
462
4f5cf76a
SH
463 if self.reset:
464 self.firstTime = True
465
466 if len(self.substFile) > 0:
467 for line in open(self.substFile, "r").readlines():
468 tokens = line[:-1].split("=")
469 self.logSubstitutions[tokens[0]] = tokens[1]
470
4f5cf76a
SH
471 self.check()
472 self.configFile = gitdir + "/p4-git-sync.cfg"
473 self.config = shelve.open(self.configFile, writeback=True)
474
475 if self.firstTime:
476 self.start()
477
478 commits = self.config.get("commits", [])
479
480 while len(commits) > 0:
481 self.firstTime = False
482 commit = commits[0]
483 commits = commits[1:]
484 self.config["commits"] = commits
485 self.apply(commit)
486 if not self.interactive:
487 break
488
489 self.config.close()
490
c1b296b9
SH
491 if self.directSubmit:
492 os.remove(self.diffFile)
493
4f5cf76a
SH
494 if len(commits) == 0:
495 if self.firstTime:
496 print "No changes found to apply between %s and current HEAD" % self.origin
497 else:
498 print "All changes applied!"
7944f142
SH
499 os.chdir(self.oldWorkingDirectory)
500 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
80b5910f 501 if response == "y" or response == "yes":
80b5910f
SH
502 rebase = P4Rebase()
503 rebase.run([])
4f5cf76a
SH
504 os.remove(self.configFile)
505
b984733c
SH
506 return True
507
711544b0 508class P4Sync(Command):
b984733c
SH
509 def __init__(self):
510 Command.__init__(self)
511 self.options = [
512 optparse.make_option("--branch", dest="branch"),
513 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
514 optparse.make_option("--changesfile", dest="changesFile"),
515 optparse.make_option("--silent", dest="silent", action="store_true"),
ef48f909 516 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
4b97ffb1 517 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
a028a98e 518 optparse.make_option("--verbose", dest="verbose", action="store_true"),
01a9c9c5
SH
519 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
520 optparse.make_option("--max-changes", dest="maxChanges")
b984733c
SH
521 ]
522 self.description = """Imports from Perforce into a git repository.\n
523 example:
524 //depot/my/project/ -- to import the current head
525 //depot/my/project/@all -- to import everything
526 //depot/my/project/@1,6 -- to import only from revision 1 to 6
527
528 (a ... is not needed in the path p4 specification, it's added implicitly)"""
529
530 self.usage += " //depot/path[@revRange]"
531
b984733c 532 self.silent = False
b984733c
SH
533 self.createdBranches = Set()
534 self.committedChanges = Set()
569d1bd4 535 self.branch = ""
b984733c 536 self.detectBranches = False
cb53e1f8 537 self.detectLabels = False
b984733c 538 self.changesFile = ""
ef48f909 539 self.syncWithOrigin = False
4b97ffb1 540 self.verbose = False
a028a98e 541 self.importIntoRemotes = True
01a9c9c5 542 self.maxChanges = ""
b984733c
SH
543
544 def p4File(self, depotPath):
545 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
546
547 def extractFilesFromCommit(self, commit):
548 files = []
549 fnum = 0
550 while commit.has_key("depotFile%s" % fnum):
551 path = commit["depotFile%s" % fnum]
8f872531 552 if not path.startswith(self.depotPath):
b984733c 553 # if not self.silent:
8f872531 554 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
b984733c
SH
555 fnum = fnum + 1
556 continue
557
558 file = {}
559 file["path"] = path
560 file["rev"] = commit["rev%s" % fnum]
561 file["action"] = commit["action%s" % fnum]
562 file["type"] = commit["type%s" % fnum]
563 files.append(file)
564 fnum = fnum + 1
565 return files
566
71b112d4 567 def splitFilesIntoBranches(self, commit):
d5904674 568 branches = {}
b984733c 569
71b112d4
SH
570 fnum = 0
571 while commit.has_key("depotFile%s" % fnum):
572 path = commit["depotFile%s" % fnum]
573 if not path.startswith(self.depotPath):
574 # if not self.silent:
575 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
576 fnum = fnum + 1
577 continue
578
579 file = {}
580 file["path"] = path
581 file["rev"] = commit["rev%s" % fnum]
582 file["action"] = commit["action%s" % fnum]
583 file["type"] = commit["type%s" % fnum]
584 fnum = fnum + 1
585
586 relPath = path[len(self.depotPath):]
b984733c 587
4b97ffb1 588 for branch in self.knownBranches.keys():
af8da89c 589 if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
d5904674
SH
590 if branch not in branches:
591 branches[branch] = []
71b112d4 592 branches[branch].append(file)
b984733c
SH
593
594 return branches
595
4b97ffb1 596 def commit(self, details, files, branch, branchPrefix, parent = ""):
b984733c
SH
597 epoch = details["time"]
598 author = details["user"]
599
4b97ffb1
SH
600 if self.verbose:
601 print "commit into %s" % branch
602
b984733c
SH
603 self.gitStream.write("commit %s\n" % branch)
604 # gitStream.write("mark :%s\n" % details["change"])
605 self.committedChanges.add(int(details["change"]))
606 committer = ""
b607e71e
SH
607 if author not in self.users:
608 self.getUserMapFromPerforceServer()
b984733c 609 if author in self.users:
0828ab14 610 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
b984733c 611 else:
0828ab14 612 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
b984733c
SH
613
614 self.gitStream.write("committer %s\n" % committer)
615
616 self.gitStream.write("data <<EOT\n")
617 self.gitStream.write(details["desc"])
6ae8de88 618 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
b984733c
SH
619 self.gitStream.write("EOT\n\n")
620
621 if len(parent) > 0:
4b97ffb1
SH
622 if self.verbose:
623 print "parent %s" % parent
b984733c
SH
624 self.gitStream.write("from %s\n" % parent)
625
b984733c
SH
626 for file in files:
627 path = file["path"]
628 if not path.startswith(branchPrefix):
629 # if not silent:
630 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
631 continue
632 rev = file["rev"]
633 depotPath = path + "#" + rev
634 relPath = path[len(branchPrefix):]
635 action = file["action"]
636
637 if file["type"] == "apple":
638 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
639 continue
640
641 if action == "delete":
642 self.gitStream.write("D %s\n" % relPath)
643 else:
644 mode = 644
645 if file["type"].startswith("x"):
646 mode = 755
647
648 data = self.p4File(depotPath)
649
650 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
651 self.gitStream.write("data %s\n" % len(data))
652 self.gitStream.write(data)
653 self.gitStream.write("\n")
654
655 self.gitStream.write("\n")
656
1f4ba1cb
SH
657 change = int(details["change"])
658
9bda3a85 659 if self.labels.has_key(change):
1f4ba1cb
SH
660 label = self.labels[change]
661 labelDetails = label[0]
662 labelRevisions = label[1]
71b112d4
SH
663 if self.verbose:
664 print "Change %s is labelled %s" % (change, labelDetails)
1f4ba1cb
SH
665
666 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
667
668 if len(files) == len(labelRevisions):
669
670 cleanedFiles = {}
671 for info in files:
672 if info["action"] == "delete":
673 continue
674 cleanedFiles[info["depotFile"]] = info["rev"]
675
676 if cleanedFiles == labelRevisions:
677 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
678 self.gitStream.write("from %s\n" % branch)
679
680 owner = labelDetails["Owner"]
681 tagger = ""
682 if author in self.users:
683 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
684 else:
685 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
686 self.gitStream.write("tagger %s\n" % tagger)
687 self.gitStream.write("data <<EOT\n")
688 self.gitStream.write(labelDetails["Description"])
689 self.gitStream.write("EOT\n\n")
690
691 else:
a46668fa 692 if not self.silent:
1f4ba1cb
SH
693 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
694
695 else:
a46668fa 696 if not self.silent:
1f4ba1cb 697 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
b984733c 698
b607e71e 699 def getUserMapFromPerforceServer(self):
ebd81168
SH
700 if self.userMapFromPerforceServer:
701 return
b984733c
SH
702 self.users = {}
703
704 for output in p4CmdList("users"):
705 if not output.has_key("User"):
706 continue
707 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
708
b607e71e
SH
709 cache = open(gitdir + "/p4-usercache.txt", "wb")
710 for user in self.users.keys():
711 cache.write("%s\t%s\n" % (user, self.users[user]))
712 cache.close();
ebd81168 713 self.userMapFromPerforceServer = True
b607e71e
SH
714
715 def loadUserMapFromCache(self):
716 self.users = {}
ebd81168 717 self.userMapFromPerforceServer = False
b607e71e
SH
718 try:
719 cache = open(gitdir + "/p4-usercache.txt", "rb")
720 lines = cache.readlines()
721 cache.close()
722 for line in lines:
723 entry = line[:-1].split("\t")
724 self.users[entry[0]] = entry[1]
725 except IOError:
726 self.getUserMapFromPerforceServer()
727
1f4ba1cb
SH
728 def getLabels(self):
729 self.labels = {}
730
8f872531 731 l = p4CmdList("labels %s..." % self.depotPath)
10c3211b 732 if len(l) > 0 and not self.silent:
8f872531 733 print "Finding files belonging to labels in %s" % self.depotPath
01ce1fe9
SH
734
735 for output in l:
1f4ba1cb
SH
736 label = output["label"]
737 revisions = {}
738 newestChange = 0
71b112d4
SH
739 if self.verbose:
740 print "Querying files for label %s" % label
741 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
1f4ba1cb
SH
742 revisions[file["depotFile"]] = file["rev"]
743 change = int(file["change"])
744 if change > newestChange:
745 newestChange = change
746
9bda3a85
SH
747 self.labels[newestChange] = [output, revisions]
748
749 if self.verbose:
750 print "Label changes: %s" % self.labels.keys()
1f4ba1cb 751
4b97ffb1 752 def getBranchMapping(self):
29bdbac1 753 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
4b97ffb1
SH
754
755 for info in p4CmdList("branches"):
756 details = p4Cmd("branch -o %s" % info["branch"])
757 viewIdx = 0
758 while details.has_key("View%s" % viewIdx):
759 paths = details["View%s" % viewIdx].split(" ")
760 viewIdx = viewIdx + 1
761 # require standard //depot/foo/... //depot/bar/... mapping
762 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
763 continue
764 source = paths[0]
765 destination = paths[1]
766 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
767 source = source[len(self.depotPath):-4]
768 destination = destination[len(self.depotPath):-4]
29bdbac1
SH
769 if destination not in self.knownBranches:
770 self.knownBranches[destination] = source
771 if source not in self.knownBranches:
772 self.knownBranches[source] = source
773
774 def listExistingP4GitBranches(self):
775 self.p4BranchesInGit = []
776
a028a98e
SH
777 cmdline = "git rev-parse --symbolic "
778 if self.importIntoRemotes:
779 cmdline += " --remotes"
780 else:
781 cmdline += " --branches"
782
783 for line in mypopen(cmdline).readlines():
57284050
SH
784 if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
785 continue
786 if self.importIntoRemotes:
787 # strip off p4
29bdbac1 788 branch = line[3:-1]
57284050
SH
789 else:
790 branch = line[:-1]
791 self.p4BranchesInGit.append(branch)
792 self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
4b97ffb1 793
b984733c 794 def run(self, args):
8f872531 795 self.depotPath = ""
179caebf
SH
796 self.changeRange = ""
797 self.initialParent = ""
cd6cc0d3 798 self.previousDepotPath = ""
29bdbac1
SH
799 # map from branch depot path to parent branch
800 self.knownBranches = {}
801 self.initialParents = {}
802
a028a98e
SH
803 if self.importIntoRemotes:
804 self.refPrefix = "refs/remotes/p4/"
805 else:
57284050 806 self.refPrefix = "refs/heads/"
a028a98e 807
faf1bd20
SH
808 createP4HeadRef = False;
809
57284050 810 if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists(self.refPrefix + "master") and not self.detectBranches and self.importIntoRemotes:
29bdbac1 811 ### needs to be ported to multi branch import
179caebf 812
ef48f909
SH
813 print "Syncing with origin first as requested by calling git fetch origin"
814 system("git fetch origin")
815 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
816 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
817 if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
818 if originPreviousDepotPath == p4PreviousDepotPath:
819 originP4Change = int(originP4Change)
820 p4Change = int(p4Change)
821 if originP4Change > p4Change:
822 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
a028a98e 823 system("git update-ref " + self.refPrefix + "master origin");
ef48f909
SH
824 else:
825 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
826
569d1bd4 827 if len(self.branch) == 0:
a028a98e
SH
828 self.branch = self.refPrefix + "master"
829 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
48df6fd8 830 system("git update-ref %s refs/heads/p4" % self.branch)
48df6fd8 831 system("git branch -D p4");
faf1bd20 832 # create it /after/ importing, when master exists
a028a98e 833 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
faf1bd20 834 createP4HeadRef = True
967f72e2 835
33be3e65
SH
836 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
837 self.listExistingP4GitBranches()
b3fd1b28
SH
838 if len(self.p4BranchesInGit) > 1:
839 if not self.silent:
840 print "Importing from/into multiple branches"
33be3e65
SH
841 self.detectBranches = True
842
967f72e2 843 if len(args) == 0:
29bdbac1
SH
844 if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
845 ### needs to be ported to multi branch import
967f72e2
SH
846 if not self.silent:
847 print "Creating %s branch in git repository based on origin" % self.branch
8ead4fda
SH
848 branch = self.branch
849 if not branch.startswith("refs"):
850 branch = "refs/heads/" + branch
851 system("git update-ref %s origin" % branch)
967f72e2 852
29bdbac1
SH
853 if self.verbose:
854 print "branches: %s" % self.p4BranchesInGit
855
856 p4Change = 0
857 for branch in self.p4BranchesInGit:
a028a98e 858 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.refPrefix + branch))
29bdbac1
SH
859
860 if self.verbose:
861 print "path %s change %s" % (depotPath, change)
862
863 if len(depotPath) > 0 and len(change) > 0:
864 change = int(change) + 1
865 p4Change = max(p4Change, change)
866
867 if len(self.previousDepotPath) == 0:
868 self.previousDepotPath = depotPath
869 else:
870 i = 0
871 l = min(len(self.previousDepotPath), len(depotPath))
872 while i < l and self.previousDepotPath[i] == depotPath[i]:
873 i = i + 1
874 self.previousDepotPath = self.previousDepotPath[:i]
875
876 if p4Change > 0:
8f872531 877 self.depotPath = self.previousDepotPath
d5904674 878 self.changeRange = "@%s,#head" % p4Change
463e8af6 879 self.initialParent = parseRevision(self.branch)
341dc1c1 880 if not self.silent and not self.detectBranches:
967f72e2 881 print "Performing incremental import into %s git branch" % self.branch
569d1bd4 882
f9162f6a
SH
883 if not self.branch.startswith("refs/"):
884 self.branch = "refs/heads/" + self.branch
179caebf 885
8f872531
SH
886 if len(self.depotPath) != 0:
887 self.depotPath = self.depotPath[:-1]
b984733c 888
8f872531 889 if len(args) == 0 and len(self.depotPath) != 0:
b984733c 890 if not self.silent:
8f872531 891 print "Depot path: %s" % self.depotPath
b984733c
SH
892 elif len(args) != 1:
893 return False
894 else:
8f872531
SH
895 if len(self.depotPath) != 0 and self.depotPath != args[0]:
896 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
b984733c 897 sys.exit(1)
8f872531 898 self.depotPath = args[0]
b984733c 899
b984733c
SH
900 self.revision = ""
901 self.users = {}
b984733c 902
8f872531
SH
903 if self.depotPath.find("@") != -1:
904 atIdx = self.depotPath.index("@")
905 self.changeRange = self.depotPath[atIdx:]
b984733c
SH
906 if self.changeRange == "@all":
907 self.changeRange = ""
908 elif self.changeRange.find(",") == -1:
909 self.revision = self.changeRange
910 self.changeRange = ""
8f872531
SH
911 self.depotPath = self.depotPath[0:atIdx]
912 elif self.depotPath.find("#") != -1:
913 hashIdx = self.depotPath.index("#")
914 self.revision = self.depotPath[hashIdx:]
915 self.depotPath = self.depotPath[0:hashIdx]
b984733c
SH
916 elif len(self.previousDepotPath) == 0:
917 self.revision = "#head"
918
8f872531
SH
919 if self.depotPath.endswith("..."):
920 self.depotPath = self.depotPath[:-3]
b984733c 921
8f872531
SH
922 if not self.depotPath.endswith("/"):
923 self.depotPath += "/"
b984733c 924
b607e71e 925 self.loadUserMapFromCache()
cb53e1f8
SH
926 self.labels = {}
927 if self.detectLabels:
928 self.getLabels();
b984733c 929
4b97ffb1
SH
930 if self.detectBranches:
931 self.getBranchMapping();
29bdbac1
SH
932 if self.verbose:
933 print "p4-git branches: %s" % self.p4BranchesInGit
934 print "initial parents: %s" % self.initialParents
935 for b in self.p4BranchesInGit:
936 if b != "master":
937 b = b[len(self.projectName):]
938 self.createdBranches.add(b)
4b97ffb1 939
f291b4e3 940 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
b984733c 941
08483580
SH
942 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
943 self.gitOutput = importProcess.stdout
944 self.gitStream = importProcess.stdin
945 self.gitError = importProcess.stderr
b984733c
SH
946
947 if len(self.revision) > 0:
8f872531 948 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
b984733c
SH
949
950 details = { "user" : "git perforce import user", "time" : int(time.time()) }
8f872531 951 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
b984733c
SH
952 details["change"] = self.revision
953 newestRevision = 0
954
955 fileCnt = 0
8f872531 956 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
b984733c
SH
957 change = int(info["change"])
958 if change > newestRevision:
959 newestRevision = change
960
961 if info["action"] == "delete":
c45b1cfe
SH
962 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
963 #fileCnt = fileCnt + 1
b984733c
SH
964 continue
965
966 for prop in [ "depotFile", "rev", "action", "type" ]:
967 details["%s%s" % (prop, fileCnt)] = info[prop]
968
969 fileCnt = fileCnt + 1
970
971 details["change"] = newestRevision
972
973 try:
8f872531 974 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
c715706b 975 except IOError:
fd4ca86a 976 print "IO error with git fast-import. Is your git version recent enough?"
b984733c
SH
977 print self.gitError.read()
978
979 else:
980 changes = []
981
0828ab14 982 if len(self.changesFile) > 0:
b984733c
SH
983 output = open(self.changesFile).readlines()
984 changeSet = Set()
985 for line in output:
986 changeSet.add(int(line))
987
988 for change in changeSet:
989 changes.append(change)
990
991 changes.sort()
992 else:
29bdbac1
SH
993 if self.verbose:
994 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
caace111 995 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
b984733c
SH
996
997 for line in output:
998 changeNum = line.split(" ")[1]
999 changes.append(changeNum)
1000
1001 changes.reverse()
1002
01a9c9c5
SH
1003 if len(self.maxChanges) > 0:
1004 changes = changes[0:min(int(self.maxChanges), len(changes))]
1005
b984733c 1006 if len(changes) == 0:
0828ab14 1007 if not self.silent:
341dc1c1 1008 print "No changes to import!"
1f52af6c 1009 return True
b984733c 1010
341dc1c1
SH
1011 self.updatedBranches = set()
1012
b984733c
SH
1013 cnt = 1
1014 for change in changes:
1015 description = p4Cmd("describe %s" % change)
1016
0828ab14 1017 if not self.silent:
341dc1c1 1018 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
b984733c
SH
1019 sys.stdout.flush()
1020 cnt = cnt + 1
1021
1022 try:
b984733c 1023 if self.detectBranches:
71b112d4 1024 branches = self.splitFilesIntoBranches(description)
d5904674 1025 for branch in branches.keys():
8f872531 1026 branchPrefix = self.depotPath + branch + "/"
b984733c 1027
b984733c 1028 parent = ""
4b97ffb1 1029
d5904674 1030 filesForCommit = branches[branch]
4b97ffb1 1031
29bdbac1
SH
1032 if self.verbose:
1033 print "branch is %s" % branch
1034
341dc1c1
SH
1035 self.updatedBranches.add(branch)
1036
8f9b2e08 1037 if branch not in self.createdBranches:
b984733c 1038 self.createdBranches.add(branch)
4b97ffb1 1039 parent = self.knownBranches[branch]
b984733c
SH
1040 if parent == branch:
1041 parent = ""
29bdbac1
SH
1042 elif self.verbose:
1043 print "parent determined through known branches: %s" % parent
b984733c 1044
8f9b2e08
SH
1045 # main branch? use master
1046 if branch == "main":
1047 branch = "master"
1048 else:
29bdbac1 1049 branch = self.projectName + branch
8f9b2e08
SH
1050
1051 if parent == "main":
1052 parent = "master"
1053 elif len(parent) > 0:
29bdbac1 1054 parent = self.projectName + parent
8f9b2e08 1055
a028a98e 1056 branch = self.refPrefix + branch
b984733c 1057 if len(parent) > 0:
a028a98e 1058 parent = self.refPrefix + parent
29bdbac1
SH
1059
1060 if self.verbose:
1061 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1062
1063 if len(parent) == 0 and branch in self.initialParents:
1064 parent = self.initialParents[branch]
1065 del self.initialParents[branch]
1066
71b112d4 1067 self.commit(description, filesForCommit, branch, branchPrefix, parent)
b984733c 1068 else:
71b112d4 1069 files = self.extractFilesFromCommit(description)
8f872531 1070 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
b984733c
SH
1071 self.initialParent = ""
1072 except IOError:
1073 print self.gitError.read()
1074 sys.exit(1)
1075
341dc1c1
SH
1076 if not self.silent:
1077 print ""
1078 if len(self.updatedBranches) > 0:
1079 sys.stdout.write("Updated branches: ")
1080 for b in self.updatedBranches:
1081 sys.stdout.write("%s " % b)
1082 sys.stdout.write("\n")
b984733c 1083
b984733c
SH
1084
1085 self.gitStream.close()
29bdbac1
SH
1086 if importProcess.wait() != 0:
1087 die("fast-import failed: %s" % self.gitError.read())
b984733c
SH
1088 self.gitOutput.close()
1089 self.gitError.close()
1090
faf1bd20 1091 if createP4HeadRef:
65d2ade9 1092 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
faf1bd20 1093
b984733c
SH
1094 return True
1095
01ce1fe9
SH
1096class P4Rebase(Command):
1097 def __init__(self):
1098 Command.__init__(self)
ef48f909 1099 self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
01ce1fe9 1100 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
ef48f909 1101 self.syncWithOrigin = False
01ce1fe9
SH
1102
1103 def run(self, args):
1104 sync = P4Sync()
ef48f909 1105 sync.syncWithOrigin = self.syncWithOrigin
01ce1fe9
SH
1106 sync.run([])
1107 print "Rebasing the current branch"
caace111 1108 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
01ce1fe9 1109 system("git rebase p4")
1f52af6c 1110 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
01ce1fe9
SH
1111 return True
1112
f9a3a4f7
SH
1113class P4Clone(P4Sync):
1114 def __init__(self):
1115 P4Sync.__init__(self)
1116 self.description = "Creates a new git repository and imports from Perforce into it"
1117 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1118 self.needsGit = False
f9a3a4f7
SH
1119
1120 def run(self, args):
59fa4171
SH
1121 global gitdir
1122
f9a3a4f7
SH
1123 if len(args) < 1:
1124 return False
1125 depotPath = args[0]
1126 dir = ""
1127 if len(args) == 2:
1128 dir = args[1]
1129 elif len(args) > 2:
1130 return False
1131
1132 if not depotPath.startswith("//"):
1133 return False
1134
1135 if len(dir) == 0:
1136 dir = depotPath
1137 atPos = dir.rfind("@")
1138 if atPos != -1:
1139 dir = dir[0:atPos]
1140 hashPos = dir.rfind("#")
1141 if hashPos != -1:
1142 dir = dir[0:hashPos]
1143
1144 if dir.endswith("..."):
1145 dir = dir[:-3]
1146
1147 if dir.endswith("/"):
1148 dir = dir[:-1]
1149
1150 slashPos = dir.rfind("/")
1151 if slashPos != -1:
1152 dir = dir[slashPos + 1:]
1153
1154 print "Importing from %s into %s" % (depotPath, dir)
1155 os.makedirs(dir)
1156 os.chdir(dir)
1157 system("git init")
64ffb06a 1158 gitdir = os.getcwd() + "/.git"
f9a3a4f7
SH
1159 if not P4Sync.run(self, [depotPath]):
1160 return False
f9a3a4f7 1161 if self.branch != "master":
8f9b2e08
SH
1162 if gitBranchExists("refs/remotes/p4/master"):
1163 system("git branch master refs/remotes/p4/master")
1164 system("git checkout -f")
1165 else:
1166 print "Could not detect main branch. No checkout/master branch created."
f9a3a4f7
SH
1167 return True
1168
b984733c
SH
1169class HelpFormatter(optparse.IndentedHelpFormatter):
1170 def __init__(self):
1171 optparse.IndentedHelpFormatter.__init__(self)
1172
1173 def format_description(self, description):
1174 if description:
1175 return description + "\n"
1176 else:
1177 return ""
4f5cf76a 1178
86949eef
SH
1179def printUsage(commands):
1180 print "usage: %s <command> [options]" % sys.argv[0]
1181 print ""
1182 print "valid commands: %s" % ", ".join(commands)
1183 print ""
1184 print "Try %s <command> --help for command specific help." % sys.argv[0]
1185 print ""
1186
1187commands = {
1188 "debug" : P4Debug(),
711544b0 1189 "submit" : P4Submit(),
01ce1fe9 1190 "sync" : P4Sync(),
f9a3a4f7 1191 "rebase" : P4Rebase(),
5834684d
SH
1192 "clone" : P4Clone(),
1193 "rollback" : P4RollBack()
86949eef
SH
1194}
1195
1196if len(sys.argv[1:]) == 0:
1197 printUsage(commands.keys())
1198 sys.exit(2)
1199
1200cmd = ""
1201cmdName = sys.argv[1]
1202try:
1203 cmd = commands[cmdName]
1204except KeyError:
1205 print "unknown command %s" % cmdName
1206 print ""
1207 printUsage(commands.keys())
1208 sys.exit(2)
1209
4f5cf76a
SH
1210options = cmd.options
1211cmd.gitdir = gitdir
4f5cf76a 1212
e20a9e53 1213args = sys.argv[2:]
86949eef 1214
e20a9e53
SH
1215if len(options) > 0:
1216 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1217
1218 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1219 options,
1220 description = cmd.description,
1221 formatter = HelpFormatter())
1222
1223 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
86949eef 1224
8910ac0e
SH
1225if cmd.needsGit:
1226 gitdir = cmd.gitdir
1227 if len(gitdir) == 0:
1228 gitdir = ".git"
1229 if not isValidGitDir(gitdir):
81f2373f 1230 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
dc1a93b6 1231 if os.path.exists(gitdir):
5c4153e4
SH
1232 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1233 if len(cdup) > 0:
1234 os.chdir(cdup);
4f5cf76a 1235
8910ac0e
SH
1236 if not isValidGitDir(gitdir):
1237 if isValidGitDir(gitdir + "/.git"):
1238 gitdir += "/.git"
1239 else:
1240 die("fatal: cannot locate git repository at %s" % gitdir)
4f5cf76a 1241
8910ac0e 1242 os.environ["GIT_DIR"] = gitdir
4f5cf76a 1243
b984733c
SH
1244if not cmd.run(args):
1245 parser.print_help()
1246