summaryrefslogtreecommitdiff
path: root/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/baseparser.py
diff options
context:
space:
mode:
authorShubham Saini <shubham6405@gmail.com>2018-12-11 10:01:23 +0000
committerShubham Saini <shubham6405@gmail.com>2018-12-11 10:01:23 +0000
commit68df54d6629ec019142eb149dd037774f2d11e7c (patch)
tree345bc22d46b4e01a4ba8303b94278952a4ed2b9e /venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/baseparser.py
First commit
Diffstat (limited to 'venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/baseparser.py')
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/baseparser.py240
1 files changed, 240 insertions, 0 deletions
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/baseparser.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/baseparser.py
new file mode 100644
index 0000000..ed28a1b
--- /dev/null
+++ b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/baseparser.py
@@ -0,0 +1,240 @@
1"""Base option parser setup"""
2from __future__ import absolute_import
3
4import logging
5import optparse
6import sys
7import textwrap
8from distutils.util import strtobool
9
10from pip._vendor.six import string_types
11
12from pip._internal.compat import get_terminal_size
13from pip._internal.configuration import Configuration, ConfigurationError
14
15logger = logging.getLogger(__name__)
16
17
18class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
19 """A prettier/less verbose help formatter for optparse."""
20
21 def __init__(self, *args, **kwargs):
22 # help position must be aligned with __init__.parseopts.description
23 kwargs['max_help_position'] = 30
24 kwargs['indent_increment'] = 1
25 kwargs['width'] = get_terminal_size()[0] - 2
26 optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs)
27
28 def format_option_strings(self, option):
29 return self._format_option_strings(option, ' <%s>', ', ')
30
31 def _format_option_strings(self, option, mvarfmt=' <%s>', optsep=', '):
32 """
33 Return a comma-separated list of option strings and metavars.
34
35 :param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
36 :param mvarfmt: metavar format string - evaluated as mvarfmt % metavar
37 :param optsep: separator
38 """
39 opts = []
40
41 if option._short_opts:
42 opts.append(option._short_opts[0])
43 if option._long_opts:
44 opts.append(option._long_opts[0])
45 if len(opts) > 1:
46 opts.insert(1, optsep)
47
48 if option.takes_value():
49 metavar = option.metavar or option.dest.lower()
50 opts.append(mvarfmt % metavar.lower())
51
52 return ''.join(opts)
53
54 def format_heading(self, heading):
55 if heading == 'Options':
56 return ''
57 return heading + ':\n'
58
59 def format_usage(self, usage):
60 """
61 Ensure there is only one newline between usage and the first heading
62 if there is no description.
63 """
64 msg = '\nUsage: %s\n' % self.indent_lines(textwrap.dedent(usage), " ")
65 return msg
66
67 def format_description(self, description):
68 # leave full control over description to us
69 if description:
70 if hasattr(self.parser, 'main'):
71 label = 'Commands'
72 else:
73 label = 'Description'
74 # some doc strings have initial newlines, some don't
75 description = description.lstrip('\n')
76 # some doc strings have final newlines and spaces, some don't
77 description = description.rstrip()
78 # dedent, then reindent
79 description = self.indent_lines(textwrap.dedent(description), " ")
80 description = '%s:\n%s\n' % (label, description)
81 return description
82 else:
83 return ''
84
85 def format_epilog(self, epilog):
86 # leave full control over epilog to us
87 if epilog:
88 return epilog
89 else:
90 return ''
91
92 def indent_lines(self, text, indent):
93 new_lines = [indent + line for line in text.split('\n')]
94 return "\n".join(new_lines)
95
96
97class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
98 """Custom help formatter for use in ConfigOptionParser.
99
100 This is updates the defaults before expanding them, allowing
101 them to show up correctly in the help listing.
102 """
103
104 def expand_default(self, option):
105 if self.parser is not None:
106 self.parser._update_defaults(self.parser.defaults)
107 return optparse.IndentedHelpFormatter.expand_default(self, option)
108
109
110class CustomOptionParser(optparse.OptionParser):
111
112 def insert_option_group(self, idx, *args, **kwargs):
113 """Insert an OptionGroup at a given position."""
114 group = self.add_option_group(*args, **kwargs)
115
116 self.option_groups.pop()
117 self.option_groups.insert(idx, group)
118
119 return group
120
121 @property
122 def option_list_all(self):
123 """Get a list of all options, including those in option groups."""
124 res = self.option_list[:]
125 for i in self.option_groups:
126 res.extend(i.option_list)
127
128 return res
129
130
131class ConfigOptionParser(CustomOptionParser):
132 """Custom option parser which updates its defaults by checking the
133 configuration files and environmental variables"""
134
135 def __init__(self, *args, **kwargs):
136 self.name = kwargs.pop('name')
137
138 isolated = kwargs.pop("isolated", False)
139 self.config = Configuration(isolated)
140
141 assert self.name
142 optparse.OptionParser.__init__(self, *args, **kwargs)
143
144 def check_default(self, option, key, val):
145 try:
146 return option.check_value(key, val)
147 except optparse.OptionValueError as exc:
148 print("An error occurred during configuration: %s" % exc)
149 sys.exit(3)
150
151 def _get_ordered_configuration_items(self):
152 # Configuration gives keys in an unordered manner. Order them.
153 override_order = ["global", self.name, ":env:"]
154
155 # Pool the options into different groups
156 section_items = {name: [] for name in override_order}
157 for section_key, val in self.config.items():
158 # ignore empty values
159 if not val:
160 logger.debug(
161 "Ignoring configuration key '%s' as it's value is empty.",
162 section_key
163 )
164 continue
165
166 section, key = section_key.split(".", 1)
167 if section in override_order:
168 section_items[section].append((key, val))
169
170 # Yield each group in their override order
171 for section in override_order:
172 for key, val in section_items[section]:
173 yield key, val
174
175 def _update_defaults(self, defaults):
176 """Updates the given defaults with values from the config files and
177 the environ. Does a little special handling for certain types of
178 options (lists)."""
179
180 # Accumulate complex default state.
181 self.values = optparse.Values(self.defaults)
182 late_eval = set()
183 # Then set the options with those values
184 for key, val in self._get_ordered_configuration_items():
185 # '--' because configuration supports only long names
186 option = self.get_option('--' + key)
187
188 # Ignore options not present in this parser. E.g. non-globals put
189 # in [global] by users that want them to apply to all applicable
190 # commands.
191 if option is None:
192 continue
193
194 if option.action in ('store_true', 'store_false', 'count'):
195 val = strtobool(val)
196 elif option.action == 'append':
197 val = val.split()
198 val = [self.check_default(option, key, v) for v in val]
199 elif option.action == 'callback':
200 late_eval.add(option.dest)
201 opt_str = option.get_opt_string()
202 val = option.convert_value(opt_str, val)
203 # From take_action
204 args = option.callback_args or ()
205 kwargs = option.callback_kwargs or {}
206 option.callback(option, opt_str, val, self, *args, **kwargs)
207 else:
208 val = self.check_default(option, key, val)
209
210 defaults[option.dest] = val
211
212 for key in late_eval:
213 defaults[key] = getattr(self.values, key)
214 self.values = None
215 return defaults
216
217 def get_default_values(self):
218 """Overriding to make updating the defaults after instantiation of
219 the option parser possible, _update_defaults() does the dirty work."""
220 if not self.process_default_values:
221 # Old, pre-Optik 1.5 behaviour.
222 return optparse.Values(self.defaults)
223
224 # Load the configuration, or error out in case of an error
225 try:
226 self.config.load()
227 except ConfigurationError as err:
228 self.exit(2, err.args[0])
229
230 defaults = self._update_defaults(self.defaults.copy()) # ours
231 for option in self._get_all_options():
232 default = defaults.get(option.dest)
233 if isinstance(default, string_types):
234 opt_str = option.get_opt_string()
235 defaults[option.dest] = option.check_value(opt_str, default)
236 return optparse.Values(defaults)
237
238 def error(self, msg):
239 self.print_usage(sys.stderr)
240 self.exit(2, "%s\n" % msg)