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