Salome HOME
Remarks from sprint 1 : do not consider 32/64 bits, have only one user config 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 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     
44     :param dirPath str: The directory path where to search the commands
45     :return: cmd_list : the list containing the commands name 
46     :rtype: list
47     '''
48     cmd_list = []
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')])
52     return cmd_list
53
54 # The list of valid salomeTools commands
55 #lCommand = ['config', 'compile', 'prepare']
56 lCommand = find_command_list(srcdir)
57
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."))
63
64 class salomeTools(object):
65     '''The main class that stores all the commands of salomeTools
66     '''
67     def __init__(self, opt='', dataDir=None):
68         '''Initialization
69         
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)
72         '''
73         # Read the salomeTools options (the list of possible options is at the beginning of this file)
74         try:
75             (options, argus) = parser.parse_args(opt.split(' '))
76         except Exception as exc:
77             write_exception(exc)
78             sys.exit(-1)
79
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)
87         
88         # if the help option has been called, print help and exit
89         if options.help:
90             try:
91                 self.print_help(argus)
92                 sys.exit(0)
93             except Exception as exc:
94                 write_exception(exc)
95                 sys.exit(1)
96
97     def __getattr__(self, name):
98         ''' overwrite of __getattr__ function in order to display a customized message in case of a wrong call
99         
100         :param name str: The name of the attribute 
101         '''
102         if name in self.__dict__:
103             return self.__dict__[name]
104         else:
105             raise AttributeError(name + _(" is not a valid command"))
106     
107     def __setCommands__(self, dirPath):
108         '''set class attributes corresponding to all commands that are in the dirPath directory
109         
110         :param dirPath str: The directory path containing the commands 
111         '''
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)
117             
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
121                 
122                 :param args str: The directory path containing the commands 
123                 '''
124                 argv = args.split(" ")
125                 
126                 # if it is provided by the command line, get the application
127                 appliToLoad = None
128                 if argv != [''] and argv[0][0] != "-":
129                     appliToLoad = argv[0].rstrip('*')
130                     argv = argv[1:]
131                 
132                 # Read the config if it is not already done
133                 if not self.cfg:
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__)
137                 
138                 return __module__.run(argv, self)
139
140             # Make sure that run_command will be redefined at each iteration of the loop
141             globals_up = {}
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__)
145
146             # set the attribute corresponding to the command
147             self.__setattr__(nameCmd, func)
148
149     def print_help(self, opt):
150         '''Prints help for a command. Function called when "sat -h <command>"
151         
152         :param argv str: the options passed (to get the command name)
153         '''
154         # if no command as argument (sat -h)
155         if len(opt)==0:
156             print_help()
157             return
158         # get command name
159         command = opt[0]
160         # read the configuration from all the pyconf files    
161         cfgManager = config.ConfigManager()
162         self.cfg = cfgManager.getConfig(dataDir=self.dataDir)
163
164         # Check if this command exists
165         if not hasattr(self, command):
166             raise common.SatException(_("Command '%s' does not exist") % command)
167         
168         # Print salomeTools version
169         print_version()
170         
171         # load the module
172         module = self.get_module(command)
173
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')
178
179         # print the description of the command options
180         if hasattr( module, "parser" ) :
181             module.parser.print_help()
182
183     def get_module(self, module):
184         '''Loads a command. Function called only by print_help
185         
186         :param module str: the command to load
187         '''
188         # Check if this command exists
189         if not hasattr(self, module):
190             raise common.SatException(_("Command '%s' does not exist") % module)
191
192         # load the module
193         (file_, pathname, description) = imp.find_module(module, [srcdir])
194         module = imp.load_module(module, file_, pathname, description)
195         return module
196  
197 def print_version():
198     '''prints salomeTools version (in src/common/internal_config/salomeTools.pyconf)
199     '''
200     # read the config 
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')
205
206
207 def print_help():
208     '''prints salomeTools general help
209     
210     :param options str: the options
211     '''
212     print_version()
213     
214     print(common.printcolors.printcHeader( _("Usage: ") ) + "sat [sat_options] <command> [product] [command_options]\n")
215
216     parser.print_help()
217
218     # display all the available commands.
219     print(common.printcolors.printcHeader(_("Available commands are:\n")))
220     for command in lCommand:
221         print(" - %s" % (command))
222         
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")
225
226 def write_exception(exc):
227     '''write exception in case of error in a command
228     
229     :param exc exception: the exception to print
230     '''
231     sys.stderr.write("\n***** ")
232     sys.stderr.write(common.printcolors.printcError("salomeTools ERROR:"))
233     sys.stderr.write("\n" + str(exc) + "\n")
234
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 
242     code = 0
243     (options, args) = parser.parse_args(sys.argv[1:])
244     
245     # no arguments : print general help
246     if len(args) == 0:
247         print_help()
248         sys.exit(0)
249     
250     # instantiate the salomeTools class with correct options
251     sat = salomeTools(' '.join(sys.argv[1:]))
252     # the command called
253     command = args[0]
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:]))
260     else:
261         # catch exception in order to show less verbose but elegant message
262         try:
263             code = fun_command(' '.join(args[1:]))
264         except Exception as exc:
265             code = 1
266             write_exception(exc)
267     
268     # exit salomeTools with the right code (0 if no errors, else 1)
269     if code is None: code = 0
270     sys.exit(code)
271