-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy patharguments.py
278 lines (203 loc) · 7.75 KB
/
arguments.py
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# swift_build_support/arguments.py ------------------------------*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ----------------------------------------------------------------------------
"""
argparse supplements
"""
# ----------------------------------------------------------------------------
from __future__ import absolute_import
import argparse
import os
import re
import shlex
__all__ = [
"action",
"type",
]
class _Registry(object):
pass
def _register(registry, name, value):
setattr(registry, name, value)
# Types ----------------------------------------------------------------------
type = _Registry()
def type_bool(string):
"""
A strict parser for bools
unlike Python's `bool()`, where `bool('False')` is `True`
This function can be passed as `type=` argument to argparse to parse values
passed to command line arguments.
"""
if string in ['0', 'false', 'False']:
return False
if string in ['1', 'true', 'True']:
return True
raise argparse.ArgumentTypeError("%r is not a boolean value" % string)
_register(type, 'bool', type_bool)
def type_shell_split(string):
"""
Parse and split shell arguments string into a list of shell arguments.
Recognize `,` as a separator as well as white spaces.
string: -BAR="foo bar" -BAZ='foo,bar',-QUX 42
into
['-BAR=foo bar', '-BAZ=foo,bar', "-QUX", "42"]
"""
lex = shlex.shlex(string, posix=True)
lex.whitespace_split = True
lex.whitespace += ','
return list(lex)
_register(type, 'shell_split', type_shell_split)
# NOTE: This class is deprecated, use the analgous class with the same name
# in utils/build_swift/argparse/types.py instead.
class CompilerVersion(object):
"""A typed representation of a compiler version."""
def __init__(self, string_representation, components):
self.string_representation = string_representation
self.components = components
def __str__(self):
return self.string_representation
def type_clang_compiler_version(string):
"""
Parse version string and split into a tuple of strings
(major, minor, patch)
Supports "MAJOR.MINOR.PATCH" and "MAJOR.MINOR.PATCH.PATCH" formats.
"""
m = re.match(r'^([0-9]+)\.([0-9]+)\.([0-9]+)(\.([0-9]+))?$', string)
if m is not None:
return CompilerVersion(
string_representation=string,
components=m.group(1, 2, 3, 5))
raise argparse.ArgumentTypeError(
"%r is an invalid version value, "
"must be 'MAJOR.MINOR.PATCH' or "
"'MAJOR.MINOR.PATCH.PATCH'" % string)
_register(type, 'clang_compiler_version', type_clang_compiler_version)
def type_swift_compiler_version(string):
"""
Parse version string and split into a tuple of strings
(major, minor, patch)
Supports "MAJOR.MINOR" and "MAJOR.MINOR.PATCH" formats.
"""
m = re.match(r'^([0-9]+)\.([0-9]+)(\.([0-9]+))?$', string)
if m is not None:
return CompilerVersion(
string_representation=string,
components=m.group(1, 2, 4))
raise argparse.ArgumentTypeError(
"%r is an invalid version value, "
"must be 'MAJOR.MINOR' or "
"'MAJOR.MINOR.PATCH'" % string)
_register(type, 'swift_compiler_version', type_swift_compiler_version)
def type_executable(string):
"""
Check the string is executable path string.
Convert it to absolute path.
"""
if os.path.isfile(string) and os.access(string, os.X_OK):
return os.path.abspath(string)
raise argparse.ArgumentTypeError(
"%r is not executable" % string)
_register(type, 'executable', type_executable)
# Actions --------------------------------------------------------------------
action = _Registry()
class _UnavailableAction(argparse.Action):
def __init__(self,
option_strings,
dest=argparse.SUPPRESS,
default=argparse.SUPPRESS,
nargs='?',
help=None):
super(_UnavailableAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=nargs,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
if option_string is not None:
arg = option_string
else:
arg = str(values)
parser.error('unknown argument: %s' % arg)
_register(action, 'unavailable', _UnavailableAction)
class _ConcatAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
old_val = getattr(namespace, self.dest)
if old_val is None:
val = values
else:
val = old_val + values
setattr(namespace, self.dest, val)
_register(action, 'concat', _ConcatAction)
class _OptionalBoolAction(argparse.Action):
def __init__(self,
option_strings,
dest,
default=False,
const=True,
metavar="BOOL",
help=None):
super(_OptionalBoolAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
metavar=metavar,
nargs="?",
type=type.bool,
help=help,
const=const)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
_register(action, 'optional_bool', _OptionalBoolAction)
_TRUE_VALUES = [True, 1, 'true', 'True', 'TRUE', '1']
_FALSE_VALUES = [False, 0, 'false', 'False', 'FALSE', '0']
class _OnOffAction(argparse.Action):
"""Action that can be toggled on or off, defaulting to the off state. An
optional bool-ish argument can be passed to set the state manually.
"""
def __init__(self, **kwargs):
assert 'choices' in kwargs and len(kwargs['choices']) == 2
self._on_value, self._off_value = kwargs.pop('choices')
kwargs['nargs'] = '?'
if 'default' not in kwargs:
kwargs['default'] = self._off_value
if 'metavar' not in kwargs:
kwargs['metavar'] = 'BOOL'
super(_OnOffAction, self).__init__(**kwargs)
def __call__(self, parser, namespace, values, option_string=None):
if values is None:
val = self._on_value
elif values in _TRUE_VALUES:
val = self._on_value
elif values in _FALSE_VALUES:
val = self._off_value
else:
raise argparse.ArgumentTypeError(
values + ' is not a boolean value')
setattr(namespace, self.dest, val)
class _EnableAction(_OnOffAction):
"""Action that defaults to False when absent and to True when parsed with
the option to override the value by passing a bool-like value as an
argument.
"""
def __init__(self, **kwargs):
kwargs['choices'] = (True, False)
super(_EnableAction, self).__init__(**kwargs)
_register(action, 'enable', _EnableAction)
class _DisableAction(_OnOffAction):
"""Action that defaults to True when absent and to False when parsed with
the option to override the value by passing a bool-like value as an
argument. When overridden the resulting value is negated, thus passing
'True' will result in the destination being set to False.
"""
def __init__(self, **kwargs):
kwargs['choices'] = (False, True)
super(_DisableAction, self).__init__(**kwargs)
_register(action, 'disable', _DisableAction)