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 srcdir = os.path.dirname(os.path.realpath(__file__))
36 # load resources for internationalization
37 #es = gettext.translation('salomeTools', os.path.join(srcdir, 'common', 'i18n'))
39 gettext.install('salomeTools', os.path.join(srcdir, 'common', 'i18n'))
41 def find_command_list(dirPath):
42 ''' Parse files in dirPath that end with .py : it gives commands list
44 :param dirPath str: The directory path where to search the commands
45 :return: cmd_list : the list containing the commands name
49 for item in os.listdir(dirPath):
50 if item.endswith('.py') and item!='salomeTools.py' and item!='__init__.py':
51 cmd_list.append(item[:-len('.py')])
54 # The list of valid salomeTools commands
55 #lCommand = ['config', 'compile', 'prepare']
56 lCommand = find_command_list(srcdir)
58 # Define all possible option for salomeTools command : sat <option> <args>
59 parser = common.options.Options()
60 parser.add_option('h', 'help', 'boolean', 'help', _("shows global help or help on a specific command."))
61 parser.add_option('o', 'overwrite', 'list', "overwrite", _("overwrites a configuration parameters."))
62 parser.add_option('g', 'debug', 'boolean', 'debug_mode', _("run salomeTools in debug mode."))
64 class salomeTools(object):
65 '''The main class that stores all the commands of salomeTools
67 def __init__(self, opt='', dataDir=None):
70 :param opt str: The sat options
71 :param: dataDir str : the directory that contain all the external data (like software pyconf and software scripts)
73 # Read the salomeTools options (the list of possible options is at the beginning of this file)
75 (options, argus) = parser.parse_args(opt.split(' '))
76 except Exception as exc:
80 # initialization of class attributes
81 self.__dict__ = dict()
82 self.cfg = None # the config that will be read using pyconf module
83 self.options = options # the options passed to salomeTools
84 self.dataDir = dataDir # default value will be <salomeTools root>/data
85 # set the commands by calling the dedicated function
86 self.__setCommands__(srcdir)
88 # if the help option has been called, print help and exit
91 self.print_help(argus)
93 except Exception as exc:
97 def __getattr__(self, name):
98 ''' overwrite of __getattr__ function in order to display a customized message in case of a wrong call
100 :param name str: The name of the attribute
102 if name in self.__dict__:
103 return self.__dict__[name]
105 raise AttributeError(name + _(" is not a valid command"))
107 def __setCommands__(self, dirPath):
108 '''set class attributes corresponding to all commands that are in the dirPath directory
110 :param dirPath str: The directory path containing the commands
112 # loop on the commands name
113 for nameCmd in lCommand:
114 # load the module that has name nameCmd in dirPath
115 (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
116 module = imp.load_module(nameCmd, file_, pathname, description)
118 def run_command(args=''):
119 '''The function that will load the configuration (all pyconf)
120 and return the function run of the command corresponding to module
122 :param args str: The directory path containing the commands
124 argv = args.split(" ")
126 # first argument is the APPLICATION
128 if argv != [''] and argv[0][0] != "-":
129 appliToLoad = argv[0].rstrip('*')
132 # Read the config if it is not already done
134 # read the configuration from all the pyconf files
135 cfgManager = config.ConfigManager()
136 self.cfg = cfgManager.getConfig(dataDir=self.dataDir, application=appliToLoad, options=self.options, command=__nameCmd__)
138 return __module__.run(argv, self)
140 # Make sure that run_command will be redefined at each iteration of the loop
142 globals_up.update(run_command.__globals__)
143 globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
144 func = types.FunctionType(run_command.__code__, globals_up, run_command.__name__,run_command.__defaults__, run_command.__closure__)
146 # set the attribute corresponding to the command
147 self.__setattr__(nameCmd, func)
149 def print_help(self, opt):
150 '''Prints help for a command. Function called when "sat -h <command>"
152 :param argv str: the options passed (to get the command name)
154 # if no command as argument (sat -h)
160 # read the configuration from all the pyconf files
161 cfgManager = config.ConfigManager()
162 self.cfg = cfgManager.getConfig(dataDir=self.dataDir)
164 # Check if this command exists
165 if not hasattr(self, command):
166 raise common.SatException(_("Command '%s' does not exist") % command)
168 # Print salomeTools version
172 module = self.get_module(command)
174 # print the description of the command that is done in the command file
175 if hasattr( module, "description" ) :
176 print(common.printcolors.printcHeader( _("Description:") ))
177 print(module.description() + '\n')
179 # print the description of the command options
180 if hasattr( module, "parser" ) :
181 module.parser.print_help()
183 def get_module(self, module):
184 '''Loads a command. Function called only by print_help
186 :param module str: the command to load
188 # Check if this command exists
189 if not hasattr(self, module):
190 raise common.SatException(_("Command '%s' does not exist") % module)
193 (file_, pathname, description) = imp.find_module(module, [srcdir])
194 module = imp.load_module(module, file_, pathname, description)
198 '''prints salomeTools version (in src/common/internal_config/salomeTools.pyconf)
201 cfgManager = config.ConfigManager()
202 cfg = cfgManager.getConfig()
203 # print the key corresponding to salomeTools version
204 print(common.printcolors.printcHeader( _("Version: ") ) + cfg.INTERNAL.sat_version + '\n')
208 '''prints salomeTools general help
210 :param options str: the options
214 print(common.printcolors.printcHeader( _("Usage: ") ) + "sat [sat_options] <command> [product] [command_options]\n")
218 # display all the available commands.
219 print(common.printcolors.printcHeader(_("Available commands are:\n")))
220 for command in lCommand:
221 print(" - %s" % (command))
223 # Explain how to get the help for a specific command
224 print(common.printcolors.printcHeader(_("\nGetting the help for a specific command: ")) + "sat --help <command>\n")
226 def write_exception(exc):
227 '''write exception in case of error in a command
229 :param exc exception: the exception to print
231 sys.stderr.write("\n***** ")
232 sys.stderr.write(common.printcolors.printcError("salomeTools ERROR:"))
233 sys.stderr.write("\n" + str(exc) + "\n")
235 # ###############################
236 # MAIN : terminal command usage #
237 # ###############################
238 if __name__ == "__main__":
239 # Get the command line using sys.argv
240 cmd_line = " ".join(sys.argv)
241 # Initialize the code that will be returned by the terminal command
243 (options, args) = parser.parse_args(sys.argv[1:])
245 # no arguments : print general help
250 # instantiate the salomeTools class with correct options
251 sat = salomeTools(' '.join(sys.argv[1:]))
254 # get dynamically the command function to call
255 fun_command = sat.__getattr__(command)
256 # call the command with two cases : mode debug or not
257 if options.debug_mode:
258 # call classically the command and if it fails, show exception and stack (usual python mode)
259 code = fun_command(' '.join(args[1:]))
261 # catch exception in order to show less verbose but elegant message
263 code = fun_command(' '.join(args[1:]))
264 except Exception as exc:
268 # exit salomeTools with the right code (0 if no errors, else 1)
269 if code is None: code = 0