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