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