Salome HOME
suppresion d'un log
[tools/sat.git] / src / options.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  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 '''The Options class that manages the access to all options passed as 
19    parameters in salomeTools command lines
20 '''
21 import getopt
22 import sys
23 from . import printcolors
24
25 class OptResult(object):
26     '''An instance of this class will be the object manipulated
27        in code of all salomeTools commands
28        The aim of this class is to have an elegant syntax 
29        to manipulate the options. 
30        ex: 
31        print(options.level)
32        5
33     '''
34     def __init__(self):
35         '''Initialization
36         '''
37         self.__dict__ = dict()
38
39     def __getattr__(self, name):
40         '''Overwrite of the __getattr__ function 
41            to customize it for option usage
42         
43         :param name str: The attribute to get the value.
44         :return: the value corresponding to the attribute.
45         :rtype: str,int,list,boolean
46         '''
47         if name in self.__dict__:
48             return self.__dict__[name]
49         else:
50             raise AttributeError(name + _(u" is not a valid option"))
51
52     def __setattr__(self, name, value):
53         '''Overwrite of the __setattr__ function 
54            to customize it for option usage
55         
56         :param name str: The attribute to set.
57         :param value str: The value  corresponding to the attribute.
58         :return: Nothing.
59         :rtype: N\A
60         '''
61         object.__setattr__(self,name,value)
62
63 class Options:
64     '''Class to manage all salomeTools options
65     '''
66     def __init__(self):
67         '''Initialization
68         '''
69         # The options field stocks all options of a command 
70         # in a list that contains dicts
71         self.options = []
72         # The list of available option type
73         self.availableOptions = ["boolean", "string", "int", "float",
74                                   "long", "list", "list2"]
75         self.default = None
76
77     def add_option(self, shortName, longName,
78                     optionType, destName, helpString="", default = None):
79         '''Method to add an option to a command. It gets all attributes
80            of an option and append it in the options field
81         
82         :param shortName str: The short name of the option
83                               (ex "l" for level option).
84         :param longName str: The long name of the option 
85                              (ex "level" for level option).
86         :param optionType str: The type of the option (ex "int").
87         :param destName str: The name that will be used in the code.
88         :param helpString str: The text to display 
89                                when user ask for help on a command.     
90         :return: Nothing.
91         :rtype: N\A
92         '''
93         option = dict()
94         option['shortName'] = shortName
95         option['longName'] = longName
96
97         if optionType not in self.availableOptions:
98             print("error optionType", optionType, "not available.")
99             sys.exit(-1)
100
101         option['optionType'] = optionType
102         option['destName'] = destName
103         option['helpString'] = helpString
104         option['result'] = default
105         self.options.append(option)
106
107     def print_help(self):
108         '''Method that display all options stored in self.options and there help
109         
110         :return: Nothing.
111         :rtype: N\A
112         '''
113         # Do nothing if there are no options
114         if len(self.options) == 0:
115             return
116
117         # for all options, print its values. 
118         # "shortname" is an optional field of the options 
119         print(printcolors.printcHeader(_("Available options are:")))
120         for option in self.options:
121             if 'shortName' in option and len(option['shortName']) > 0:
122                 print(" -%(shortName)1s, --%(longName)s"
123                       " (%(optionType)s)\n\t%(helpString)s\n" % option)
124             else:
125                 print(" --%(longName)s (%(optionType)s)\n\t%(helpString)s\n"
126                        % option)
127
128     def parse_args(self, argList=None):
129         '''Method that instantiates the class OptResult 
130            that gives access to all options in the code
131         
132         :param argList list: the raw list of arguments that were passed
133         :return: optResult, args : optResult is the option instance 
134                                    to manipulate in the code. args 
135                                    is the full raw list of passed options 
136         :rtype: (class 'common.options.OptResult',list)
137         '''
138         if argList is None:
139             argList = sys.argv[1:]
140         
141         # format shortNameOption and longNameOption 
142         # to make right arguments to getopt.getopt function
143         shortNameOption = ""
144         longNameOption = []
145         for option in self.options:
146             shortNameOption = shortNameOption + option['shortName']
147             if option['shortName'] != "" and option['optionType'] != "boolean":
148                 shortNameOption = shortNameOption + ":"
149
150             if option['longName'] != "":
151                 if option['optionType'] != "boolean":
152                     longNameOption.append(option['longName'] + "=")
153                 else:
154                     longNameOption.append(option['longName'])
155
156         # call to getopt.getopt function to get the option 
157         # passed in the command regarding the available options
158         optlist, args = getopt.getopt(argList, shortNameOption, longNameOption)
159         
160         # instantiate and completing the optResult that will be returned
161         optResult = OptResult()
162         for option in self.options:
163             shortOption = "-" + option['shortName']
164             longOption = "--" + option['longName']
165             optionType = option['optionType']
166             for opt in optlist:
167                 if opt[0] in [shortOption, longOption]:
168                     if optionType == "string":
169                         option['result'] = opt[1]
170                     elif optionType == "boolean":
171                         option['result'] = True
172                     elif optionType == "int":
173                         option['result'] = int(opt[1])
174                     elif optionType == "float":
175                         option['result'] = float(opt[1])
176                     elif optionType == "long":
177                         option['result'] = long(opt[1])
178                     elif optionType == "list":
179                         if option['result'] is None:
180                             option['result'] = list()
181                         option['result'].append(opt[1])
182                     elif optionType == "list2":
183                         if option['result'] is None:
184                             option['result'] = list()
185                         if opt[1].find(",") == -1:
186                             option['result'].append(opt[1])
187                         else:
188                             elts = filter(lambda l: len(l) > 0, opt[1].split(","))
189                             option['result'].extend(elts)
190
191             optResult.__setattr__(option['destName'], option['result'])
192             # free the option in order to be able to make 
193             # a new free call of options (API case)
194             option['result'] = None
195         return optResult, args
196