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
18 '''This file is the main entry file to salomeTools
34 # get path to salomeTools sources
35 satdir = os.path.dirname(os.path.realpath(__file__))
36 cmdsdir = os.path.join(satdir, 'commands')
38 # Make the src package accessible from all code
39 sys.path.append(satdir)
40 sys.path.append(cmdsdir)
44 # load resources for internationalization
45 #es = gettext.translation('salomeTools', os.path.join(satdir, 'src', 'i18n'))
47 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
49 # The possible hooks :
50 # pre is for hooks to be executed before commands
51 # post is for hooks to be executed after commands
55 def find_command_list(dirPath):
56 ''' Parse files in dirPath that end with .py : it gives commands list
58 :param dirPath str: The directory path where to search the commands
59 :return: cmd_list : the list containing the commands name
63 for item in os.listdir(dirPath):
64 if item.endswith('.py'):
65 cmd_list.append(item[:-len('.py')])
68 # The list of valid salomeTools commands
69 #lCommand = ['config', 'compile', 'prepare']
70 lCommand = find_command_list(cmdsdir)
72 # Define all possible option for salomeTools command : sat <option> <args>
73 parser = src.options.Options()
74 parser.add_option('h', 'help', 'boolean', 'help',
75 _("shows global help or help on a specific command."))
76 parser.add_option('o', 'overwrite', 'list', "overwrite",
77 _("overwrites a configuration parameters."))
78 parser.add_option('g', 'debug', 'boolean', 'debug_mode',
79 _("run salomeTools in debug mode."))
80 parser.add_option('v', 'verbose', 'int', "output_verbose_level",
81 _("change output verbose level (default is 3)."))
82 parser.add_option('b', 'batch', 'boolean', "batch",
83 _("batch mode (no question)."))
84 parser.add_option('t', 'all_in_terminal', 'boolean', "all_in_terminal",
85 _("All traces in the terminal (for example compilation logs)."))
86 parser.add_option('l', 'logs_paths_in_file', 'string', "logs_paths_in_file",
87 _("Put the command result and paths to log files in ."))
90 '''The main class that stores all the commands of salomeTools
92 def __init__(self, opt='', datadir=None):
95 :param opt str: The sat options
96 :param: datadir str : the directory that contain all the external
97 data (like software pyconf and software scripts)
99 # Read the salomeTools options (the list of possible options is
100 # at the beginning of this file)
102 (options, argus) = parser.parse_args(opt)
103 except Exception as exc:
107 # initialization of class attributes
108 self.__dict__ = dict()
109 self.cfg = None # the config that will be read using pyconf module
111 self.options = options # the options passed to salomeTools
112 self.datadir = datadir # default value will be <salomeTools root>/data
113 # set the commands by calling the dedicated function
114 self._setCommands(cmdsdir)
116 # if the help option has been called, print help and exit
119 self.print_help(argus)
121 except Exception as exc:
125 def __getattr__(self, name):
126 ''' overwrite of __getattr__ function in order to display
127 a customized message in case of a wrong call
129 :param name str: The name of the attribute
131 if name in self.__dict__:
132 return self.__dict__[name]
134 raise AttributeError(name + _(" is not a valid command"))
136 def _setCommands(self, dirPath):
137 '''set class attributes corresponding to all commands that are
138 in the dirPath directory
140 :param dirPath str: The directory path containing the commands
142 # loop on the commands name
143 for nameCmd in lCommand:
145 # Exception for the jobs command that requires the paramiko module
146 if nameCmd == "jobs":
149 ff = tempfile.TemporaryFile()
157 # load the module that has name nameCmd in dirPath
158 (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
159 module = imp.load_module(nameCmd, file_, pathname, description)
161 def run_command(args='',
165 logger_add_link = None):
166 '''The function that will load the configuration (all pyconf)
167 and return the function run of the command corresponding to module
169 :param args str: The arguments of the command
171 # Make sure the internationalization is available
172 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
174 # Get the arguments in a list and remove the empty elements
175 if type(args) == type(''):
176 # split by spaces without considering spaces in quotes
177 argv_0 = re.findall(r'(?:"[^"]*"|[^\s"])+', args)
182 while "" in argv_0: argv_0.remove("")
184 # Format the argv list in order to prevent strings
185 # that contain a blank to be separated
189 if argv == [] or elem_old.startswith("-") or elem.startswith("-"):
192 argv[-1] += " " + elem
195 # if it is provided by the command line, get the application
197 if argv not in [[''], []] and argv[0][0] != "-":
198 appliToLoad = argv[0].rstrip('*')
201 # Check if the global options of salomeTools have to be changed
203 options_save = self.options
204 self.options = options
206 # read the configuration from all the pyconf files
207 cfgManager = config.ConfigManager()
208 self.cfg = cfgManager.get_config(datadir=self.datadir,
209 application=appliToLoad,
210 options=self.options,
213 # Set the verbose mode if called
215 verbose_save = self.options.output_verbose_level
216 self.options.__setattr__("output_verbose_level", verbose)
218 # Set batch mode if called
220 batch_save = self.options.batch
221 self.options.__setattr__("batch", True)
224 if self.options.output_verbose_level is not None:
225 self.cfg.USER.output_verbose_level = self.options.output_verbose_level
226 if self.cfg.USER.output_verbose_level < 1:
227 self.cfg.USER.output_verbose_level = 0
228 silent = (self.cfg.USER.output_verbose_level == 0)
231 micro_command = False
234 logger_command = src.logger.Logger(self.cfg,
235 silent_sysstd=silent,
236 all_in_terminal=self.options.all_in_terminal,
237 micro_command=micro_command)
239 # Check that the path given by the logs_paths_in_file option
240 # is a file path that can be written
241 if self.options.logs_paths_in_file and not micro_command:
243 self.options.logs_paths_in_file = os.path.abspath(
244 self.options.logs_paths_in_file)
245 dir_file = os.path.dirname(self.options.logs_paths_in_file)
246 if not os.path.exists(dir_file):
247 os.makedirs(dir_file)
248 if os.path.exists(self.options.logs_paths_in_file):
249 os.remove(self.options.logs_paths_in_file)
250 file_test = open(self.options.logs_paths_in_file, "w")
252 except Exception as e:
253 msg = _("WARNING: the logs_paths_in_file option will "
254 "not be taken into account.\nHere is the error:")
255 logger_command.write("%s\n%s\n\n" % (
256 src.printcolors.printcWarning(msg),
258 self.options.logs_paths_in_file = None
260 options_launched = ""
263 # Execute the hooks (if there is any)
264 # and run method of the command
265 self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
266 res = __module__.run(argv, self, logger_command)
267 self.run_hook(__nameCmd__, C_POST_HOOK, logger_command)
271 except Exception as e:
273 logger_command.write("\n***** ", 1)
274 logger_command.write(src.printcolors.printcError(
275 "salomeTools ERROR:"), 1)
276 logger_command.write("\n" + str(e) + "\n\n", 1)
278 __, __, exc_traceback = sys.exc_info()
279 fp = tempfile.TemporaryFile()
280 traceback.print_tb(exc_traceback, file=fp)
284 if self.options.debug_mode:
286 logger_command.write("TRACEBACK: %s" % stack.replace('"',"'"),
289 # set res if it is not set in the command
293 # come back to the original global options
295 options_launched = get_text_from_options(self.options)
296 self.options = options_save
298 # come back in the original batch mode if
299 # batch argument was called
301 self.options.__setattr__("batch", batch_save)
303 # come back in the original verbose mode if
304 # verbose argument was called
306 self.options.__setattr__("output_verbose_level",
308 # put final attributes in xml log file
309 # (end time, total time, ...) and write it
310 launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
316 launchedCommand = launchedCommand.replace('"', "'")
318 # Add a link to the parent command
319 if logger_add_link is not None:
320 logger_add_link.add_link(logger_command.logFileName,
324 logger_add_link.l_logFiles += logger_command.l_logFiles
326 # Put the final attributes corresponding to end time and
327 # Write the file to the hard drive
328 logger_command.end_write(
329 {"launchedCommand" : launchedCommand})
334 # print the log file path if
335 # the maximum verbose mode is invoked
336 if not micro_command:
337 logger_command.write("\nPath to the xml log file :\n",
339 logger_command.write("%s\n\n" % src.printcolors.printcInfo(
340 logger_command.logFilePath), 5)
342 # If the logs_paths_in_file was called, write the result
343 # and log files in the given file path
344 if self.options.logs_paths_in_file and not micro_command:
345 file_res = open(self.options.logs_paths_in_file, "w")
346 file_res.write(str(res) + "\n")
347 for i, filepath in enumerate(logger_command.l_logFiles):
348 file_res.write(filepath)
349 if i < len(logger_command.l_logFiles):
355 # Make sure that run_command will be redefined
356 # at each iteration of the loop
358 globals_up.update(run_command.__globals__)
359 globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
360 func = types.FunctionType(run_command.__code__,
362 run_command.__name__,
363 run_command.__defaults__,
364 run_command.__closure__)
366 # set the attribute corresponding to the command
367 self.__setattr__(nameCmd, func)
369 def run_hook(self, cmd_name, hook_type, logger):
370 '''Execute a hook file for a given command regarding the fact
373 :param cmd_name str: The the command on which execute the hook
374 :param hook_type str: pre or post
375 :param logger Logger: the logging instance to use for the prints
377 # The hooks must be defined in the application pyconf
378 # So, if there is no application, do not do anything
379 if not src.config_has_application(self.cfg):
382 # The hooks must be defined in the application pyconf in the
383 # APPLICATION section, hook : { command : 'script_path.py'}
384 if "hook" not in self.cfg.APPLICATION \
385 or cmd_name not in self.cfg.APPLICATION.hook:
388 # Get the hook_script path and verify that it exists
389 hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
390 if not os.path.exists(hook_script_path):
391 raise src.SatException(_("Hook script not found: %s") %
394 # Try to execute the script, catch the exception if it fails
396 # import the module (in the sense of python)
397 pymodule = imp.load_source(cmd_name, hook_script_path)
399 # format a message to be printed at hook execution
400 msg = src.printcolors.printcWarning(_("Run hook script"))
401 msg = "%s: %s\n" % (msg,
402 src.printcolors.printcInfo(hook_script_path))
404 # run the function run_pre_hook if this function is called
405 # before the command, run_post_hook if it is called after
406 if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
408 pymodule.run_pre_hook(self.cfg, logger)
409 elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
411 pymodule.run_post_hook(self.cfg, logger)
413 except Exception as exc:
414 msg = _("Unable to run hook script: %s") % hook_script_path
415 msg += "\n" + str(exc)
416 raise src.SatException(msg)
418 def print_help(self, opt):
419 '''Prints help for a command. Function called when "sat -h <command>"
421 :param argv str: the options passed (to get the command name)
423 # if no command as argument (sat -h)
429 # read the configuration from all the pyconf files
430 cfgManager = config.ConfigManager()
431 self.cfg = cfgManager.get_config(datadir=self.datadir)
433 # Check if this command exists
434 if not hasattr(self, command):
435 raise src.SatException(_("Command '%s' does not exist") % command)
437 # Print salomeTools version
441 module = self.get_module(command)
443 # print the description of the command that is done in the command file
444 if hasattr( module, "description" ) :
445 print(src.printcolors.printcHeader( _("Description:") ))
446 print(module.description() + '\n')
448 # print the description of the command options
449 if hasattr( module, "parser" ) :
450 module.parser.print_help()
452 def get_module(self, module):
453 '''Loads a command. Function called only by print_help
455 :param module str: the command to load
457 # Check if this command exists
458 if not hasattr(self, module):
459 raise src.SatException(_("Command '%s' does not exist") % module)
462 (file_, pathname, description) = imp.find_module(module, [cmdsdir])
463 module = imp.load_module(module, file_, pathname, description)
466 def get_text_from_options(options):
468 for attr in dir(options):
469 if attr.startswith("__"):
471 if options.__getattr__(attr) != None:
472 option_contain = options.__getattr__(attr)
473 if type(option_contain)==type([]):
474 option_contain = ",".join(option_contain)
475 if type(option_contain)==type(True):
477 text_options+= "--%s %s " % (attr, option_contain)
482 '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
485 cfgManager = config.ConfigManager()
486 cfg = cfgManager.get_config()
487 # print the key corresponding to salomeTools version
488 print(src.printcolors.printcHeader( _("Version: ") ) +
489 cfg.INTERNAL.sat_version + '\n')
493 '''prints salomeTools general help
495 :param options str: the options
499 print(src.printcolors.printcHeader( _("Usage: ") ) +
500 "sat [sat_options] <command> [product] [command_options]\n")
504 # display all the available commands.
505 print(src.printcolors.printcHeader(_("Available commands are:\n")))
506 for command in lCommand:
507 print(" - %s" % (command))
509 # Explain how to get the help for a specific command
510 print(src.printcolors.printcHeader(_("\nGetting the help for a specific"
511 " command: ")) + "sat --help <command>\n")
513 def write_exception(exc):
514 '''write exception in case of error in a command
516 :param exc exception: the exception to print
518 sys.stderr.write("\n***** ")
519 sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
520 sys.stderr.write("\n" + str(exc) + "\n")
522 # ###############################
523 # MAIN : terminal command usage #
524 # ###############################
525 if __name__ == "__main__":
526 # Initialize the code that will be returned by the terminal command
528 (options, args) = parser.parse_args(sys.argv[1:])
530 # no arguments : print general help
535 # instantiate the salomeTools class with correct options
536 sat = Sat(sys.argv[1:])
539 # get dynamically the command function to call
540 fun_command = sat.__getattr__(command)
541 # Run the command using the arguments
542 code = fun_command(args[1:])
544 # exit salomeTools with the right code (0 if no errors, else 1)
545 if code is None: code = 0