3 # Copyright (C) 2010-2012 CEA/DEN
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 '''This file is the main entry file to salomeTools
33 # get path to salomeTools sources
34 srcdir = os.path.dirname(os.path.realpath(__file__))
36 # load resources for internationalization
37 es = gettext.translation('salomeTools', os.path.join(srcdir, 'common', 'i18n'))
40 def find_command_list(dirPath):
41 ''' Parse files in dirPath that end with .py : it gives commands list
42 :param dirPath str: The directory path where to search the commands
43 :return: cmd_list : the list containing the commands name
47 for item in os.listdir(dirPath):
48 if item.endswith('.py') and item!='salomeTools.py':
49 cmd_list.append(item[:-len('.py')])
52 # The list of valid salomeTools commands
53 #lCommand = ['config', 'compile', 'prepare']
54 lCommand = find_command_list(srcdir)
56 # Define all possible option for salomeTools command : sat <option> <args>
57 parser = common.options.Options()
58 parser.add_option('h', 'help', 'boolean', 'help', _("shows global help or help on a specific command."))
59 parser.add_option('o', 'overwrite', 'list', "overwrite", _("overwrites a configuration parameters."))
60 parser.add_option('g', 'debug', 'boolean', 'debug_mode', _("run salomeTools in debug mode."))
62 class salomeTools(object):
63 '''The main class that stores all the commands of salomeTools
65 def __init__(self, opt, dataDir=None):
67 :param opt str: The sat options
68 :param: dataDir str : the directory that contain all the external data (like software pyconf and software scripts)
70 # Read the salomeTools options (the list of possible options is at the beginning of this file)
72 (options, argus) = parser.parse_args(opt.split(' '))
73 except Exception as exc:
77 # initialization of class attributes
78 self.__dict__ = dict()
79 self.cfg = None # the config that will be read using config_pyconf module
80 self.options = options # the options passed to salomeTools
81 self.dataDir = dataDir # default value will be <salomeTools root>/data
82 # set the commands by calling the dedicated function
83 self.__setCommands__(srcdir)
85 # if the help option has been called, print help and exit
88 self.print_help(argus)
90 except Exception as exc:
94 def __getattr__(self, name):
95 ''' overwrite of __getattr__ function in order to display a customized message in case of a wrong call
96 :param name str: The name of the attribute
98 if name in self.__dict__:
99 return self.__dict__[name]
101 raise AttributeError(name + _(" is not a valid command"))
103 def __setCommands__(self, dirPath):
104 '''set class attributes corresponding to all commands that are in the dirPath directory
105 :param dirPath str: The directory path containing the commands
107 # loop on the commands name
108 for nameCmd in lCommand:
109 # load the module that has name nameCmd in dirPath
110 (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
111 module = imp.load_module(nameCmd, file_, pathname, description)
113 def run_command(args):
114 '''The function that will load the configuration (all pyconf)
115 and return the function run of the command corresponding to module
116 :param args str: The directory path containing the commands
118 argv = args.split(" ")
120 # first argument is the APPLICATION
122 if argv != [''] and argv[0][0] != "-":
123 appliToLoad = argv[0].rstrip('*')
126 # Read the config if it is not already done
128 # read the configuration from all the pyconf files
129 cfgManager = config.ConfigManager()
130 self.cfg = cfgManager.getConfig(dataDir=self.dataDir, application=appliToLoad, options=self.options)
132 return __module__.run(argv, self)
134 # Make sure that run_command will be redefined at each iteration of the loop
136 globals_up.update(run_command.__globals__)
137 globals_up.update({'__name__': nameCmd, '__module__' : module})
138 func = types.FunctionType(run_command.__code__, globals_up, run_command.__name__,run_command.__defaults__, run_command.__closure__)
140 # set the attribute corresponding to the command
141 self.__setattr__(nameCmd, func)
143 def print_help(self, opt):
144 '''Prints help for a command. Function called when "sat -h <command>"
145 :param argv str: the options passed (to get the command name)
147 # if no command as argument (sat -h)
153 # read the configuration from all the pyconf files
154 cfgManager = config.ConfigManager()
155 self.cfg = cfgManager.getConfig(dataDir=self.dataDir)
157 # Check if this command exists
158 if not hasattr(self, command):
159 raise common.SatException(_("Command '%s' does not exist") % command)
161 # Print salomeTools version
165 module = self.get_module(command)
167 # print the description of the command that is done in the command file
168 if hasattr( module, "description" ) :
169 print(common.printcolors.printcHeader( _("Description:") ))
170 print(module.description() + '\n')
172 # print the description of the command options
173 if hasattr( module, "parser" ) :
174 module.parser.print_help()
176 def get_module(self, module):
177 '''Loads a command. Function called only by print_help
178 :param module str: the command to load
180 # Check if this command exists
181 if not hasattr(self, module):
182 raise common.SatException(_("Command '%s' does not exist") % module)
185 (file_, pathname, description) = imp.find_module(module, [srcdir])
186 module = imp.load_module(module, file_, pathname, description)
190 '''prints salomeTools version (in src/common/internal_config/salomeTools.pyconf)
193 cfgManager = config.ConfigManager()
194 cfg = cfgManager.getConfig()
195 # print the key corresponding to salomeTools version
196 print(common.printcolors.printcHeader( _("Version: ") ) + cfg.INTERNAL.sat_version + '\n')
200 '''prints salomeTools general help
201 :param options str: the options
205 print(common.printcolors.printcHeader( _("Usage: ") ) + "sat [sat_options] <command> [product] [command_options]\n")
209 # display all the available commands.
210 print(common.printcolors.printcHeader(_("Available commands are:\n")))
211 for command in lCommand:
212 print(" - %s" % (command))
214 # Explain how to get the help for a specific command
215 print(common.printcolors.printcHeader(_("\nGetting the help for a specific command: ")) + "sat --help <command>\n")
217 def write_exception(exc):
218 '''write exception in case of error in a command
219 :param exc exception: the exception to print
221 sys.stderr.write("\n***** ")
222 sys.stderr.write(common.printcolors.printcError("salomeTools ERROR:"))
223 sys.stderr.write("\n" + str(exc) + "\n")
225 # ###############################
226 # MAIN : terminal command usage #
227 # ###############################
228 if __name__ == "__main__":
229 # Get the command line using sys.argv
230 cmd_line = " ".join(sys.argv)
231 # Initialize the code that will be returned by the terminal command
233 (options, args) = parser.parse_args(sys.argv[1:])
235 # instantiate the salomeTools class with correct options
236 sat = salomeTools(' '.join(sys.argv[1:]))
239 # get dynamically the command function to call
240 fun_command = sat.__getattr__(command)
241 if options.debug_mode:
242 # call classically the command and if it fails, show exception and stack (usual python mode)
243 code = fun_command(' '.join(args[1:]))
245 # catch exception in order to show less verbose but elegant message
247 code = fun_command(' '.join(args[1:]))
248 except Exception as exc:
252 # exit salomeTools with the right code (0 if no errors, else 1)
253 if code is None: code = 0