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
32 # get path to salomeTools sources
33 satdir = os.path.dirname(os.path.realpath(__file__))
34 cmdsdir = os.path.join(satdir, 'commands')
36 # Make the src package accessible from all code
37 sys.path.append(satdir)
38 sys.path.append(cmdsdir)
42 # load resources for internationalization
43 #es = gettext.translation('salomeTools', os.path.join(satdir, 'src', 'i18n'))
45 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
47 # The possible hooks :
48 # pre is for hooks to be executed before commands
49 # post is for hooks to be executed after commands
53 def find_command_list(dirPath):
54 ''' Parse files in dirPath that end with .py : it gives commands list
56 :param dirPath str: The directory path where to search the commands
57 :return: cmd_list : the list containing the commands name
61 for item in os.listdir(dirPath):
62 if item.endswith('.py'):
63 cmd_list.append(item[:-len('.py')])
66 # The list of valid salomeTools commands
67 #lCommand = ['config', 'compile', 'prepare']
68 lCommand = find_command_list(cmdsdir)
70 # Define all possible option for salomeTools command : sat <option> <args>
71 parser = src.options.Options()
72 parser.add_option('h', 'help', 'boolean', 'help',
73 _("shows global help or help on a specific command."))
74 parser.add_option('o', 'overwrite', 'list', "overwrite",
75 _("overwrites a configuration parameters."))
76 parser.add_option('g', 'debug', 'boolean', 'debug_mode',
77 _("run salomeTools in debug mode."))
78 parser.add_option('v', 'verbose', 'int', "output_verbose_level",
79 _("change output verbose level (default is 3)."))
80 parser.add_option('b', 'batch', 'boolean', "batch",
81 _("batch mode (no question)."))
82 parser.add_option('t', 'all_in_terminal', 'boolean', "all_in_terminal",
83 _("All traces in the terminal (for example compilation logs)."))
86 '''The main class that stores all the commands of salomeTools
88 def __init__(self, opt='', datadir=None):
91 :param opt str: The sat options
92 :param: datadir str : the directory that contain all the external
93 data (like software pyconf and software scripts)
95 # Read the salomeTools options (the list of possible options is
96 # at the beginning of this file)
98 (options, argus) = parser.parse_args(opt.split(' '))
99 except Exception as exc:
103 # initialization of class attributes
104 self.__dict__ = dict()
105 self.cfg = None # the config that will be read using pyconf module
107 self.options = options # the options passed to salomeTools
108 self.datadir = datadir # default value will be <salomeTools root>/data
109 # set the commands by calling the dedicated function
110 self._setCommands(cmdsdir)
112 # if the help option has been called, print help and exit
115 self.print_help(argus)
117 except Exception as exc:
121 def __getattr__(self, name):
122 ''' overwrite of __getattr__ function in order to display
123 a customized message in case of a wrong call
125 :param name str: The name of the attribute
127 if name in self.__dict__:
128 return self.__dict__[name]
130 raise AttributeError(name + _(" is not a valid command"))
132 def _setCommands(self, dirPath):
133 '''set class attributes corresponding to all commands that are
134 in the dirPath directory
136 :param dirPath str: The directory path containing the commands
138 # loop on the commands name
139 for nameCmd in lCommand:
140 # load the module that has name nameCmd in dirPath
141 (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
142 module = imp.load_module(nameCmd, file_, pathname, description)
144 def run_command(args='', batch = False, verbose = -1, logger_add_link = None):
145 '''The function that will load the configuration (all pyconf)
146 and return the function run of the command corresponding to module
148 :param args str: The directory path containing the commands
150 # Make sure the internationalization is available
151 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
153 # Get the arguments in a list and remove the empty elements
154 argv_0 = args.split(" ")
156 while "" in argv_0: argv_0.remove("")
158 # Format the argv list in order to prevent strings
159 # that contain a blank to be separated
163 if argv == [] or elem_old.startswith("-") or elem.startswith("-"):
166 argv[-1] += " " + elem
169 # if it is provided by the command line, get the application
171 if argv != [''] and argv[0][0] != "-":
172 appliToLoad = argv[0].rstrip('*')
175 # read the configuration from all the pyconf files
176 cfgManager = config.ConfigManager()
177 self.cfg = cfgManager.get_config(datadir=self.datadir,
178 application=appliToLoad,
179 options=self.options,
182 # Set the verbose mode if called
184 verbose_save = self.options.output_verbose_level
185 self.options.__setattr__("output_verbose_level", verbose)
187 # Set batch mode if called
189 batch_save = self.options.batch
190 self.options.__setattr__("batch", True)
193 if self.options.output_verbose_level is not None:
194 self.cfg.USER.output_verbose_level = self.options.output_verbose_level
195 if self.cfg.USER.output_verbose_level < 1:
196 self.cfg.USER.output_verbose_level = 0
197 silent = (self.cfg.USER.output_verbose_level == 0)
200 logger_command = src.logger.Logger(self.cfg,
201 silent_sysstd=silent,
202 all_in_terminal=self.options.all_in_terminal)
205 # Execute the hooks (if there is any)
206 # and run method of the command
207 self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
208 res = __module__.run(argv, self, logger_command)
209 self.run_hook(__nameCmd__, C_POST_HOOK, logger_command)
211 # set res if it is not set in the command
215 # come back in the original batch mode if
216 # batch argument was called
218 self.options.__setattr__("batch", batch_save)
220 # come back in the original verbose mode if
221 # verbose argument was called
223 self.options.__setattr__("output_verbose_level",
225 # put final attributes in xml log file
226 # (end time, total time, ...) and write it
227 launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
232 launchedCommand = launchedCommand.replace('"', "'")
234 # Add a link to the parent command
235 if logger_add_link is not None:
236 xmlLinks = logger_add_link.xmlFile.xmlroot.find(
238 src.xmlManager.add_simple_node(xmlLinks,
240 text = logger_command.logFileName,
241 attrib = {"command" : __nameCmd__,
243 "launchedCommand" : launchedCommand})
244 logger_add_link.l_logFiles += logger_command.l_logFiles
247 launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
252 launchedCommand = launchedCommand.replace('"', "'")
254 # Put the final attributes corresponding to end time and
255 # Write the file to the hard drive
256 logger_command.end_write(
257 {"launchedCommand" : launchedCommand})
261 # Make sure that run_command will be redefined
262 # at each iteration of the loop
264 globals_up.update(run_command.__globals__)
265 globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
266 func = types.FunctionType(run_command.__code__,
268 run_command.__name__,
269 run_command.__defaults__,
270 run_command.__closure__)
272 # set the attribute corresponding to the command
273 self.__setattr__(nameCmd, func)
275 def run_hook(self, cmd_name, hook_type, logger):
276 '''Execute a hook file for a given command regarding the fact
279 :param cmd_name str: The the command on which execute the hook
280 :param hook_type str: pre or post
281 :param logger Logger: the logging instance to use for the prints
283 # The hooks must be defined in the application pyconf
284 # So, if there is no application, do not do anything
285 if not src.config_has_application(self.cfg):
288 # The hooks must be defined in the application pyconf in the
289 # APPLICATION section, hook : { command : 'script_path.py'}
290 if "hook" not in self.cfg.APPLICATION \
291 or cmd_name not in self.cfg.APPLICATION.hook:
294 # Get the hook_script path and verify that it exists
295 hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
296 if not os.path.exists(hook_script_path):
297 raise src.SatException(_("Hook script not found: %s") %
300 # Try to execute the script, catch the exception if it fails
302 # import the module (in the sense of python)
303 pymodule = imp.load_source(cmd_name, hook_script_path)
305 # format a message to be printed at hook execution
306 msg = src.printcolors.printcWarning(_("Run hook script"))
307 msg = "%s: %s\n" % (msg,
308 src.printcolors.printcInfo(hook_script_path))
310 # run the function run_pre_hook if this function is called
311 # before the command, run_post_hook if it is called after
312 if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
314 pymodule.run_pre_hook(self.cfg, logger)
315 elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
317 pymodule.run_post_hook(self.cfg, logger)
319 except Exception as exc:
320 msg = _("Unable to run hook script: %s") % hook_script_path
321 msg += "\n" + str(exc)
322 raise src.SatException(msg)
324 def print_help(self, opt):
325 '''Prints help for a command. Function called when "sat -h <command>"
327 :param argv str: the options passed (to get the command name)
329 # if no command as argument (sat -h)
335 # read the configuration from all the pyconf files
336 cfgManager = config.ConfigManager()
337 self.cfg = cfgManager.get_config(datadir=self.datadir)
339 # Check if this command exists
340 if not hasattr(self, command):
341 raise src.SatException(_("Command '%s' does not exist") % command)
343 # Print salomeTools version
347 module = self.get_module(command)
349 # print the description of the command that is done in the command file
350 if hasattr( module, "description" ) :
351 print(src.printcolors.printcHeader( _("Description:") ))
352 print(module.description() + '\n')
354 # print the description of the command options
355 if hasattr( module, "parser" ) :
356 module.parser.print_help()
358 def get_module(self, module):
359 '''Loads a command. Function called only by print_help
361 :param module str: the command to load
363 # Check if this command exists
364 if not hasattr(self, module):
365 raise src.SatException(_("Command '%s' does not exist") % module)
368 (file_, pathname, description) = imp.find_module(module, [cmdsdir])
369 module = imp.load_module(module, file_, pathname, description)
373 '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
376 cfgManager = config.ConfigManager()
377 cfg = cfgManager.get_config()
378 # print the key corresponding to salomeTools version
379 print(src.printcolors.printcHeader( _("Version: ") ) +
380 cfg.INTERNAL.sat_version + '\n')
384 '''prints salomeTools general help
386 :param options str: the options
390 print(src.printcolors.printcHeader( _("Usage: ") ) +
391 "sat [sat_options] <command> [product] [command_options]\n")
395 # display all the available commands.
396 print(src.printcolors.printcHeader(_("Available commands are:\n")))
397 for command in lCommand:
398 print(" - %s" % (command))
400 # Explain how to get the help for a specific command
401 print(src.printcolors.printcHeader(_("\nGetting the help for a specific"
402 " command: ")) + "sat --help <command>\n")
404 def write_exception(exc):
405 '''write exception in case of error in a command
407 :param exc exception: the exception to print
409 sys.stderr.write("\n***** ")
410 sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
411 sys.stderr.write("\n" + str(exc) + "\n")
413 # ###############################
414 # MAIN : terminal command usage #
415 # ###############################
416 if __name__ == "__main__":
417 # Initialize the code that will be returned by the terminal command
419 (options, args) = parser.parse_args(sys.argv[1:])
421 # no arguments : print general help
426 # instantiate the salomeTools class with correct options
427 sat = Sat(' '.join(sys.argv[1:]))
430 # get dynamically the command function to call
431 fun_command = sat.__getattr__(command)
432 # call the command with two cases : mode debug or not
433 if options.debug_mode:
434 # call classically the command and if it fails,
435 # show exception and stack (usual python mode)
436 code = fun_command(' '.join(args[1:]))
438 # catch exception in order to show less verbose but elegant message
440 code = fun_command(' '.join(args[1:]))
441 except Exception as exc:
445 # exit salomeTools with the right code (0 if no errors, else 1)
446 if code is None: code = 0