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('l', 'level', 'int', "output_level",
79 _("change output level (default is 3)."))
80 parser.add_option('s', 'silent', 'boolean', 'silent',
81 _("do not write log or show errors."))
84 '''The main class that stores all the commands of salomeTools
86 def __init__(self, opt='', datadir=None):
89 :param opt str: The sat options
90 :param: datadir str : the directory that contain all the external
91 data (like software pyconf and software scripts)
93 # Read the salomeTools options (the list of possible options is
94 # at the beginning of this file)
96 (options, argus) = parser.parse_args(opt.split(' '))
97 except Exception as exc:
101 # initialization of class attributes
102 self.__dict__ = dict()
103 self.cfg = None # the config that will be read using pyconf module
105 self.options = options # the options passed to salomeTools
106 self.datadir = datadir # default value will be <salomeTools root>/data
107 # set the commands by calling the dedicated function
108 self._setCommands(cmdsdir)
110 # if the help option has been called, print help and exit
113 self.print_help(argus)
115 except Exception as exc:
119 def __getattr__(self, name):
120 ''' overwrite of __getattr__ function in order to display
121 a customized message in case of a wrong call
123 :param name str: The name of the attribute
125 if name in self.__dict__:
126 return self.__dict__[name]
128 raise AttributeError(name + _(" is not a valid command"))
130 def _setCommands(self, dirPath):
131 '''set class attributes corresponding to all commands that are
132 in the dirPath directory
134 :param dirPath str: The directory path containing the commands
136 # loop on the commands name
137 for nameCmd in lCommand:
138 # load the module that has name nameCmd in dirPath
139 (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
140 module = imp.load_module(nameCmd, file_, pathname, description)
142 def run_command(args='', logger=None):
143 '''The function that will load the configuration (all pyconf)
144 and return the function run of the command corresponding to module
146 :param args str: The directory path containing the commands
148 # Make sure the internationalization is available
149 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
151 # Get the arguments in a list and remove the empty elements
152 argv = args.split(" ")
154 while "" in argv: argv.remove("")
156 # if it is provided by the command line, get the application
158 if argv != [''] and argv[0][0] != "-":
159 appliToLoad = argv[0].rstrip('*')
162 # read the configuration from all the pyconf files
163 cfgManager = config.ConfigManager()
164 self.cfg = cfgManager.get_config(datadir=self.datadir,
165 application=appliToLoad,
166 options=self.options,
170 if self.options.output_level:
171 self.cfg.USER.output_level = self.options.output_level
172 if self.cfg.USER.output_level < 1:
173 self.cfg.USER.output_level = 1
175 # create log file, unless the command is called
176 # with a logger as parameter
177 logger_command = src.logger.Logger(self.cfg,
178 silent_sysstd=self.options.silent)
180 logger_command = logger
183 # Execute the hooks (if there is any)
184 # and run method of the command
185 self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
186 res = __module__.run(argv, self, logger_command)
187 self.run_hook(__nameCmd__, C_POST_HOOK, logger_command)
189 # put final attributes in xml log file
190 # (end time, total time, ...) and write it
191 launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
196 logger_command.end_write({"launchedCommand" : launchedCommand})
200 # Make sure that run_command will be redefined
201 # at each iteration of the loop
203 globals_up.update(run_command.__globals__)
204 globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
205 func = types.FunctionType(run_command.__code__,
207 run_command.__name__,
208 run_command.__defaults__,
209 run_command.__closure__)
211 # set the attribute corresponding to the command
212 self.__setattr__(nameCmd, func)
214 def run_hook(self, cmd_name, hook_type, logger):
215 '''Execute a hook file for a given command regarding the fact
218 :param cmd_name str: The the command on which execute the hook
219 :param hook_type str: pre or post
220 :param logger Logger: the logging instance to use for the prints
222 # The hooks must be defined in the application pyconf
223 # So, if there is no application, do not do anything
224 if not src.config_has_application(self.cfg):
227 # The hooks must be defined in the application pyconf in the
228 # APPLICATION section, hook : { command : 'script_path.py'}
229 if "hook" not in self.cfg.APPLICATION \
230 or cmd_name not in self.cfg.APPLICATION.hook:
233 # Get the hook_script path and verify that it exists
234 hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
235 if not os.path.exists(hook_script_path):
236 raise src.SatException(_("Hook script not found: %s") %
239 # Try to execute the script, catch the exception if it fails
241 # import the module (in the sense of python)
242 pymodule = imp.load_source(cmd_name, hook_script_path)
244 # format a message to be printed at hook execution
245 msg = src.printcolors.printcWarning(_("Run hook script"))
246 msg = "%s: %s\n" % (msg,
247 src.printcolors.printcInfo(hook_script_path))
249 # run the function run_pre_hook if this function is called
250 # before the command, run_post_hook if it is called after
251 if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
253 pymodule.run_pre_hook(self.cfg, logger)
254 elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
256 pymodule.run_post_hook(self.cfg, logger)
258 except Exception as exc:
259 msg = _("Unable to run hook script: %s") % hook_script_path
260 msg += "\n" + str(exc)
261 raise src.SatException(msg)
263 def print_help(self, opt):
264 '''Prints help for a command. Function called when "sat -h <command>"
266 :param argv str: the options passed (to get the command name)
268 # if no command as argument (sat -h)
274 # read the configuration from all the pyconf files
275 cfgManager = config.ConfigManager()
276 self.cfg = cfgManager.get_config(datadir=self.datadir)
278 # Check if this command exists
279 if not hasattr(self, command):
280 raise src.SatException(_("Command '%s' does not exist") % command)
282 # Print salomeTools version
286 module = self.get_module(command)
288 # print the description of the command that is done in the command file
289 if hasattr( module, "description" ) :
290 print(src.printcolors.printcHeader( _("Description:") ))
291 print(module.description() + '\n')
293 # print the description of the command options
294 if hasattr( module, "parser" ) :
295 module.parser.print_help()
297 def get_module(self, module):
298 '''Loads a command. Function called only by print_help
300 :param module str: the command to load
302 # Check if this command exists
303 if not hasattr(self, module):
304 raise src.SatException(_("Command '%s' does not exist") % module)
307 (file_, pathname, description) = imp.find_module(module, [cmdsdir])
308 module = imp.load_module(module, file_, pathname, description)
312 '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
315 cfgManager = config.ConfigManager()
316 cfg = cfgManager.get_config()
317 # print the key corresponding to salomeTools version
318 print(src.printcolors.printcHeader( _("Version: ") ) +
319 cfg.INTERNAL.sat_version + '\n')
323 '''prints salomeTools general help
325 :param options str: the options
329 print(src.printcolors.printcHeader( _("Usage: ") ) +
330 "sat [sat_options] <command> [product] [command_options]\n")
334 # display all the available commands.
335 print(src.printcolors.printcHeader(_("Available commands are:\n")))
336 for command in lCommand:
337 print(" - %s" % (command))
339 # Explain how to get the help for a specific command
340 print(src.printcolors.printcHeader(_("\nGetting the help for a specific"
341 " command: ")) + "sat --help <command>\n")
343 def write_exception(exc):
344 '''write exception in case of error in a command
346 :param exc exception: the exception to print
348 sys.stderr.write("\n***** ")
349 sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
350 sys.stderr.write("\n" + str(exc) + "\n")
352 # ###############################
353 # MAIN : terminal command usage #
354 # ###############################
355 if __name__ == "__main__":
356 # Initialize the code that will be returned by the terminal command
358 (options, args) = parser.parse_args(sys.argv[1:])
360 # no arguments : print general help
365 # instantiate the salomeTools class with correct options
366 sat = Sat(' '.join(sys.argv[1:]))
369 # get dynamically the command function to call
370 fun_command = sat.__getattr__(command)
371 # call the command with two cases : mode debug or not
372 if options.debug_mode:
373 # call classically the command and if it fails,
374 # show exception and stack (usual python mode)
375 code = fun_command(' '.join(args[1:]))
377 # catch exception in order to show less verbose but elegant message
379 code = fun_command(' '.join(args[1:]))
380 except Exception as exc:
384 # exit salomeTools with the right code (0 if no errors, else 1)
385 if code is None: code = 0