File: optiontools.py

package info (click to toggle)
python-happydoc 2.1-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 4,392 kB
  • ctags: 3,480
  • sloc: python: 12,382; makefile: 102; sh: 77
file content (214 lines) | stat: -rw-r--r-- 6,518 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/env python
#
# $Id: optiontools.py,v 1.2 2001/11/25 13:24:20 doughellmann Exp $
#
# Time-stamp: <01/11/25 08:19:50 dhellmann>
#
# Copyright 2001 Doug Hellmann
#
#                         All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of Doug
# Hellmann not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior
# permission.
#
# DOUG HELLMANN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
# NO EVENT SHALL DOUG HELLMANN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

"""Functions for handling options and arguments.

"""

__rcs_info__ = {
    #
    #  Creation Information
    #
    'module_name'  : '$RCSfile: optiontools.py,v $',
    'rcs_id'       : '$Id: optiontools.py,v 1.2 2001/11/25 13:24:20 doughellmann Exp $',
    'creator'      : 'Doug Hellmann <DougHellmann@bigfoot.com>',
    'project'      : 'HappyDoc',
    'created'      : 'Sat, 03-Feb-2001 09:55:18 EST',

    #
    #  Current Information
    #
    'author'       : '$Author: doughellmann $',
    'version'      : '$Revision: 1.2 $',
    'date'         : '$Date: 2001/11/25 13:24:20 $',
}
try:
    __version__ = __rcs_info__['version'].split(' ')[1]
except:
    __version__ = '0.0'

#
# Import system modules
#
import string
import types

#
# Import Local modules
#
from StreamFlushTest import StreamFlushTest

#
# Module
#

def getParameters(prefix, args, prefixSeparator='_'):
    """Find parameter settings in an argument sequence.

    Arguments

      prefix -- Parameter names must begin with this string followed
                by 'prefixSeparator'.

      args -- Sequence containing arguments to scan.

      prefixSeparator -- String separating 'prefix' from actual
                         parameter names.
      
    """
    #
    # What we're going to return
    #
    parameter_set = {}
    ignored_values = []
    #
    # Local variables are faster to access
    #
    ignore = ignored_values.append
    find = string.find
    split = string.split
    prefix_len = len(prefix)
    full_prefix_len = prefix_len + len(prefixSeparator)
    #
    # Process candidates
    #
    for candidate in args:
        #
        # Check that this *is* a parameter
        #
        if find(candidate, '=') < 0:
            ignore(candidate)
            continue
        #
        # Check that this is our parameter
        #
        if candidate[:prefix_len] != prefix:
            ignore(candidate)
            continue
        #
        # Handle the parameter, it's ours.
        #
        param_with_prefix, val = split(candidate, '=')
        param = param_with_prefix[full_prefix_len:]
        parameter_set[param] = val
    return ignored_values, parameter_set



def getBooleanArgumentValue(inputValue):
    """Convert value for a boolean argument into a boolean representation.

    When presented with a representation of a boolean value, convert that
    represetntation to a 1 or 0 and return it.  Currently accepts:

      - integer or floating point values

      - strings (with mixed case) with words 'true', 'false', 'yes',
        'no', 'on', 'off', 'None'

    """
    t = type(inputValue)
    
    if t in ( types.IntType, types.FloatType ):
        #
        # Convert floats to ints
        #
        bool_val = int(inputValue)
        
    elif t == types.StringType:
        #
        # Convert strings with mixed case versions
        # of words that mean true and false.
        #
        lower_input = string.lower(inputValue)
        if lower_input in ('y', 'true', 'yes', 'on'):
            bool_val = 1
        elif lower_input in ('n', 'false', 'no', 'off', 'None'):
            bool_val = 0
        else:
            #
            # Try to interpret the value as 
            try:
                bool_val = int(inputValue)
            except ValueError:
                pass
            
    elif not inputValue:
        #
        # Recognize other types which might indicate false.
        #
        # We do not have a similar test for true because false
        # positives are easier to have happen.
        #
        bool_val = 0
        
    try:
        return bool_val
    except NameError:
        #
        # Wasn't able to get a bool_val, so the name does
        # not resolve.
        #
        raise ValueError('Unrecognized boolean value', inputValue)


class OptionToolTest(StreamFlushTest):

    def testBooleanConversion(self):
        for true_val in ( 1, -1, '1', '-1', 'y', 'Y', 'yes', 'Yes', 'YES',
                          'on', 'On', 'ON', ):
            assert getBooleanArgumentValue(true_val), \
                   'Failed to convert %s to a true value.' % str(true_val)
        for false_val in ( 0, '0', 'n', 'N', 'no', 'No', 'NO',
                           'off', 'Off', 'OFF', ):
            assert not getBooleanArgumentValue(false_val), \
                   'Failed to convert %s to a false value.' % str(false_val)
        

    def testParameterExtraction(self):
        expected_vals = {
            'a':'A',
            'b':'B',
            'longName':'longValue',
            }
        expected_left_overs = [ 'foo', 'blah' ]
        
        left_overs, actual_vals = getParameters( 'foo',
                                                [ 'foo_a=A',
                                                  'foo_b=B',
                                                  'foo_longName=longValue',
                                                  'foo',
                                                  'blah',
                                                  ]
                                                )
        assert actual_vals == expected_vals, \
               'Did not find expected parameters.  Got %s' % str(actual_vals)
        assert left_overs == expected_left_overs, \
               'Did not preserve expected left overs.  Got %s' % str(left_overs)
        return