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 def find_command_list(dirPath):
48 ''' Parse files in dirPath that end with .py : it gives commands list
50 :param dirPath str: The directory path where to search the commands
51 :return: cmd_list : the list containing the commands name
55 for item in os.listdir(dirPath):
56 if item.endswith('.py'):
57 cmd_list.append(item[:-len('.py')])
60 # The list of valid salomeTools commands
61 #lCommand = ['config', 'compile', 'prepare']
62 lCommand = find_command_list(cmdsdir)
64 # Define all possible option for salomeTools command : sat <option> <args>
65 parser = src.options.Options()
66 parser.add_option('h', 'help', 'boolean', 'help', _("shows global help or help on a specific command."))
67 parser.add_option('o', 'overwrite', 'list', "overwrite", _("overwrites a configuration parameters."))
68 parser.add_option('g', 'debug', 'boolean', 'debug_mode', _("run salomeTools in debug mode."))
69 parser.add_option('l', 'level', 'int', "output_level", _("change output level (default is 3)."))
70 parser.add_option('s', 'silent', 'boolean', 'silent', _("do not write log or show errors."))
73 '''The main class that stores all the commands of salomeTools
75 def __init__(self, opt='', dataDir=None):
78 :param opt str: The sat options
79 :param: dataDir str : the directory that contain all the external data (like software pyconf and software scripts)
81 # Read the salomeTools options (the list of possible options is at the beginning of this file)
83 (options, argus) = parser.parse_args(opt.split(' '))
84 except Exception as exc:
88 # initialization of class attributes
89 self.__dict__ = dict()
90 self.cfg = None # the config that will be read using pyconf module
92 self.options = options # the options passed to salomeTools
93 self.dataDir = dataDir # default value will be <salomeTools root>/data
94 # set the commands by calling the dedicated function
95 self.__setCommands__(cmdsdir)
97 # if the help option has been called, print help and exit
100 self.print_help(argus)
102 except Exception as exc:
106 def __getattr__(self, name):
107 ''' overwrite of __getattr__ function in order to display a customized message in case of a wrong call
109 :param name str: The name of the attribute
111 if name in self.__dict__:
112 return self.__dict__[name]
114 raise AttributeError(name + _(" is not a valid command"))
116 def __setCommands__(self, dirPath):
117 '''set class attributes corresponding to all commands that are in the dirPath directory
119 :param dirPath str: The directory path containing the commands
121 # loop on the commands name
122 for nameCmd in lCommand:
123 # load the module that has name nameCmd in dirPath
124 (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
125 module = imp.load_module(nameCmd, file_, pathname, description)
127 def run_command(args='', logger=None):
128 '''The function that will load the configuration (all pyconf)
129 and return the function run of the command corresponding to module
131 :param args str: The directory path containing the commands
133 argv = args.split(" ")
135 # if it is provided by the command line, get the application
137 if argv != [''] and argv[0][0] != "-":
138 appliToLoad = argv[0].rstrip('*')
141 # read the configuration from all the pyconf files
142 cfgManager = config.ConfigManager()
143 self.cfg = cfgManager.getConfig(dataDir=self.dataDir, application=appliToLoad, options=self.options, command=__nameCmd__)
146 if self.options.output_level:
147 self.cfg.USER.output_level = self.options.output_level
148 if self.cfg.USER.output_level < 1:
149 self.cfg.USER.output_level = 1
151 # create log file, unless the command is called with a logger as parameter
152 logger_command = src.logger.Logger(self.cfg, silent_sysstd=self.options.silent)
154 logger_command = logger
157 # Execute the run method of the command
158 res = __module__.run(argv, self, logger_command)
160 # put final attributes in xml log file (end time, total time, ...) and write it
161 launchedCommand = ' '.join([self.cfg.VARS.salometoolsway + os.path.sep + 'sat', self.arguments.split(' ')[0], args])
162 logger_command.endWrite({"launchedCommand" : launchedCommand})
166 # Make sure that run_command will be redefined at each iteration of the loop
168 globals_up.update(run_command.__globals__)
169 globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
170 func = types.FunctionType(run_command.__code__, globals_up, run_command.__name__,run_command.__defaults__, run_command.__closure__)
172 # set the attribute corresponding to the command
173 self.__setattr__(nameCmd, func)
175 def print_help(self, opt):
176 '''Prints help for a command. Function called when "sat -h <command>"
178 :param argv str: the options passed (to get the command name)
180 # if no command as argument (sat -h)
186 # read the configuration from all the pyconf files
187 cfgManager = config.ConfigManager()
188 self.cfg = cfgManager.getConfig(dataDir=self.dataDir)
190 # Check if this command exists
191 if not hasattr(self, command):
192 raise src.SatException(_("Command '%s' does not exist") % command)
194 # Print salomeTools version
198 module = self.get_module(command)
200 # print the description of the command that is done in the command file
201 if hasattr( module, "description" ) :
202 print(src.printcolors.printcHeader( _("Description:") ))
203 print(module.description() + '\n')
205 # print the description of the command options
206 if hasattr( module, "parser" ) :
207 module.parser.print_help()
209 def get_module(self, module):
210 '''Loads a command. Function called only by print_help
212 :param module str: the command to load
214 # Check if this command exists
215 if not hasattr(self, module):
216 raise src.SatException(_("Command '%s' does not exist") % module)
219 (file_, pathname, description) = imp.find_module(module, [cmdsdir])
220 module = imp.load_module(module, file_, pathname, description)
224 '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
227 cfgManager = config.ConfigManager()
228 cfg = cfgManager.getConfig()
229 # print the key corresponding to salomeTools version
230 print(src.printcolors.printcHeader( _("Version: ") ) + cfg.INTERNAL.sat_version + '\n')
234 '''prints salomeTools general help
236 :param options str: the options
240 print(src.printcolors.printcHeader( _("Usage: ") ) + "sat [sat_options] <command> [product] [command_options]\n")
244 # display all the available commands.
245 print(src.printcolors.printcHeader(_("Available commands are:\n")))
246 for command in lCommand:
247 print(" - %s" % (command))
249 # Explain how to get the help for a specific command
250 print(src.printcolors.printcHeader(_("\nGetting the help for a specific command: ")) + "sat --help <command>\n")
252 def write_exception(exc):
253 '''write exception in case of error in a command
255 :param exc exception: the exception to print
257 sys.stderr.write("\n***** ")
258 sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
259 sys.stderr.write("\n" + str(exc) + "\n")
261 # ###############################
262 # MAIN : terminal command usage #
263 # ###############################
264 if __name__ == "__main__":
265 # Initialize the code that will be returned by the terminal command
267 (options, args) = parser.parse_args(sys.argv[1:])
269 # no arguments : print general help
274 # instantiate the salomeTools class with correct options
275 sat = Sat(' '.join(sys.argv[1:]))
278 # get dynamically the command function to call
279 fun_command = sat.__getattr__(command)
280 # call the command with two cases : mode debug or not
281 if options.debug_mode:
282 # call classically the command and if it fails, show exception and stack (usual python mode)
283 code = fun_command(' '.join(args[1:]))
285 # catch exception in order to show less verbose but elegant message
287 code = fun_command(' '.join(args[1:]))
288 except Exception as exc:
292 # exit salomeTools with the right code (0 if no errors, else 1)
293 if code is None: code = 0