1 # Copyright 2013 The Chromium Authors. All rights reserved. 2 # Use of this source code is governed by a BSD-style license that can be 3 # found in the LICENSE file. 4 5 """A module for the shell command.""" 6 7 import os 8 import tempfile 9 10 import cr 11 12 13 class ShellCommand(cr.Command): 14 """The implementation of the shell command. 15 16 The shell command is the escape hatch that lets user run any program in the 17 same environment that cr would use if it were running it. 18 """ 19 20 def __init__(self): 21 super(ShellCommand, self).__init__() 22 self.help = 'Launch a shell' 23 self.description = (""" 24 If no arguments are present, this launches an interactive system 25 shell (ie bash) with the environment modified to that used for the 26 build systems. 27 If any arguments are present, they are used as a command line to run 28 in that shell. 29 This allows you to run commands that are not yet available natively 30 in cr. 31 """) 32 33 def AddArguments(self, subparsers): 34 parser = super(ShellCommand, self).AddArguments(subparsers) 35 self.ConsumeArgs(parser, 'the shell') 36 return parser 37 38 def Run(self): 39 if cr.context.remains: 40 cr.Host.Shell(*cr.context.remains) 41 return 42 # If we get here, we are trying to launch an interactive shell 43 shell = os.environ.get('SHELL', None) 44 if shell is None: 45 print 'Don\'t know how to run a shell on this system' 46 elif shell.endswith('bash'): 47 ps1 = '[CR] ' + os.environ.get('PS1', '') 48 with tempfile.NamedTemporaryFile() as rcfile: 49 rcfile.write('source ~/.bashrc\nPS1="'+ps1+'"') 50 rcfile.flush() 51 cr.Host.Execute(shell, '--rcfile', rcfile.name) 52 else: 53 cr.Host.Execute(shell) 54