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