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 satdir = os.path.dirname(os.path.realpath(__file__))
35 cmdsdir = os.path.join(satdir, 'commands')
37 # Make the src package accessible from all code
38 sys.path.append(satdir)
39 sys.path.append(cmdsdir)
43 # load resources for internationalization
44 #es = gettext.translation('salomeTools', os.path.join(satdir, 'src', 'i18n'))
46 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
48 # The possible hooks :
49 # pre is for hooks to be executed before commands
50 # post is for hooks to be executed after commands
54 def find_command_list(dirPath):
55 ''' Parse files in dirPath that end with .py : it gives commands list
57 :param dirPath str: The directory path where to search the commands
58 :return: cmd_list : the list containing the commands name
62 for item in os.listdir(dirPath):
63 if item.endswith('.py'):
64 cmd_list.append(item[:-len('.py')])
67 # The list of valid salomeTools commands
68 #lCommand = ['config', 'compile', 'prepare']
69 lCommand = find_command_list(cmdsdir)
71 # Define all possible option for salomeTools command : sat <option> <args>
72 parser = src.options.Options()
73 parser.add_option('h', 'help', 'boolean', 'help',
74 _("shows global help or help on a specific command."))
75 parser.add_option('o', 'overwrite', 'list', "overwrite",
76 _("overwrites a configuration parameters."))
77 parser.add_option('g', 'debug', 'boolean', 'debug_mode',
78 _("run salomeTools in debug mode."))
79 parser.add_option('v', 'verbose', 'int', "output_verbose_level",
80 _("change output verbose level (default is 3)."))
81 parser.add_option('b', 'batch', 'boolean', "batch",
82 _("batch mode (no question)."))
83 parser.add_option('t', 'all_in_terminal', 'boolean', "all_in_terminal",
84 _("All traces in the terminal (for example compilation logs)."))
85 parser.add_option('l', 'logs_paths_in_file', 'string', "logs_paths_in_file",
86 _("Put the command result and paths to log files in ."))
89 '''The main class that stores all the commands of salomeTools
91 def __init__(self, opt='', datadir=None):
94 :param opt str: The sat options
95 :param: datadir str : the directory that contain all the external
96 data (like software pyconf and software scripts)
98 # Read the salomeTools options (the list of possible options is
99 # at the beginning of this file)
101 (options, argus) = parser.parse_args(opt.split(' '))
102 except Exception as exc:
106 # initialization of class attributes
107 self.__dict__ = dict()
108 self.cfg = None # the config that will be read using pyconf module
110 self.options = options # the options passed to salomeTools
111 self.datadir = datadir # default value will be <salomeTools root>/data
112 # set the commands by calling the dedicated function
113 self._setCommands(cmdsdir)
115 # if the help option has been called, print help and exit
118 self.print_help(argus)
120 except Exception as exc:
124 def __getattr__(self, name):
125 ''' overwrite of __getattr__ function in order to display
126 a customized message in case of a wrong call
128 :param name str: The name of the attribute
130 if name in self.__dict__:
131 return self.__dict__[name]
133 raise AttributeError(name + _(" is not a valid command"))
135 def _setCommands(self, dirPath):
136 '''set class attributes corresponding to all commands that are
137 in the dirPath directory
139 :param dirPath str: The directory path containing the commands
141 # loop on the commands name
142 for nameCmd in lCommand:
144 # Exception for the jobs command that requires the paramiko module
145 if nameCmd == "jobs":
148 ff = tempfile.TemporaryFile()
156 # load the module that has name nameCmd in dirPath
157 (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
158 module = imp.load_module(nameCmd, file_, pathname, description)
160 def run_command(args='',
164 logger_add_link = None):
165 '''The function that will load the configuration (all pyconf)
166 and return the function run of the command corresponding to module
168 :param args str: The directory path containing the commands
170 # Make sure the internationalization is available
171 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
173 # Get the arguments in a list and remove the empty elements
174 argv_0 = args.split(" ")
176 while "" in argv_0: argv_0.remove("")
178 # Format the argv list in order to prevent strings
179 # that contain a blank to be separated
183 if argv == [] or elem_old.startswith("-") or elem.startswith("-"):
186 argv[-1] += " " + elem
189 # if it is provided by the command line, get the application
191 if argv != [''] and argv[0][0] != "-":
192 appliToLoad = argv[0].rstrip('*')
195 # Check if the global options of salomeTools have to be changed
197 options_save = self.options
198 self.options = options
200 # read the configuration from all the pyconf files
201 cfgManager = config.ConfigManager()
202 self.cfg = cfgManager.get_config(datadir=self.datadir,
203 application=appliToLoad,
204 options=self.options,
207 # Set the verbose mode if called
209 verbose_save = self.options.output_verbose_level
210 self.options.__setattr__("output_verbose_level", verbose)
212 # Set batch mode if called
214 batch_save = self.options.batch
215 self.options.__setattr__("batch", True)
218 if self.options.output_verbose_level is not None:
219 self.cfg.USER.output_verbose_level = self.options.output_verbose_level
220 if self.cfg.USER.output_verbose_level < 1:
221 self.cfg.USER.output_verbose_level = 0
222 silent = (self.cfg.USER.output_verbose_level == 0)
225 micro_command = False
228 logger_command = src.logger.Logger(self.cfg,
229 silent_sysstd=silent,
230 all_in_terminal=self.options.all_in_terminal,
231 micro_command=micro_command)
233 # Check that the path given by the logs_paths_in_file option
234 # is a file path that can be written
235 if self.options.logs_paths_in_file and not micro_command:
237 self.options.logs_paths_in_file = os.path.abspath(
238 self.options.logs_paths_in_file)
239 dir_file = os.path.dirname(self.options.logs_paths_in_file)
240 if not os.path.exists(dir_file):
241 os.makedirs(dir_file)
242 if os.path.exists(self.options.logs_paths_in_file):
243 os.remove(self.options.logs_paths_in_file)
244 file_test = open(self.options.logs_paths_in_file, "w")
246 except Exception as e:
247 msg = _("WARNING: the logs_paths_in_file option will "
248 "not be taken into account.\nHere is the error:")
249 logger_command.write("%s\n%s\n\n" % (
250 src.printcolors.printcWarning(msg),
252 self.options.logs_paths_in_file = None
254 options_launched = ""
257 # Execute the hooks (if there is any)
258 # and run method of the command
259 self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
260 res = __module__.run(argv, self, logger_command)
261 self.run_hook(__nameCmd__, C_POST_HOOK, logger_command)
263 # set res if it is not set in the command
267 # come back to the original global options
269 options_launched = get_text_from_options(self.options)
270 self.options = options_save
272 # come back in the original batch mode if
273 # batch argument was called
275 self.options.__setattr__("batch", batch_save)
277 # come back in the original verbose mode if
278 # verbose argument was called
280 self.options.__setattr__("output_verbose_level",
282 # put final attributes in xml log file
283 # (end time, total time, ...) and write it
284 launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
290 launchedCommand = launchedCommand.replace('"', "'")
292 # Add a link to the parent command
293 if logger_add_link is not None:
294 logger_add_link.add_link(logger_command.logFileName,
298 logger_add_link.l_logFiles += logger_command.l_logFiles
301 launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
307 launchedCommand = launchedCommand.replace('"', "'")
309 # Put the final attributes corresponding to end time and
310 # Write the file to the hard drive
311 logger_command.end_write(
312 {"launchedCommand" : launchedCommand})
316 # If the logs_paths_in_file was called, write the result
317 # and log files in the given file path
318 if self.options.logs_paths_in_file and not micro_command:
319 file_res = open(self.options.logs_paths_in_file, "w")
320 file_res.write(str(res) + "\n")
321 for i, filepath in enumerate(logger_command.l_logFiles):
322 file_res.write(filepath)
323 if i < len(logger_command.l_logFiles):
329 # Make sure that run_command will be redefined
330 # at each iteration of the loop
332 globals_up.update(run_command.__globals__)
333 globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
334 func = types.FunctionType(run_command.__code__,
336 run_command.__name__,
337 run_command.__defaults__,
338 run_command.__closure__)
340 # set the attribute corresponding to the command
341 self.__setattr__(nameCmd, func)
343 def run_hook(self, cmd_name, hook_type, logger):
344 '''Execute a hook file for a given command regarding the fact
347 :param cmd_name str: The the command on which execute the hook
348 :param hook_type str: pre or post
349 :param logger Logger: the logging instance to use for the prints
351 # The hooks must be defined in the application pyconf
352 # So, if there is no application, do not do anything
353 if not src.config_has_application(self.cfg):
356 # The hooks must be defined in the application pyconf in the
357 # APPLICATION section, hook : { command : 'script_path.py'}
358 if "hook" not in self.cfg.APPLICATION \
359 or cmd_name not in self.cfg.APPLICATION.hook:
362 # Get the hook_script path and verify that it exists
363 hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
364 if not os.path.exists(hook_script_path):
365 raise src.SatException(_("Hook script not found: %s") %
368 # Try to execute the script, catch the exception if it fails
370 # import the module (in the sense of python)
371 pymodule = imp.load_source(cmd_name, hook_script_path)
373 # format a message to be printed at hook execution
374 msg = src.printcolors.printcWarning(_("Run hook script"))
375 msg = "%s: %s\n" % (msg,
376 src.printcolors.printcInfo(hook_script_path))
378 # run the function run_pre_hook if this function is called
379 # before the command, run_post_hook if it is called after
380 if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
382 pymodule.run_pre_hook(self.cfg, logger)
383 elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
385 pymodule.run_post_hook(self.cfg, logger)
387 except Exception as exc:
388 msg = _("Unable to run hook script: %s") % hook_script_path
389 msg += "\n" + str(exc)
390 raise src.SatException(msg)
392 def print_help(self, opt):
393 '''Prints help for a command. Function called when "sat -h <command>"
395 :param argv str: the options passed (to get the command name)
397 # if no command as argument (sat -h)
403 # read the configuration from all the pyconf files
404 cfgManager = config.ConfigManager()
405 self.cfg = cfgManager.get_config(datadir=self.datadir)
407 # Check if this command exists
408 if not hasattr(self, command):
409 raise src.SatException(_("Command '%s' does not exist") % command)
411 # Print salomeTools version
415 module = self.get_module(command)
417 # print the description of the command that is done in the command file
418 if hasattr( module, "description" ) :
419 print(src.printcolors.printcHeader( _("Description:") ))
420 print(module.description() + '\n')
422 # print the description of the command options
423 if hasattr( module, "parser" ) :
424 module.parser.print_help()
426 def get_module(self, module):
427 '''Loads a command. Function called only by print_help
429 :param module str: the command to load
431 # Check if this command exists
432 if not hasattr(self, module):
433 raise src.SatException(_("Command '%s' does not exist") % module)
436 (file_, pathname, description) = imp.find_module(module, [cmdsdir])
437 module = imp.load_module(module, file_, pathname, description)
440 def get_text_from_options(options):
442 for attr in dir(options):
443 if attr.startswith("__"):
445 if options.__getattr__(attr) != None:
446 option_contain = options.__getattr__(attr)
447 if type(option_contain)==type([]):
448 option_contain = ",".join(option_contain)
449 if type(option_contain)==type(True):
451 text_options+= "--%s %s " % (attr, option_contain)
456 '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
459 cfgManager = config.ConfigManager()
460 cfg = cfgManager.get_config()
461 # print the key corresponding to salomeTools version
462 print(src.printcolors.printcHeader( _("Version: ") ) +
463 cfg.INTERNAL.sat_version + '\n')
467 '''prints salomeTools general help
469 :param options str: the options
473 print(src.printcolors.printcHeader( _("Usage: ") ) +
474 "sat [sat_options] <command> [product] [command_options]\n")
478 # display all the available commands.
479 print(src.printcolors.printcHeader(_("Available commands are:\n")))
480 for command in lCommand:
481 print(" - %s" % (command))
483 # Explain how to get the help for a specific command
484 print(src.printcolors.printcHeader(_("\nGetting the help for a specific"
485 " command: ")) + "sat --help <command>\n")
487 def write_exception(exc):
488 '''write exception in case of error in a command
490 :param exc exception: the exception to print
492 sys.stderr.write("\n***** ")
493 sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
494 sys.stderr.write("\n" + str(exc) + "\n")
496 # ###############################
497 # MAIN : terminal command usage #
498 # ###############################
499 if __name__ == "__main__":
500 # Initialize the code that will be returned by the terminal command
502 (options, args) = parser.parse_args(sys.argv[1:])
504 # no arguments : print general help
509 # instantiate the salomeTools class with correct options
510 sat = Sat(' '.join(sys.argv[1:]))
513 # get dynamically the command function to call
514 fun_command = sat.__getattr__(command)
515 # call the command with two cases : mode debug or not
516 if options.debug_mode:
517 # call classically the command and if it fails,
518 # show exception and stack (usual python mode)
519 code = fun_command(' '.join(args[1:]))
521 # catch exception in order to show less verbose but elegant message
523 code = fun_command(' '.join(args[1:]))
524 except Exception as exc:
528 # exit salomeTools with the right code (0 if no errors, else 1)
529 if code is None: code = 0