]> SALOME platform Git repositories - tools/sat.git/blob - src/salomeTools.py
Salome HOME
architecture finalization and commentaries for main executable file
[tools/sat.git] / src / salomeTools.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2012  CEA/DEN
4 #
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.
9 #
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.
14 #
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
18
19 '''This file is the main entry file to salomeTools
20 '''
21
22 # python imports
23 import os
24 import sys
25 import imp
26 import types
27 import gettext
28
29 # salomeTools imports
30 import common.options
31 import config
32
33 # get path to salomeTools sources
34 srcdir = os.path.dirname(os.path.realpath(__file__))
35
36 # load resources for internationalization
37 es = gettext.translation('salomeTools', os.path.join(srcdir, 'common', 'i18n'))
38 es.install()
39
40 def find_command_list(dirPath):
41     ''' Parse files in dirPath that end with .py : it gives commands list
42     :param dirPath str: The directory path where to search the commands
43     :return: cmd_list : the list containing the commands name 
44     :rtype: list
45     '''
46     cmd_list = []
47     for item in os.listdir(dirPath):
48         if item.endswith('.py') and item!='salomeTools.py':
49             cmd_list.append(item[:-len('.py')])
50     return cmd_list
51
52 # The list of valid salomeTools commands
53 #lCommand = ['config', 'compile', 'prepare']
54 lCommand = find_command_list(srcdir)
55
56 # Define all possible option for salomeTools command :  sat <option> <args>
57 parser = common.options.Options()
58 parser.add_option('h', 'help', 'boolean', 'help', _("shows global help or help on a specific command."))
59 parser.add_option('o', 'overwrite', 'list', "overwrite", _("overwrites a configuration parameters."))
60 parser.add_option('g', 'debug', 'boolean', 'debug_mode', _("run salomeTools in debug mode."))
61
62 class salomeTools(object):
63     '''The main class that stores all the commands of salomeTools
64     '''
65     def __init__(self, opt, dataDir=None):
66         '''Initialization
67         :param opt str: The sat options 
68         :param: dataDir str : the directory that contain all the external data (like software pyconf and software scripts)
69         '''
70         # Read the salomeTools options (the list of possible options is at the beginning of this file)
71         try:
72             (options, argus) = parser.parse_args(opt.split(' '))
73         except Exception as exc:
74             write_exception(exc)
75             sys.exit(-1)
76
77         # initialization of class attributes       
78         self.__dict__ = dict()
79         self.cfg = None # the config that will be read using config_pyconf module
80         self.options = options # the options passed to salomeTools
81         self.dataDir = dataDir # default value will be <salomeTools root>/data
82         # set the commands by calling the dedicated function
83         self.__setCommands__(srcdir)
84         
85         # if the help option has been called, print help and exit
86         if options.help:
87             try:
88                 self.print_help(argus)
89                 sys.exit(0)
90             except Exception as exc:
91                 write_exception(exc)
92                 sys.exit(1)
93
94     def __getattr__(self, name):
95         ''' overwrite of __getattr__ function in order to display a customized message in case of a wrong call
96         :param name str: The name of the attribute 
97         '''
98         if name in self.__dict__:
99             return self.__dict__[name]
100         else:
101             raise AttributeError(name + _(" is not a valid command"))
102     
103     def __setCommands__(self, dirPath):
104         '''set class attributes corresponding to all commands that are in the dirPath directory
105         :param dirPath str: The directory path containing the commands 
106         '''
107         # loop on the commands name
108         for nameCmd in lCommand:
109             # load the module that has name nameCmd in dirPath
110             (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
111             module = imp.load_module(nameCmd, file_, pathname, description)
112             
113             def run_command(args):
114                 '''The function that will load the configuration (all pyconf)
115                 and return the function run of the command corresponding to module
116                 :param args str: The directory path containing the commands 
117                 '''
118                 argv = args.split(" ")
119                 
120                 # first argument is the APPLICATION
121                 appliToLoad = None
122                 if argv != [''] and argv[0][0] != "-":
123                     appliToLoad = argv[0].rstrip('*')
124                     argv = argv[1:]
125                 
126                 # Read the config if it is not already done
127                 if not self.cfg:
128                     # read the configuration from all the pyconf files    
129                     cfgManager = config.ConfigManager()
130                     self.cfg = cfgManager.getConfig(dataDir=self.dataDir, application=appliToLoad, options=self.options)
131                 
132                 return __module__.run(argv, self)
133
134             # Make sure that run_command will be redefined at each iteration of the loop
135             globals_up = {}
136             globals_up.update(run_command.__globals__)
137             globals_up.update({'__name__': nameCmd, '__module__' : module})
138             func = types.FunctionType(run_command.__code__, globals_up, run_command.__name__,run_command.__defaults__, run_command.__closure__)
139
140             # set the attribute corresponding to the command
141             self.__setattr__(nameCmd, func)
142
143     def print_help(self, opt):
144         '''Prints help for a command. Function called when "sat -h <command>"
145         :param argv str: the options passed (to get the command name)
146         '''
147         # if no command as argument (sat -h)
148         if len(opt)==0:
149             print_help()
150             return
151         # get command name
152         command = opt[0]
153         # read the configuration from all the pyconf files    
154         cfgManager = config.ConfigManager()
155         self.cfg = cfgManager.getConfig(dataDir=self.dataDir)
156
157         # Check if this command exists
158         if not hasattr(self, command):
159             raise common.SatException(_("Command '%s' does not exist") % command)
160         
161         # Print salomeTools version
162         print_version()
163         
164         # load the module
165         module = self.get_module(command)
166
167         # print the description of the command that is done in the command file
168         if hasattr( module, "description" ) :
169             print(common.printcolors.printcHeader( _("Description:") ))
170             print(module.description() + '\n')
171
172         # print the description of the command options
173         if hasattr( module, "parser" ) :
174             module.parser.print_help()
175
176     def get_module(self, module):
177         '''Loads a command. Function called only by print_help
178         :param module str: the command to load
179         '''
180         # Check if this command exists
181         if not hasattr(self, module):
182             raise common.SatException(_("Command '%s' does not exist") % module)
183
184         # load the module
185         (file_, pathname, description) = imp.find_module(module, [srcdir])
186         module = imp.load_module(module, file_, pathname, description)
187         return module
188  
189 def print_version():
190     '''prints salomeTools version (in src/common/internal_config/salomeTools.pyconf)
191     '''
192     # read the config 
193     cfgManager = config.ConfigManager()
194     cfg = cfgManager.getConfig()
195     # print the key corresponding to salomeTools version
196     print(common.printcolors.printcHeader( _("Version: ") ) + cfg.INTERNAL.sat_version + '\n')
197
198
199 def print_help():
200     '''prints salomeTools general help
201     :param options str: the options
202     '''
203     print_version()
204     
205     print(common.printcolors.printcHeader( _("Usage: ") ) + "sat [sat_options] <command> [product] [command_options]\n")
206
207     parser.print_help()
208
209     # display all the available commands.
210     print(common.printcolors.printcHeader(_("Available commands are:\n")))
211     for command in lCommand:
212         print(" - %s" % (command))
213         
214     # Explain how to get the help for a specific command
215     print(common.printcolors.printcHeader(_("\nGetting the help for a specific command: ")) + "sat --help <command>\n")
216
217 def write_exception(exc):
218     '''write exception in case of error in a command
219     :param exc exception: the exception to print
220     '''
221     sys.stderr.write("\n***** ")
222     sys.stderr.write(common.printcolors.printcError("salomeTools ERROR:"))
223     sys.stderr.write("\n" + str(exc) + "\n")
224
225 # ###############################
226 # MAIN : terminal command usage #
227 # ###############################
228 if __name__ == "__main__":  
229     # Get the command line using sys.argv
230     cmd_line = " ".join(sys.argv)
231     # Initialize the code that will be returned by the terminal command 
232     code = 0
233     (options, args) = parser.parse_args(sys.argv[1:])
234
235     # instantiate the salomeTools class with correct options
236     sat = salomeTools(' '.join(sys.argv[1:]))
237     # the command called
238     command = args[0]
239     # get dynamically the command function to call
240     fun_command = sat.__getattr__(command)
241     if options.debug_mode:
242         # call classically the command and if it fails, show exception and stack (usual python mode)
243         code = fun_command(' '.join(args[1:]))
244     else:
245         # catch exception in order to show less verbose but elegant message
246         try:
247             code = fun_command(' '.join(args[1:]))
248         except Exception as exc:
249             code = 1
250             write_exception(exc)
251     
252     # exit salomeTools with the right code (0 if no errors, else 1)
253     if code is None: code = 0
254     sys.exit(code)
255