Salome HOME
78dc0afb6a902bf05567f1ec273d8385d56b8188
[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 gettext.install('salomeTools', os.path.join(srcdir, 'common', 'i18n'))
40
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 
45     :rtype: list
46     '''
47     cmd_list = []
48     for item in os.listdir(dirPath):
49         if item.endswith('.py') and item!='salomeTools.py':
50             cmd_list.append(item[:-len('.py')])
51     return cmd_list
52
53 # The list of valid salomeTools commands
54 #lCommand = ['config', 'compile', 'prepare']
55 lCommand = find_command_list(srcdir)
56
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."))
62
63 class salomeTools(object):
64     '''The main class that stores all the commands of salomeTools
65     '''
66     def __init__(self, opt, dataDir=None):
67         '''Initialization
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)
70         '''
71         # Read the salomeTools options (the list of possible options is at the beginning of this file)
72         try:
73             (options, argus) = parser.parse_args(opt.split(' '))
74         except Exception as exc:
75             write_exception(exc)
76             sys.exit(-1)
77
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)
85         
86         # if the help option has been called, print help and exit
87         if options.help:
88             try:
89                 self.print_help(argus)
90                 sys.exit(0)
91             except Exception as exc:
92                 write_exception(exc)
93                 sys.exit(1)
94
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 
98         '''
99         if name in self.__dict__:
100             return self.__dict__[name]
101         else:
102             raise AttributeError(name + _(" is not a valid command"))
103     
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 
107         '''
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)
113             
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 
118                 '''
119                 argv = args.split(" ")
120                 
121                 # first argument is the APPLICATION
122                 appliToLoad = None
123                 if argv != [''] and argv[0][0] != "-":
124                     appliToLoad = argv[0].rstrip('*')
125                     argv = argv[1:]
126                 
127                 # Read the config if it is not already done
128                 if not self.cfg:
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)
132                 
133                 return __module__.run(argv, self)
134
135             # Make sure that run_command will be redefined at each iteration of the loop
136             globals_up = {}
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__)
140
141             # set the attribute corresponding to the command
142             self.__setattr__(nameCmd, func)
143
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)
147         '''
148         # if no command as argument (sat -h)
149         if len(opt)==0:
150             print_help()
151             return
152         # get command name
153         command = opt[0]
154         # read the configuration from all the pyconf files    
155         cfgManager = config.ConfigManager()
156         self.cfg = cfgManager.getConfig(dataDir=self.dataDir)
157
158         # Check if this command exists
159         if not hasattr(self, command):
160             raise common.SatException(_("Command '%s' does not exist") % command)
161         
162         # Print salomeTools version
163         print_version()
164         
165         # load the module
166         module = self.get_module(command)
167
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')
172
173         # print the description of the command options
174         if hasattr( module, "parser" ) :
175             module.parser.print_help()
176
177     def get_module(self, module):
178         '''Loads a command. Function called only by print_help
179         :param module str: the command to load
180         '''
181         # Check if this command exists
182         if not hasattr(self, module):
183             raise common.SatException(_("Command '%s' does not exist") % module)
184
185         # load the module
186         (file_, pathname, description) = imp.find_module(module, [srcdir])
187         module = imp.load_module(module, file_, pathname, description)
188         return module
189  
190 def print_version():
191     '''prints salomeTools version (in src/common/internal_config/salomeTools.pyconf)
192     '''
193     # read the config 
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')
198
199
200 def print_help():
201     '''prints salomeTools general help
202     :param options str: the options
203     '''
204     print_version()
205     
206     print(common.printcolors.printcHeader( _("Usage: ") ) + "sat [sat_options] <command> [product] [command_options]\n")
207
208     parser.print_help()
209
210     # display all the available commands.
211     print(common.printcolors.printcHeader(_("Available commands are:\n")))
212     for command in lCommand:
213         print(" - %s" % (command))
214         
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")
217
218 def write_exception(exc):
219     '''write exception in case of error in a command
220     :param exc exception: the exception to print
221     '''
222     sys.stderr.write("\n***** ")
223     sys.stderr.write(common.printcolors.printcError("salomeTools ERROR:"))
224     sys.stderr.write("\n" + str(exc) + "\n")
225
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 
233     code = 0
234     (options, args) = parser.parse_args(sys.argv[1:])
235
236     # instantiate the salomeTools class with correct options
237     sat = salomeTools(' '.join(sys.argv[1:]))
238     # the command called
239     command = args[0]
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:]))
246     else:
247         # catch exception in order to show less verbose but elegant message
248         try:
249             code = fun_command(' '.join(args[1:]))
250         except Exception as exc:
251             code = 1
252             write_exception(exc)
253     
254     # exit salomeTools with the right code (0 if no errors, else 1)
255     if code is None: code = 0
256     sys.exit(code)
257