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
43 :param dirPath str: The directory path where to search the commands
44 :return: cmd_list : the list containing the commands name
48 for item in os.listdir(dirPath):
49 if item.endswith('.py') and item!='salomeTools.py':
50 cmd_list.append(item[:-len('.py')])
53 # The list of valid salomeTools commands
54 #lCommand = ['config', 'compile', 'prepare']
55 lCommand = find_command_list(srcdir)
57 # Define all possible option for salomeTools command : sat <option> <args>
58 parser = common.options.Options()
59 parser.add_option('h', 'help', 'boolean', 'help', _("shows global help or help on a specific command."))
60 parser.add_option('o', 'overwrite', 'list', "overwrite", _("overwrites a configuration parameters."))
61 parser.add_option('g', 'debug', 'boolean', 'debug_mode', _("run salomeTools in debug mode."))
63 class salomeTools(object):
64 '''The main class that stores all the commands of salomeTools
66 def __init__(self, opt, dataDir=None):
68 :param opt str: The sat options
69 :param: dataDir str : the directory that contain all the external data (like software pyconf and software scripts)
71 # Read the salomeTools options (the list of possible options is at the beginning of this file)
73 (options, argus) = parser.parse_args(opt.split(' '))
74 except Exception as exc:
78 # initialization of class attributes
79 self.__dict__ = dict()
80 self.cfg = None # the config that will be read using config_pyconf module
81 self.options = options # the options passed to salomeTools
82 self.dataDir = dataDir # default value will be <salomeTools root>/data
83 # set the commands by calling the dedicated function
84 self.__setCommands__(srcdir)
86 # if the help option has been called, print help and exit
89 self.print_help(argus)
91 except Exception as exc:
95 def __getattr__(self, name):
96 ''' overwrite of __getattr__ function in order to display a customized message in case of a wrong call
97 :param name str: The name of the attribute
99 if name in self.__dict__:
100 return self.__dict__[name]
102 raise AttributeError(name + _(" is not a valid command"))
104 def __setCommands__(self, dirPath):
105 '''set class attributes corresponding to all commands that are in the dirPath directory
106 :param dirPath str: The directory path containing the commands
108 # loop on the commands name
109 for nameCmd in lCommand:
110 # load the module that has name nameCmd in dirPath
111 (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
112 module = imp.load_module(nameCmd, file_, pathname, description)
114 def run_command(args):
115 '''The function that will load the configuration (all pyconf)
116 and return the function run of the command corresponding to module
117 :param args str: The directory path containing the commands
119 argv = args.split(" ")
121 # first argument is the APPLICATION
123 if argv != [''] and argv[0][0] != "-":
124 appliToLoad = argv[0].rstrip('*')
127 # Read the config if it is not already done
129 # read the configuration from all the pyconf files
130 cfgManager = config.ConfigManager()
131 self.cfg = cfgManager.getConfig(dataDir=self.dataDir, application=appliToLoad, options=self.options)
133 return __module__.run(argv, self)
135 # Make sure that run_command will be redefined at each iteration of the loop
137 globals_up.update(run_command.__globals__)
138 globals_up.update({'__name__': nameCmd, '__module__' : module})
139 func = types.FunctionType(run_command.__code__, globals_up, run_command.__name__,run_command.__defaults__, run_command.__closure__)
141 # set the attribute corresponding to the command
142 self.__setattr__(nameCmd, func)
144 def print_help(self, opt):
145 '''Prints help for a command. Function called when "sat -h <command>"
146 :param argv str: the options passed (to get the command name)
148 # if no command as argument (sat -h)
154 # read the configuration from all the pyconf files
155 cfgManager = config.ConfigManager()
156 self.cfg = cfgManager.getConfig(dataDir=self.dataDir)
158 # Check if this command exists
159 if not hasattr(self, command):
160 raise common.SatException(_("Command '%s' does not exist") % command)
162 # Print salomeTools version
166 module = self.get_module(command)
168 # print the description of the command that is done in the command file
169 if hasattr( module, "description" ) :
170 print(common.printcolors.printcHeader( _("Description:") ))
171 print(module.description() + '\n')
173 # print the description of the command options
174 if hasattr( module, "parser" ) :
175 module.parser.print_help()
177 def get_module(self, module):
178 '''Loads a command. Function called only by print_help
179 :param module str: the command to load
181 # Check if this command exists
182 if not hasattr(self, module):
183 raise common.SatException(_("Command '%s' does not exist") % module)
186 (file_, pathname, description) = imp.find_module(module, [srcdir])
187 module = imp.load_module(module, file_, pathname, description)
191 '''prints salomeTools version (in src/common/internal_config/salomeTools.pyconf)
194 cfgManager = config.ConfigManager()
195 cfg = cfgManager.getConfig()
196 # print the key corresponding to salomeTools version
197 print(common.printcolors.printcHeader( _("Version: ") ) + cfg.INTERNAL.sat_version + '\n')
201 '''prints salomeTools general help
202 :param options str: the options
206 print(common.printcolors.printcHeader( _("Usage: ") ) + "sat [sat_options] <command> [product] [command_options]\n")
210 # display all the available commands.
211 print(common.printcolors.printcHeader(_("Available commands are:\n")))
212 for command in lCommand:
213 print(" - %s" % (command))
215 # Explain how to get the help for a specific command
216 print(common.printcolors.printcHeader(_("\nGetting the help for a specific command: ")) + "sat --help <command>\n")
218 def write_exception(exc):
219 '''write exception in case of error in a command
220 :param exc exception: the exception to print
222 sys.stderr.write("\n***** ")
223 sys.stderr.write(common.printcolors.printcError("salomeTools ERROR:"))
224 sys.stderr.write("\n" + str(exc) + "\n")
226 # ###############################
227 # MAIN : terminal command usage #
228 # ###############################
229 if __name__ == "__main__":
230 # Get the command line using sys.argv
231 cmd_line = " ".join(sys.argv)
232 # Initialize the code that will be returned by the terminal command
234 (options, args) = parser.parse_args(sys.argv[1:])
236 # instantiate the salomeTools class with correct options
237 sat = salomeTools(' '.join(sys.argv[1:]))
240 # get dynamically the command function to call
241 fun_command = sat.__getattr__(command)
242 # call the command with two cases : mode debug or not
243 if options.debug_mode:
244 # call classically the command and if it fails, show exception and stack (usual python mode)
245 code = fun_command(' '.join(args[1:]))
247 # catch exception in order to show less verbose but elegant message
249 code = fun_command(' '.join(args[1:]))
250 except Exception as exc:
254 # exit salomeTools with the right code (0 if no errors, else 1)
255 if code is None: code = 0