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