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