Salome HOME
bbfa571d501a89fdadd8832c4a0ac5b2796de75f
[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 common.options
27 import config
28
29 def copy_func(f, name=None):
30     '''
31     return a function with same code, globals, defaults, closure, and 
32     name (or provide a new name)
33     '''
34
35     fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
36         f.__defaults__, f.__closure__)
37     # in case f was given attrs (note this dict is a shallow copy):
38     fn.__dict__.update(f.__dict__) 
39     return fn
40
41 # get path to salomeTools sources
42 srcdir = os.path.dirname(os.path.realpath(__file__))
43
44 def find_command_list():
45     cmd_list = []
46     for item in os.listdir(srcdir):
47         if item.endswith('.py') and item!='salomeTools.py':
48             cmd_list.append(item[:-len('.py')])
49     return cmd_list
50
51 # The list of valid salomeTools commands
52 #lCommand = ['config', 'compile', 'prepare']
53 lCommand = find_command_list()
54
55 # Define all possible option for salomeTools command :  sat <option> <args>
56 parser = common.options.Options()
57 parser.add_option('h', 'help', 'boolean', 'help', "shows global help or help on a specific command.")
58
59 class salomeTools(object):
60     def __init__(self, options, dataDir=None):
61         '''Initialization
62         '''
63         self.__dict__ = dict()
64         self.options = options
65         self.dataDir = dataDir
66         # set the commands
67         self.__setCommands__(srcdir)
68
69     def __getattr__(self, name):
70         if name in self.__dict__:
71             return self.__dict__[name]
72         else:
73             raise AttributeError(name + " is not a valid command")
74
75     def __setattr__(self, name, value):
76         object.__setattr__(self,name,value)
77
78     def __setCommands__(self, dirPath):
79         for nameCmd in lCommand:
80             (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
81             module = imp.load_module(nameCmd, file_, pathname, description)
82                        
83             def run_command(args):
84                 print('Je suis dans l\'initialisation de la commande ' + __name__)
85                 argv = args.split(" ")
86                 
87                 # first argument is the APPLICATION
88                 appliToLoad = None
89                 if len(argv) > 0 and argv[0][0] != "-":
90                     appliToLoad = argv[0].rstrip('*')
91                     argv = argv[1:]
92                 
93                 # read the configuration from all the pyconf files    
94                 cfgManager = config.ConfigManager()
95                 self.cfg = cfgManager.getConfig(dataDir=self.dataDir, application=appliToLoad)
96                 
97                 return __module__.run(argv, self)
98
99             globals_up = {}
100             globals_up.update(run_command.__globals__)
101             globals_up.update({'__name__': nameCmd, '__module__' : module})
102             fn = types.FunctionType(run_command.__code__, globals_up, run_command.__name__,run_command.__defaults__, run_command.__closure__)
103
104             self.__setattr__(nameCmd, fn)
105              
106
107
108
109 def print_help(options):
110     #from config import ConfigManager
111     #cfgManager = ConfigManager(STAND_ALONE_VERSION)
112     #cfg = cfgManager.getConfig(None, options)
113     #print_version(cfg)
114     #print
115
116     print(common.printcolors.printcHeader( "Usage: " ) + "sat [sat_options] <command> [product] [command_options]\n")
117
118     parser.print_help()
119
120     # parse the src directory to list the available commands.
121     print(common.printcolors.printcHeader("Available commands are:\n"))
122     for command in lCommand:
123         print(" - %s" % (command))
124
125     print(common.printcolors.printcHeader("\nGetting the help for a specific command: " + "sat --help <command>\n"))
126
127 def write_exception(exc):
128     sys.stderr.write("\n***** ")
129     sys.stderr.write(common.printcolors.printcError("salomeTools ERROR:"))
130     sys.stderr.write("\n" + str(exc) + "\n")
131
132 # ###############################
133 # MAIN : terminal command usage #
134 # ###############################
135 if __name__ == "__main__":  
136     # Get the command line using sys.argv
137     cmd_line = " ".join(sys.argv)
138     # Initialize the code that will be returned by the terminal command 
139     code = 0
140     
141     # Read the salomeTools options (the list of possible options is at the beginning of this file)
142     try:
143         (options, args) = parser.parse_args(sys.argv[1:])
144     except Exception as exc:
145         write_exception(exc)
146         sys.exit(-1)
147     
148     if len(args) == 0:
149         # no options => show help
150         print_help(options)
151     
152     sat = salomeTools('')
153     sat.config('-v VARS.python')
154     
155
156