Salome HOME
Add help prints and terminal command mechanism
[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 import os
23 import sys
24 import imp
25 import types
26 import gettext
27
28 import common.options
29 import config
30
31 # get path to salomeTools sources
32 srcdir = os.path.dirname(os.path.realpath(__file__))
33
34 # load resources for internationalization
35 #gettext.install('salomeTools', os.path.join(srcdir, 'common', 'i18n'))
36
37 es = gettext.translation('salomeTools', os.path.join(srcdir, 'common', 'i18n'))
38 es.install()
39
40 def find_command_list():
41     cmd_list = []
42     for item in os.listdir(srcdir):
43         if item.endswith('.py') and item!='salomeTools.py':
44             cmd_list.append(item[:-len('.py')])
45     return cmd_list
46
47 # The list of valid salomeTools commands
48 #lCommand = ['config', 'compile', 'prepare']
49 lCommand = find_command_list()
50
51 # Define all possible option for salomeTools command :  sat <option> <args>
52 parser = common.options.Options()
53 parser.add_option('h', 'help', 'boolean', 'help', _(u"shows global help or help on a specific command."))
54
55 class salomeTools(object):
56     def __init__(self, opt, dataDir=None):
57         '''Initialization
58         '''
59         # Read the salomeTools options (the list of possible options is at the beginning of this file)
60         try:
61             (options, args) = parser.parse_args(opt)
62         except Exception as exc:
63             write_exception(exc)
64             sys.exit(-1)
65                            
66         self.__dict__ = dict()
67         self.options = options
68         self.dataDir = dataDir
69         # set the commands
70         self.__setCommands__(srcdir)
71         
72         if options.help:
73             try:
74                 self.print_help(args)
75                 sys.exit(0)
76             except Exception as exc:
77                 code = 1
78                 write_exception(exc)
79
80     def __getattr__(self, name):
81         if name in self.__dict__:
82             return self.__dict__[name]
83         else:
84             raise AttributeError(name + _(" is not a valid command"))
85
86     def __setattr__(self, name, value):
87         object.__setattr__(self,name,value)
88
89
90     def __setCommands__(self, dirPath):
91         for nameCmd in lCommand:
92             (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
93             module = imp.load_module(nameCmd, file_, pathname, description)
94
95             def run_command(args):
96                 print('Je suis dans l\'initialisation de la commande ' + __name__)
97                 argv = args.split(" ")
98                 
99                 # first argument is the APPLICATION
100                 appliToLoad = None
101                 if len(argv) > 0 and argv[0][0] != "-":
102                     appliToLoad = argv[0].rstrip('*')
103                     argv = argv[1:]
104                 
105                 # read the configuration from all the pyconf files    
106                 cfgManager = config.ConfigManager()
107                 self.cfg = cfgManager.getConfig(dataDir=self.dataDir, application=appliToLoad)
108                 
109                 return __module__.run(argv, self)
110
111             globals_up = {}
112             globals_up.update(run_command.__globals__)
113             globals_up.update({'__name__': nameCmd, '__module__' : module})
114             func = types.FunctionType(run_command.__code__, globals_up, run_command.__name__,run_command.__defaults__, run_command.__closure__)
115
116             self.__setattr__(nameCmd, func)
117
118     def print_help(self, argv):
119         '''Prints help for a command
120         '''
121         command = argv[0]
122         # read the configuration from all the pyconf files    
123         cfgManager = config.ConfigManager()
124         self.cfg = cfgManager.getConfig(dataDir=self.dataDir)
125
126         if not hasattr(self, command):
127             raise common.SatException(_("Command '%s' does not exist") % command)
128
129         print_version()
130         
131         module = self.get_module(command)
132
133         if hasattr( module, "description" ) :
134             print(common.printcolors.printcHeader( _("Description:") ))
135             print(module.description() + '\n')
136
137         if hasattr( module, "parser" ) :
138             module.parser.print_help()
139
140     def get_module(self, module):
141         if not hasattr(self, module):
142             raise common.SatException(_("Command '%s' does not exist") % module)
143
144         # reduce variables substitution and so on
145         (file_, pathname, description) = imp.find_module(module, [srcdir])
146         module = imp.load_module(module, file_, pathname, description)
147         return module
148  
149 def print_version():
150     cfgManager = config.ConfigManager()
151     cfg = cfgManager.getConfig()
152     print(common.printcolors.printcHeader( _("Version: ") ) + cfg.INTERNAL.sat_version + '\n')
153
154
155 def print_help(options):
156     print_version()
157     
158     print(common.printcolors.printcHeader( _("Usage: ") ) + "sat [sat_options] <command> [product] [command_options]\n")
159
160     parser.print_help()
161
162     # parse the src directory to list the available commands.
163     print(common.printcolors.printcHeader(_("Available commands are:\n")))
164     for command in lCommand:
165         print(" - %s" % (command))
166
167     print(common.printcolors.printcHeader(_(u"\nGetting the help for a specific command: ")) + "sat --help <command>\n")
168
169 def write_exception(exc):
170     sys.stderr.write("\n***** ")
171     sys.stderr.write(common.printcolors.printcError("salomeTools ERROR:"))
172     sys.stderr.write("\n" + str(exc) + "\n")
173
174 # ###############################
175 # MAIN : terminal command usage #
176 # ###############################
177 if __name__ == "__main__":  
178     # Get the command line using sys.argv
179     cmd_line = " ".join(sys.argv)
180     # Initialize the code that will be returned by the terminal command 
181     code = 0
182
183     (options, args) = parser.parse_args(sys.argv[1:])
184     
185     if len(args) == 0:
186         # no options => show help
187         print_help(options)
188     else:
189         sat = salomeTools(sys.argv[1:])
190         command = args[0]
191         fun_command = sat.__getattr__(command)
192         if len(args[1:]) == 0:
193             print(common.printcolors.printcWarning(_("No arguments")))
194             sys.exit(0)
195         fun_command(' '.join(args[1:]))
196
197     
198
199