index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
8,027 | webob.response | _content_type_params__set | null | def _content_type_params__set(self, value_dict):
if not value_dict:
self._content_type_params__del()
return
params = []
for k, v in sorted(value_dict.items()):
if not _OK_PARAM_RE.search(v):
v = '"%s"' % v.replace('"', '\\"')
params.append('; %s=%s' % (k, v))
ct = self.headers.pop('Content-Type', '').split(';', 1)[0]
ct += ''.join(params)
self.headers['Content-Type'] = ct
| (self, value_dict) |
8,028 | webtest.response | _find_element | null | def _find_element(self, tag, href_attr, href_extract,
content, id,
href_pattern,
index, verbose):
content_pat = utils.make_pattern(content)
id_pat = utils.make_pattern(id)
href_pat = utils.make_pattern(href_pattern)
def printlog(s):
if verbose:
print(s)
found_links = []
total_links = 0
for element in self.html.find_all(tag):
el_html = str(element)
el_content = element.decode_contents()
attrs = element
if verbose:
printlog('Element: %r' % el_html)
if not attrs.get(href_attr):
printlog(' Skipped: no %s attribute' % href_attr)
continue
el_href = attrs[href_attr]
if href_extract:
m = href_extract.search(el_href)
if not m:
printlog(" Skipped: doesn't match extract pattern")
continue
el_href = m.group(1)
attrs['uri'] = el_href
if el_href.startswith('#'):
printlog(' Skipped: only internal fragment href')
continue
if el_href.startswith('javascript:'):
printlog(' Skipped: cannot follow javascript:')
continue
total_links += 1
if content_pat and not content_pat(el_content):
printlog(" Skipped: doesn't match description")
continue
if id_pat and not id_pat(attrs.get('id', '')):
printlog(" Skipped: doesn't match id")
continue
if href_pat and not href_pat(el_href):
printlog(" Skipped: doesn't match href")
continue
printlog(" Accepted")
found_links.append((el_html, el_content, attrs))
if not found_links:
raise IndexError(
"No matching elements found (from %s possible)"
% total_links)
if index is None:
if len(found_links) > 1:
raise IndexError(
"Multiple links match: %s"
% ', '.join([repr(anc) for anc, d, attr in found_links]))
found_link = found_links[0]
else:
try:
found_link = found_links[index]
except IndexError:
raise IndexError(
"Only %s (out of %s) links match; index %s out of range"
% (len(found_links), total_links, index))
return found_link
| (self, tag, href_attr, href_extract, content, id, href_pattern, index, verbose) |
8,029 | webtest.response | _follow | null | def _follow(self, **kw):
location = self.headers['location']
abslocation = urlparse.urljoin(self.request.url, location)
# @@: We should test that it's not a remote redirect
return self.test_app.get(abslocation, **kw)
| (self, **kw) |
8,030 | webob.response | _has_body__get |
Determine if the the response has a :attr:`~Response.body`. In
contrast to simply accessing :attr:`~Response.body`, this method
will **not** read the underlying :attr:`~Response.app_iter`.
| def _has_body__get(self):
"""
Determine if the the response has a :attr:`~Response.body`. In
contrast to simply accessing :attr:`~Response.body`, this method
will **not** read the underlying :attr:`~Response.app_iter`.
"""
app_iter = self._app_iter
if isinstance(app_iter, list) and len(app_iter) == 1:
if app_iter[0] != b'':
return True
else:
return False
if app_iter is None: # pragma: no cover
return False
return True
| (self) |
8,031 | webob.response | _headerlist__del | null | def _headerlist__del(self):
self.headerlist = []
| (self) |
8,032 | webob.response | _headerlist__get |
The list of response headers.
| def _headerlist__get(self):
"""
The list of response headers.
"""
return self._headerlist
| (self) |
8,033 | webob.response | _headerlist__set | null | def _headerlist__set(self, value):
self._headers = None
if not isinstance(value, list):
if hasattr(value, 'items'):
value = value.items()
value = list(value)
self._headerlist = value
| (self, value) |
8,034 | webob.response | _headers__get |
The headers in a dictionary-like object.
| def _headers__get(self):
"""
The headers in a dictionary-like object.
"""
if self._headers is None:
self._headers = ResponseHeaders.view_list(self._headerlist)
return self._headers
| (self) |
8,035 | webob.response | _headers__set | null | def _headers__set(self, value):
if hasattr(value, 'items'):
value = value.items()
self.headerlist = value
self._headers = None
| (self, value) |
8,037 | webob.response | _json_body__get |
Set/get the body of the response as JSON.
.. note::
This will automatically :meth:`~bytes.decode` the
:attr:`~Response.body` as ``UTF-8`` on get, and
:meth:`~str.encode` the :meth:`json.dumps` as ``UTF-8``
before assigning to :attr:`~Response.body`.
| def _json_body__get(self):
"""
Set/get the body of the response as JSON.
.. note::
This will automatically :meth:`~bytes.decode` the
:attr:`~Response.body` as ``UTF-8`` on get, and
:meth:`~str.encode` the :meth:`json.dumps` as ``UTF-8``
before assigning to :attr:`~Response.body`.
"""
# Note: UTF-8 is a content-type specific default for JSON
return json.loads(self.body.decode('UTF-8'))
| (self) |
8,038 | webob.response | _json_body__set | null | def _json_body__set(self, value):
self.body = json.dumps(value, separators=(',', ':')).encode('UTF-8')
| (self, value) |
8,039 | webob.response | _make_location_absolute | null | @staticmethod
def _make_location_absolute(environ, value):
if SCHEME_RE.search(value):
return value
new_location = urlparse.urljoin(_request_uri(environ), value)
return new_location
| (environ, value) |
8,040 | webtest.response | _parse_forms | null | def _parse_forms(self):
forms_ = self._forms_indexed = {}
form_texts = [str(f) for f in self.html('form')]
for i, text in enumerate(form_texts):
form = forms.Form(self, text, self.parser_features)
forms_[i] = form
if form.id:
forms_[form.id] = form
| (self) |
8,041 | webob.response | _status__get |
The status string.
| def _status__get(self):
"""
The status string.
"""
return self._status
| (self) |
8,042 | webob.response | _status__set | null | def _status__set(self, value):
try:
code = int(value)
except (ValueError, TypeError):
pass
else:
self.status_code = code
return
if not PY2:
if isinstance(value, bytes):
value = value.decode('ascii')
elif isinstance(value, text_type):
value = value.encode('ascii')
if not isinstance(value, str):
raise TypeError(
"You must set status to a string or integer (not %s)"
% type(value))
# Attempt to get the status code itself, if this fails we should fail
try:
# We don't need this value anywhere, we just want to validate it's
# an integer. So we are using the side-effect of int() raises a
# ValueError as a test
int(value.split()[0])
except ValueError:
raise ValueError('Invalid status code, integer required.')
self._status = value
| (self, value) |
8,043 | webob.response | _status_code__get |
The status as an integer.
| def _status_code__get(self):
"""
The status as an integer.
"""
return int(self._status.split()[0])
| (self) |
8,044 | webob.response | _status_code__set | null | def _status_code__set(self, code):
try:
self._status = '%d %s' % (code, status_reasons[code])
except KeyError:
self._status = '%d %s' % (code, status_generic_reasons[code // 100])
| (self, code) |
8,046 | webob.response | _text__get |
Get/set the text value of the body using the ``charset`` of the
``Content-Type`` or the ``default_body_encoding``.
| def _text__get(self):
"""
Get/set the text value of the body using the ``charset`` of the
``Content-Type`` or the ``default_body_encoding``.
"""
if not self.charset and not self.default_body_encoding:
raise AttributeError(
"You cannot access Response.text unless charset or default_body_encoding"
" is set"
)
decoding = self.charset or self.default_body_encoding
body = self.body
return body.decode(decoding, self.unicode_errors)
| (self) |
8,047 | webob.response | _text__set | null | def _text__set(self, value):
if not self.charset and not self.default_body_encoding:
raise AttributeError(
"You cannot access Response.text unless charset or default_body_encoding"
" is set"
)
if not isinstance(value, text_type):
raise TypeError(
"You can only set Response.text to a unicode string "
"(not %s)" % type(value))
encoding = self.charset or self.default_body_encoding
self.body = value.encode(encoding)
| (self, value) |
8,048 | webob.response | _update_cache_control | null | def _update_cache_control(self, prop_dict):
value = serialize_cache_control(prop_dict)
if not value:
if 'Cache-Control' in self.headers:
del self.headers['Cache-Control']
else:
self.headers['Cache-Control'] = value
| (self, prop_dict) |
8,049 | webob.response | app_iter_range |
Return a new ``app_iter`` built from the response ``app_iter``, that
serves up only the given ``start:stop`` range.
| def app_iter_range(self, start, stop):
"""
Return a new ``app_iter`` built from the response ``app_iter``, that
serves up only the given ``start:stop`` range.
"""
app_iter = self._app_iter
if hasattr(app_iter, 'app_iter_range'):
return app_iter.app_iter_range(start, stop)
return AppIterRange(app_iter, start, stop)
| (self, start, stop) |
8,050 | webtest.response | click |
Click the link as described. Each of ``description``,
``linkid``, and ``url`` are *patterns*, meaning that they are
either strings (regular expressions), compiled regular
expressions (objects with a ``search`` method), or callables
returning true or false.
All the given patterns are ANDed together:
* ``description`` is a pattern that matches the contents of the
anchor (HTML and all -- everything between ``<a...>`` and
``</a>``)
* ``linkid`` is a pattern that matches the ``id`` attribute of
the anchor. It will receive the empty string if no id is
given.
* ``href`` is a pattern that matches the ``href`` of the anchor;
the literal content of that attribute, not the fully qualified
attribute.
If more than one link matches, then the ``index`` link is
followed. If ``index`` is not given and more than one link
matches, or if no link matches, then ``IndexError`` will be
raised.
If you give ``verbose`` then messages will be printed about
each link, and why it does or doesn't match. If you use
``app.click(verbose=True)`` you'll see a list of all the
links.
You can use multiple criteria to essentially assert multiple
aspects about the link, e.g., where the link's destination is.
| def click(self, description=None, linkid=None, href=None,
index=None, verbose=False,
extra_environ=None):
"""
Click the link as described. Each of ``description``,
``linkid``, and ``url`` are *patterns*, meaning that they are
either strings (regular expressions), compiled regular
expressions (objects with a ``search`` method), or callables
returning true or false.
All the given patterns are ANDed together:
* ``description`` is a pattern that matches the contents of the
anchor (HTML and all -- everything between ``<a...>`` and
``</a>``)
* ``linkid`` is a pattern that matches the ``id`` attribute of
the anchor. It will receive the empty string if no id is
given.
* ``href`` is a pattern that matches the ``href`` of the anchor;
the literal content of that attribute, not the fully qualified
attribute.
If more than one link matches, then the ``index`` link is
followed. If ``index`` is not given and more than one link
matches, or if no link matches, then ``IndexError`` will be
raised.
If you give ``verbose`` then messages will be printed about
each link, and why it does or doesn't match. If you use
``app.click(verbose=True)`` you'll see a list of all the
links.
You can use multiple criteria to essentially assert multiple
aspects about the link, e.g., where the link's destination is.
"""
found_html, found_desc, found_attrs = self._find_element(
tag='a', href_attr='href',
href_extract=None,
content=description,
id=linkid,
href_pattern=href,
index=index, verbose=verbose)
extra_environ = extra_environ or {}
extra_environ.setdefault('HTTP_REFERER', str(self.request.url))
return self.goto(str(found_attrs['uri']), extra_environ=extra_environ)
| (self, description=None, linkid=None, href=None, index=None, verbose=False, extra_environ=None) |
8,051 | webtest.response | clickbutton |
Like :meth:`~webtest.response.TestResponse.click`, except looks
for link-like buttons.
This kind of button should look like
``<button onclick="...location.href='url'...">``.
| def clickbutton(self, description=None, buttonid=None, href=None,
index=None, verbose=False):
"""
Like :meth:`~webtest.response.TestResponse.click`, except looks
for link-like buttons.
This kind of button should look like
``<button onclick="...location.href='url'...">``.
"""
found_html, found_desc, found_attrs = self._find_element(
tag='button', href_attr='onclick',
href_extract=re.compile(r"location\.href='(.*?)'"),
content=description,
id=buttonid,
href_pattern=href,
index=index, verbose=verbose)
extra_environ = {'HTTP_REFERER': str(self.request.url)}
return self.goto(str(found_attrs['uri']), extra_environ=extra_environ)
| (self, description=None, buttonid=None, href=None, index=None, verbose=False) |
8,052 | webob.response | conditional_response_app |
Like the normal ``__call__`` interface, but checks conditional headers:
* ``If-Modified-Since`` (``304 Not Modified``; only on ``GET``,
``HEAD``)
* ``If-None-Match`` (``304 Not Modified``; only on ``GET``,
``HEAD``)
* ``Range`` (``406 Partial Content``; only on ``GET``,
``HEAD``)
| def conditional_response_app(self, environ, start_response):
"""
Like the normal ``__call__`` interface, but checks conditional headers:
* ``If-Modified-Since`` (``304 Not Modified``; only on ``GET``,
``HEAD``)
* ``If-None-Match`` (``304 Not Modified``; only on ``GET``,
``HEAD``)
* ``Range`` (``406 Partial Content``; only on ``GET``,
``HEAD``)
"""
req = BaseRequest(environ)
headerlist = self._abs_headerlist(environ)
method = environ.get('REQUEST_METHOD', 'GET')
if method in self._safe_methods:
status304 = False
if req.if_none_match and self.etag:
status304 = self.etag in req.if_none_match
elif req.if_modified_since and self.last_modified:
status304 = self.last_modified <= req.if_modified_since
if status304:
start_response('304 Not Modified', filter_headers(headerlist))
return EmptyResponse(self._app_iter)
if (
req.range and self in req.if_range and
self.content_range is None and
method in ('HEAD', 'GET') and
self.status_code == 200 and
self.content_length is not None
):
content_range = req.range.content_range(self.content_length)
if content_range is None:
iter_close(self._app_iter)
body = bytes_("Requested range not satisfiable: %s" % req.range)
headerlist = [
('Content-Length', str(len(body))),
('Content-Range', str(ContentRange(None, None,
self.content_length))),
('Content-Type', 'text/plain'),
] + filter_headers(headerlist)
start_response('416 Requested Range Not Satisfiable',
headerlist)
if method == 'HEAD':
return ()
return [body]
else:
app_iter = self.app_iter_range(content_range.start,
content_range.stop)
if app_iter is not None:
# the following should be guaranteed by
# Range.range_for_length(length)
assert content_range.start is not None
headerlist = [
('Content-Length',
str(content_range.stop - content_range.start)),
('Content-Range', str(content_range)),
] + filter_headers(headerlist, ('content-length',))
start_response('206 Partial Content', headerlist)
if method == 'HEAD':
return EmptyResponse(app_iter)
return app_iter
start_response(self.status, headerlist)
if method == 'HEAD':
return EmptyResponse(self._app_iter)
return self._app_iter
| (self, environ, start_response) |
8,053 | webob.response | copy | Makes a copy of the response. | def copy(self):
"""Makes a copy of the response."""
# we need to do this for app_iter to be reusable
app_iter = list(self._app_iter)
iter_close(self._app_iter)
# and this to make sure app_iter instances are different
self._app_iter = list(app_iter)
return self.__class__(
status=self._status,
headerlist=self._headerlist[:],
app_iter=app_iter,
conditional_response=self.conditional_response)
| (self) |
8,054 | webob.response | decode_content | null | def decode_content(self):
content_encoding = self.content_encoding or 'identity'
if content_encoding == 'identity':
return
if content_encoding not in ('gzip', 'deflate'):
raise ValueError(
"I don't know how to decode the content %s" % content_encoding)
if content_encoding == 'gzip':
from gzip import GzipFile
from io import BytesIO
gzip_f = GzipFile(filename='', mode='r', fileobj=BytesIO(self.body))
self.body = gzip_f.read()
self.content_encoding = None
gzip_f.close()
else:
try:
# RFC7230 section 4.2.2 specifies that the body should be wrapped
# inside a ZLIB (RFC1950) container ...
self.body = zlib.decompress(self.body)
except zlib.error:
# ... but there are nonconformant implementations around which send
# the data without the ZLIB container, so we use maximum window size
# decompression without header check (the - sign)
self.body = zlib.decompress(self.body, -15)
self.content_encoding = None
| (self) |
8,055 | webob.response | delete_cookie |
Delete a cookie from the client. Note that ``path`` and ``domain``
must match how the cookie was originally set.
This sets the cookie to the empty string, and ``max_age=0`` so
that it should expire immediately.
| def delete_cookie(self, name, path='/', domain=None):
"""
Delete a cookie from the client. Note that ``path`` and ``domain``
must match how the cookie was originally set.
This sets the cookie to the empty string, and ``max_age=0`` so
that it should expire immediately.
"""
self.set_cookie(name, None, path=path, domain=domain)
| (self, name, path='/', domain=None) |
8,056 | webob.response | encode_content |
Encode the content with the given encoding (only ``gzip`` and
``identity`` are supported).
| def encode_content(self, encoding='gzip', lazy=False):
"""
Encode the content with the given encoding (only ``gzip`` and
``identity`` are supported).
"""
assert encoding in ('identity', 'gzip'), \
"Unknown encoding: %r" % encoding
if encoding == 'identity':
self.decode_content()
return
if self.content_encoding == 'gzip':
return
if lazy:
self.app_iter = gzip_app_iter(self._app_iter)
self.content_length = None
else:
self.app_iter = list(gzip_app_iter(self._app_iter))
self.content_length = sum(map(len, self._app_iter))
self.content_encoding = 'gzip'
| (self, encoding='gzip', lazy=False) |
8,057 | webtest.response | follow |
If this response is a redirect, follow that redirect. It is an
error if it is not a redirect response. Any keyword
arguments are passed to :class:`webtest.app.TestApp.get`. Returns
another :class:`TestResponse` object.
| def follow(self, **kw):
"""
If this response is a redirect, follow that redirect. It is an
error if it is not a redirect response. Any keyword
arguments are passed to :class:`webtest.app.TestApp.get`. Returns
another :class:`TestResponse` object.
"""
if not (300 <= self.status_int < 400):
raise AssertionError(
"You can only follow redirect responses (not %s)" % self.status
)
return self._follow(**kw)
| (self, **kw) |
8,058 | webtest.response | goto |
Go to the (potentially relative) link ``href``, using the
given method (``'get'`` or ``'post'``) and any extra arguments
you want to pass to the :meth:`webtest.app.TestApp.get` or
:meth:`webtest.app.TestApp.post` methods.
All hostnames and schemes will be ignored.
| def goto(self, href, method='get', **args):
"""
Go to the (potentially relative) link ``href``, using the
given method (``'get'`` or ``'post'``) and any extra arguments
you want to pass to the :meth:`webtest.app.TestApp.get` or
:meth:`webtest.app.TestApp.post` methods.
All hostnames and schemes will be ignored.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(href)
# We
scheme = host = fragment = ''
href = urlparse.urlunsplit((scheme, host, path, query, fragment))
href = urlparse.urljoin(self.request.url, href)
method = method.lower()
assert method in ('get', 'post'), (
'Only "get" or "post" are allowed for method (you gave %r)'
% method)
if method == 'get':
method = self.test_app.get
else:
method = self.test_app.post
return method(href, **args)
| (self, href, method='get', **args) |
8,059 | webtest.response | maybe_follow |
Follow all redirects. If this response is not a redirect, do nothing.
Any keyword arguments are passed to :class:`webtest.app.TestApp.get`.
Returns another :class:`TestResponse` object.
| def maybe_follow(self, **kw):
"""
Follow all redirects. If this response is not a redirect, do nothing.
Any keyword arguments are passed to :class:`webtest.app.TestApp.get`.
Returns another :class:`TestResponse` object.
"""
remaining_redirects = 100 # infinite loops protection
response = self
while 300 <= response.status_int < 400 and remaining_redirects:
response = response._follow(**kw)
remaining_redirects -= 1
if remaining_redirects <= 0:
raise AssertionError("redirects chain looks infinite")
return response
| (self, **kw) |
8,060 | webob.response | md5_etag |
Generate an etag for the response object using an MD5 hash of
the body (the ``body`` parameter, or ``self.body`` if not given).
Sets ``self.etag``.
If ``set_content_md5`` is ``True``, sets ``self.content_md5`` as well.
| def md5_etag(self, body=None, set_content_md5=False):
"""
Generate an etag for the response object using an MD5 hash of
the body (the ``body`` parameter, or ``self.body`` if not given).
Sets ``self.etag``.
If ``set_content_md5`` is ``True``, sets ``self.content_md5`` as well.
"""
if body is None:
body = self.body
md5_digest = md5(body).digest()
md5_digest = b64encode(md5_digest)
md5_digest = md5_digest.replace(b'\n', b'')
md5_digest = native_(md5_digest)
self.etag = md5_digest.strip('=')
if set_content_md5:
self.content_md5 = md5_digest
| (self, body=None, set_content_md5=False) |
8,061 | webob.response | merge_cookies | Merge the cookies that were set on this response with the
given ``resp`` object (which can be any WSGI application).
If the ``resp`` is a :class:`webob.Response` object, then the
other object will be modified in-place.
| def merge_cookies(self, resp):
"""Merge the cookies that were set on this response with the
given ``resp`` object (which can be any WSGI application).
If the ``resp`` is a :class:`webob.Response` object, then the
other object will be modified in-place.
"""
if not self.headers.get('Set-Cookie'):
return resp
if isinstance(resp, Response):
for header in self.headers.getall('Set-Cookie'):
resp.headers.add('Set-Cookie', header)
return resp
else:
c_headers = [h for h in self.headerlist if
h[0].lower() == 'set-cookie']
def repl_app(environ, start_response):
def repl_start_response(status, headers, exc_info=None):
return start_response(status, headers + c_headers,
exc_info=exc_info)
return resp(environ, repl_start_response)
return repl_app
| (self, resp) |
8,062 | webtest.response | mustcontain | mustcontain(*strings, no=[])
Assert that the response contains all of the strings passed
in as arguments.
Equivalent to::
assert string in res
Can take a `no` keyword argument that can be a string or a
list of strings which must not be present in the response.
| def mustcontain(self, *strings, **kw):
"""mustcontain(*strings, no=[])
Assert that the response contains all of the strings passed
in as arguments.
Equivalent to::
assert string in res
Can take a `no` keyword argument that can be a string or a
list of strings which must not be present in the response.
"""
if 'no' in kw:
no = kw['no']
del kw['no']
if isinstance(no, str):
no = [no]
else:
no = []
if kw:
raise TypeError(
"The only keyword argument allowed is 'no'")
for s in strings:
if s not in self:
print_stderr("Actual response (no %r):" % s)
print_stderr(str(self))
raise IndexError(
"Body does not contain string %r" % s)
for no_s in no:
if no_s in self:
print_stderr("Actual response (has %r)" % no_s)
print_stderr(str(self))
raise IndexError(
"Body contains bad string %r" % no_s)
| (self, *strings, **kw) |
8,063 | webob.response | set_cookie |
Set (add) a cookie for the response.
Arguments are:
``name``
The cookie name.
``value``
The cookie value, which should be a string or ``None``. If
``value`` is ``None``, it's equivalent to calling the
:meth:`webob.response.Response.unset_cookie` method for this
cookie key (it effectively deletes the cookie on the client).
``max_age``
An integer representing a number of seconds, ``datetime.timedelta``,
or ``None``. This value is used as the ``Max-Age`` of the generated
cookie. If ``expires`` is not passed and this value is not
``None``, the ``max_age`` value will also influence the ``Expires``
value of the cookie (``Expires`` will be set to ``now`` +
``max_age``). If this value is ``None``, the cookie will not have a
``Max-Age`` value (unless ``expires`` is set). If both ``max_age``
and ``expires`` are set, this value takes precedence.
``path``
A string representing the cookie ``Path`` value. It defaults to
``/``.
``domain``
A string representing the cookie ``Domain``, or ``None``. If
domain is ``None``, no ``Domain`` value will be sent in the
cookie.
``secure``
A boolean. If it's ``True``, the ``secure`` flag will be sent in
the cookie, if it's ``False``, the ``secure`` flag will not be
sent in the cookie.
``httponly``
A boolean. If it's ``True``, the ``HttpOnly`` flag will be sent
in the cookie, if it's ``False``, the ``HttpOnly`` flag will not
be sent in the cookie.
``samesite``
A string representing the ``SameSite`` attribute of the cookie or
``None``. If samesite is ``None`` no ``SameSite`` value will be sent
in the cookie. Should only be ``"strict"``, ``"lax"``, or ``"none"``.
``comment``
A string representing the cookie ``Comment`` value, or ``None``.
If ``comment`` is ``None``, no ``Comment`` value will be sent in
the cookie.
``expires``
A ``datetime.timedelta`` object representing an amount of time,
``datetime.datetime`` or ``None``. A non-``None`` value is used to
generate the ``Expires`` value of the generated cookie. If
``max_age`` is not passed, but this value is not ``None``, it will
influence the ``Max-Age`` header. If this value is ``None``, the
``Expires`` cookie value will be unset (unless ``max_age`` is set).
If ``max_age`` is set, it will be used to generate the ``expires``
and this value is ignored.
If a ``datetime.datetime`` is provided it has to either be timezone
aware or be based on UTC. ``datetime.datetime`` objects that are
local time are not supported. Timezone aware ``datetime.datetime``
objects are converted to UTC.
This argument will be removed in future versions of WebOb (version
1.9).
``overwrite``
If this key is ``True``, before setting the cookie, unset any
existing cookie.
| def set_cookie(self, name, value='', max_age=None,
path='/', domain=None, secure=False, httponly=False,
comment=None, expires=None, overwrite=False,
samesite=None):
"""
Set (add) a cookie for the response.
Arguments are:
``name``
The cookie name.
``value``
The cookie value, which should be a string or ``None``. If
``value`` is ``None``, it's equivalent to calling the
:meth:`webob.response.Response.unset_cookie` method for this
cookie key (it effectively deletes the cookie on the client).
``max_age``
An integer representing a number of seconds, ``datetime.timedelta``,
or ``None``. This value is used as the ``Max-Age`` of the generated
cookie. If ``expires`` is not passed and this value is not
``None``, the ``max_age`` value will also influence the ``Expires``
value of the cookie (``Expires`` will be set to ``now`` +
``max_age``). If this value is ``None``, the cookie will not have a
``Max-Age`` value (unless ``expires`` is set). If both ``max_age``
and ``expires`` are set, this value takes precedence.
``path``
A string representing the cookie ``Path`` value. It defaults to
``/``.
``domain``
A string representing the cookie ``Domain``, or ``None``. If
domain is ``None``, no ``Domain`` value will be sent in the
cookie.
``secure``
A boolean. If it's ``True``, the ``secure`` flag will be sent in
the cookie, if it's ``False``, the ``secure`` flag will not be
sent in the cookie.
``httponly``
A boolean. If it's ``True``, the ``HttpOnly`` flag will be sent
in the cookie, if it's ``False``, the ``HttpOnly`` flag will not
be sent in the cookie.
``samesite``
A string representing the ``SameSite`` attribute of the cookie or
``None``. If samesite is ``None`` no ``SameSite`` value will be sent
in the cookie. Should only be ``"strict"``, ``"lax"``, or ``"none"``.
``comment``
A string representing the cookie ``Comment`` value, or ``None``.
If ``comment`` is ``None``, no ``Comment`` value will be sent in
the cookie.
``expires``
A ``datetime.timedelta`` object representing an amount of time,
``datetime.datetime`` or ``None``. A non-``None`` value is used to
generate the ``Expires`` value of the generated cookie. If
``max_age`` is not passed, but this value is not ``None``, it will
influence the ``Max-Age`` header. If this value is ``None``, the
``Expires`` cookie value will be unset (unless ``max_age`` is set).
If ``max_age`` is set, it will be used to generate the ``expires``
and this value is ignored.
If a ``datetime.datetime`` is provided it has to either be timezone
aware or be based on UTC. ``datetime.datetime`` objects that are
local time are not supported. Timezone aware ``datetime.datetime``
objects are converted to UTC.
This argument will be removed in future versions of WebOb (version
1.9).
``overwrite``
If this key is ``True``, before setting the cookie, unset any
existing cookie.
"""
# Remove in WebOb 1.10
if expires:
warn_deprecation('Argument "expires" will be removed in a future '
'version of WebOb, please use "max_age".', 1.10, 1)
if overwrite:
self.unset_cookie(name, strict=False)
# If expires is set, but not max_age we set max_age to expires
if not max_age and isinstance(expires, timedelta):
max_age = expires
# expires can also be a datetime
if not max_age and isinstance(expires, datetime):
# If expires has a timezone attached, convert it to UTC
if expires.tzinfo and expires.utcoffset():
expires = (expires - expires.utcoffset()).replace(tzinfo=None)
max_age = expires - datetime.utcnow()
value = bytes_(value, 'utf-8')
cookie = make_cookie(name, value, max_age=max_age, path=path,
domain=domain, secure=secure, httponly=httponly,
comment=comment, samesite=samesite)
self.headerlist.append(('Set-Cookie', cookie))
| (self, name, value='', max_age=None, path='/', domain=None, secure=False, httponly=False, comment=None, expires=None, overwrite=False, samesite=None) |
8,064 | webtest.response | showbrowser |
Show this response in a browser window (for debugging purposes,
when it's hard to read the HTML).
| def showbrowser(self):
"""
Show this response in a browser window (for debugging purposes,
when it's hard to read the HTML).
"""
import webbrowser
import tempfile
f = tempfile.NamedTemporaryFile(prefix='webtest-page',
suffix='.html')
name = f.name
f.close()
f = open(name, 'w')
f.write(self.body.decode(self.charset or 'ascii', 'replace'))
f.close()
if name[0] != '/': # pragma: no cover
# windows ...
url = 'file:///' + name
else:
url = 'file://' + name
webbrowser.open_new(url)
| (self) |
8,065 | webob.response | unset_cookie |
Unset a cookie with the given name (remove it from the response).
| def unset_cookie(self, name, strict=True):
"""
Unset a cookie with the given name (remove it from the response).
"""
existing = self.headers.getall('Set-Cookie')
if not existing and not strict:
return
cookies = Cookie()
for header in existing:
cookies.load(header)
if isinstance(name, text_type):
name = name.encode('utf8')
if name in cookies:
del cookies[name]
del self.headers['Set-Cookie']
for m in cookies.values():
self.headerlist.append(('Set-Cookie', m.serialize()))
elif strict:
raise KeyError("No cookie has been set with the name %r" % name)
| (self, name, strict=True) |
8,066 | webob.response | write | null | def write(self, text):
if not isinstance(text, bytes):
if not isinstance(text, text_type):
msg = "You can only write str to a Response.body_file, not %s"
raise TypeError(msg % type(text))
if not self.charset:
msg = ("You can only write text to Response if charset has "
"been set")
raise TypeError(msg)
text = text.encode(self.charset)
app_iter = self._app_iter
if not isinstance(app_iter, list):
try:
new_app_iter = self._app_iter = list(app_iter)
finally:
iter_close(app_iter)
app_iter = new_app_iter
self.content_length = sum(len(chunk) for chunk in app_iter)
app_iter.append(text)
if self.content_length is not None:
self.content_length += len(text)
| (self, text) |
8,067 | webtest.forms | Text | Field representing ``<input type="text">`` | class Text(Field):
"""Field representing ``<input type="text">``"""
| (form, tag, name, pos, value=None, id=None, **attrs) |
8,073 | webtest.forms | Textarea | Field representing ``<textarea>`` | class Textarea(Text):
"""Field representing ``<textarea>``"""
| (form, tag, name, pos, value=None, id=None, **attrs) |
8,079 | webtest.forms | Upload |
A file to upload::
>>> Upload('filename.txt', 'data', 'application/octet-stream')
<Upload "filename.txt">
>>> Upload('filename.txt', 'data')
<Upload "filename.txt">
>>> Upload("README.txt")
<Upload "README.txt">
:param filename: Name of the file to upload.
:param content: Contents of the file.
:param content_type: MIME type of the file.
| class Upload:
"""
A file to upload::
>>> Upload('filename.txt', 'data', 'application/octet-stream')
<Upload "filename.txt">
>>> Upload('filename.txt', 'data')
<Upload "filename.txt">
>>> Upload("README.txt")
<Upload "README.txt">
:param filename: Name of the file to upload.
:param content: Contents of the file.
:param content_type: MIME type of the file.
"""
def __init__(self, filename, content=None, content_type=None):
self.filename = filename
self.content = content
self.content_type = content_type
def __iter__(self):
yield self.filename
if self.content is not None:
yield self.content
yield self.content_type
# TODO: do we handle the case when we need to get
# contents ourselves?
def __repr__(self):
return '<Upload "%s">' % self.filename
| (filename, content=None, content_type=None) |
8,080 | webtest.forms | __init__ | null | def __init__(self, filename, content=None, content_type=None):
self.filename = filename
self.content = content
self.content_type = content_type
| (self, filename, content=None, content_type=None) |
8,081 | webtest.forms | __iter__ | null | def __iter__(self):
yield self.filename
if self.content is not None:
yield self.content
yield self.content_type
# TODO: do we handle the case when we need to get
# contents ourselves?
| (self) |
8,082 | webtest.forms | __repr__ | null | def __repr__(self):
return '<Upload "%s">' % self.filename
| (self) |
8,089 | entrypoint2 | _ParagraphPreservingArgParseFormatter | null | class _ParagraphPreservingArgParseFormatter(argparse.HelpFormatter):
def __init__(self, *args, **kwargs):
super(_ParagraphPreservingArgParseFormatter, self).__init__(*args, **kwargs)
self._long_break_matcher = argparse._re.compile(r"\n\n+")
def _fill_text(self, text, width, indent):
output = []
for block in self._long_break_matcher.split(text.strip()):
output.append(
textwrap.fill(
block, width, initial_indent=indent, subsequent_indent=indent
)
)
return "\n\n".join(output + [""])
| (*args, **kwargs) |
8,090 | entrypoint2 | __init__ | null | def __init__(self, *args, **kwargs):
super(_ParagraphPreservingArgParseFormatter, self).__init__(*args, **kwargs)
self._long_break_matcher = argparse._re.compile(r"\n\n+")
| (self, *args, **kwargs) |
8,091 | argparse | _add_item | null | def _add_item(self, func, args):
self._current_section.items.append((func, args))
| (self, func, args) |
8,092 | argparse | _dedent | null | def _dedent(self):
self._current_indent -= self._indent_increment
assert self._current_indent >= 0, 'Indent decreased below 0.'
self._level -= 1
| (self) |
8,093 | argparse | _expand_help | null | def _expand_help(self, action):
params = dict(vars(action), prog=self._prog)
for name in list(params):
if params[name] is SUPPRESS:
del params[name]
for name in list(params):
if hasattr(params[name], '__name__'):
params[name] = params[name].__name__
if params.get('choices') is not None:
choices_str = ', '.join([str(c) for c in params['choices']])
params['choices'] = choices_str
return self._get_help_string(action) % params
| (self, action) |
8,094 | entrypoint2 | _fill_text | null | def _fill_text(self, text, width, indent):
output = []
for block in self._long_break_matcher.split(text.strip()):
output.append(
textwrap.fill(
block, width, initial_indent=indent, subsequent_indent=indent
)
)
return "\n\n".join(output + [""])
| (self, text, width, indent) |
8,095 | argparse | _format_action | null | def _format_action(self, action):
# determine the required width and the entry label
help_position = min(self._action_max_length + 2,
self._max_help_position)
help_width = max(self._width - help_position, 11)
action_width = help_position - self._current_indent - 2
action_header = self._format_action_invocation(action)
# no help; start on same line and add a final newline
if not action.help:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
# short action name; start on the same line and pad two spaces
elif len(action_header) <= action_width:
tup = self._current_indent, '', action_width, action_header
action_header = '%*s%-*s ' % tup
indent_first = 0
# long action name; start on the next line
else:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
indent_first = help_position
# collect the pieces of the action help
parts = [action_header]
# if there was help for the action, add lines of help text
if action.help and action.help.strip():
help_text = self._expand_help(action)
if help_text:
help_lines = self._split_lines(help_text, help_width)
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
for line in help_lines[1:]:
parts.append('%*s%s\n' % (help_position, '', line))
# or add a newline if the description doesn't end with one
elif not action_header.endswith('\n'):
parts.append('\n')
# if there are any sub-actions, add their help as well
for subaction in self._iter_indented_subactions(action):
parts.append(self._format_action(subaction))
# return a single string
return self._join_parts(parts)
| (self, action) |
8,096 | argparse | _format_action_invocation | null | def _format_action_invocation(self, action):
if not action.option_strings:
default = self._get_default_metavar_for_positional(action)
metavar, = self._metavar_formatter(action, default)(1)
return metavar
else:
parts = []
# if the Optional doesn't take a value, format is:
# -s, --long
if action.nargs == 0:
parts.extend(action.option_strings)
# if the Optional takes a value, format is:
# -s ARGS, --long ARGS
else:
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append('%s %s' % (option_string, args_string))
return ', '.join(parts)
| (self, action) |
8,097 | argparse | _format_actions_usage | null | def _format_actions_usage(self, actions, groups):
# find group indices and identify actions in groups
group_actions = set()
inserts = {}
for group in groups:
if not group._group_actions:
raise ValueError(f'empty group {group}')
try:
start = actions.index(group._group_actions[0])
except ValueError:
continue
else:
group_action_count = len(group._group_actions)
end = start + group_action_count
if actions[start:end] == group._group_actions:
suppressed_actions_count = 0
for action in group._group_actions:
group_actions.add(action)
if action.help is SUPPRESS:
suppressed_actions_count += 1
exposed_actions_count = group_action_count - suppressed_actions_count
if not group.required:
if start in inserts:
inserts[start] += ' ['
else:
inserts[start] = '['
if end in inserts:
inserts[end] += ']'
else:
inserts[end] = ']'
elif exposed_actions_count > 1:
if start in inserts:
inserts[start] += ' ('
else:
inserts[start] = '('
if end in inserts:
inserts[end] += ')'
else:
inserts[end] = ')'
for i in range(start + 1, end):
inserts[i] = '|'
# collect all actions format strings
parts = []
for i, action in enumerate(actions):
# suppressed arguments are marked with None
# remove | separators for suppressed arguments
if action.help is SUPPRESS:
parts.append(None)
if inserts.get(i) == '|':
inserts.pop(i)
elif inserts.get(i + 1) == '|':
inserts.pop(i + 1)
# produce all arg strings
elif not action.option_strings:
default = self._get_default_metavar_for_positional(action)
part = self._format_args(action, default)
# if it's in a group, strip the outer []
if action in group_actions:
if part[0] == '[' and part[-1] == ']':
part = part[1:-1]
# add the action string to the list
parts.append(part)
# produce the first way to invoke the option in brackets
else:
option_string = action.option_strings[0]
# if the Optional doesn't take a value, format is:
# -s or --long
if action.nargs == 0:
part = action.format_usage()
# if the Optional takes a value, format is:
# -s ARGS or --long ARGS
else:
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
part = '%s %s' % (option_string, args_string)
# make it look optional if it's not required or in a group
if not action.required and action not in group_actions:
part = '[%s]' % part
# add the action string to the list
parts.append(part)
# insert things at the necessary indices
for i in sorted(inserts, reverse=True):
parts[i:i] = [inserts[i]]
# join all the action items with spaces
text = ' '.join([item for item in parts if item is not None])
# clean up separators for mutually exclusive groups
open = r'[\[(]'
close = r'[\])]'
text = _re.sub(r'(%s) ' % open, r'\1', text)
text = _re.sub(r' (%s)' % close, r'\1', text)
text = _re.sub(r'%s *%s' % (open, close), r'', text)
text = text.strip()
# return the text
return text
| (self, actions, groups) |
8,098 | argparse | _format_args | null | def _format_args(self, action, default_metavar):
get_metavar = self._metavar_formatter(action, default_metavar)
if action.nargs is None:
result = '%s' % get_metavar(1)
elif action.nargs == OPTIONAL:
result = '[%s]' % get_metavar(1)
elif action.nargs == ZERO_OR_MORE:
metavar = get_metavar(1)
if len(metavar) == 2:
result = '[%s [%s ...]]' % metavar
else:
result = '[%s ...]' % metavar
elif action.nargs == ONE_OR_MORE:
result = '%s [%s ...]' % get_metavar(2)
elif action.nargs == REMAINDER:
result = '...'
elif action.nargs == PARSER:
result = '%s ...' % get_metavar(1)
elif action.nargs == SUPPRESS:
result = ''
else:
try:
formats = ['%s' for _ in range(action.nargs)]
except TypeError:
raise ValueError("invalid nargs value") from None
result = ' '.join(formats) % get_metavar(action.nargs)
return result
| (self, action, default_metavar) |
8,099 | argparse | _format_text | null | def _format_text(self, text):
if '%(prog)' in text:
text = text % dict(prog=self._prog)
text_width = max(self._width - self._current_indent, 11)
indent = ' ' * self._current_indent
return self._fill_text(text, text_width, indent) + '\n\n'
| (self, text) |
8,100 | argparse | _format_usage | null | def _format_usage(self, usage, actions, groups, prefix):
if prefix is None:
prefix = _('usage: ')
# if usage is specified, use that
if usage is not None:
usage = usage % dict(prog=self._prog)
# if no optionals or positionals are available, usage is just prog
elif usage is None and not actions:
usage = '%(prog)s' % dict(prog=self._prog)
# if optionals and positionals are available, calculate usage
elif usage is None:
prog = '%(prog)s' % dict(prog=self._prog)
# split optionals from positionals
optionals = []
positionals = []
for action in actions:
if action.option_strings:
optionals.append(action)
else:
positionals.append(action)
# build full usage string
format = self._format_actions_usage
action_usage = format(optionals + positionals, groups)
usage = ' '.join([s for s in [prog, action_usage] if s])
# wrap the usage parts if it's too long
text_width = self._width - self._current_indent
if len(prefix) + len(usage) > text_width:
# break usage into wrappable parts
part_regexp = (
r'\(.*?\)+(?=\s|$)|'
r'\[.*?\]+(?=\s|$)|'
r'\S+'
)
opt_usage = format(optionals, groups)
pos_usage = format(positionals, groups)
opt_parts = _re.findall(part_regexp, opt_usage)
pos_parts = _re.findall(part_regexp, pos_usage)
assert ' '.join(opt_parts) == opt_usage
assert ' '.join(pos_parts) == pos_usage
# helper for wrapping lines
def get_lines(parts, indent, prefix=None):
lines = []
line = []
if prefix is not None:
line_len = len(prefix) - 1
else:
line_len = len(indent) - 1
for part in parts:
if line_len + 1 + len(part) > text_width and line:
lines.append(indent + ' '.join(line))
line = []
line_len = len(indent) - 1
line.append(part)
line_len += len(part) + 1
if line:
lines.append(indent + ' '.join(line))
if prefix is not None:
lines[0] = lines[0][len(indent):]
return lines
# if prog is short, follow it with optionals or positionals
if len(prefix) + len(prog) <= 0.75 * text_width:
indent = ' ' * (len(prefix) + len(prog) + 1)
if opt_parts:
lines = get_lines([prog] + opt_parts, indent, prefix)
lines.extend(get_lines(pos_parts, indent))
elif pos_parts:
lines = get_lines([prog] + pos_parts, indent, prefix)
else:
lines = [prog]
# if prog is long, put it on its own line
else:
indent = ' ' * len(prefix)
parts = opt_parts + pos_parts
lines = get_lines(parts, indent)
if len(lines) > 1:
lines = []
lines.extend(get_lines(opt_parts, indent))
lines.extend(get_lines(pos_parts, indent))
lines = [prog] + lines
# join lines into usage
usage = '\n'.join(lines)
# prefix with 'usage:'
return '%s%s\n\n' % (prefix, usage)
| (self, usage, actions, groups, prefix) |
8,101 | argparse | _get_default_metavar_for_optional | null | def _get_default_metavar_for_optional(self, action):
return action.dest.upper()
| (self, action) |
8,102 | argparse | _get_default_metavar_for_positional | null | def _get_default_metavar_for_positional(self, action):
return action.dest
| (self, action) |
8,103 | argparse | _get_help_string | null | def _get_help_string(self, action):
return action.help
| (self, action) |
8,104 | argparse | _indent | null | def _indent(self):
self._current_indent += self._indent_increment
self._level += 1
| (self) |
8,105 | argparse | _iter_indented_subactions | null | def _iter_indented_subactions(self, action):
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
yield from get_subactions()
self._dedent()
| (self, action) |
8,106 | argparse | _join_parts | null | def _join_parts(self, part_strings):
return ''.join([part
for part in part_strings
if part and part is not SUPPRESS])
| (self, part_strings) |
8,107 | argparse | _metavar_formatter | null | def _metavar_formatter(self, action, default_metavar):
if action.metavar is not None:
result = action.metavar
elif action.choices is not None:
choice_strs = [str(choice) for choice in action.choices]
result = '{%s}' % ','.join(choice_strs)
else:
result = default_metavar
def format(tuple_size):
if isinstance(result, tuple):
return result
else:
return (result, ) * tuple_size
return format
| (self, action, default_metavar) |
8,108 | argparse | _split_lines | null | def _split_lines(self, text, width):
text = self._whitespace_matcher.sub(' ', text).strip()
# The textwrap module is used only for formatting help.
# Delay its import for speeding up the common usage of argparse.
import textwrap
return textwrap.wrap(text, width)
| (self, text, width) |
8,109 | argparse | add_argument | null | def add_argument(self, action):
if action.help is not SUPPRESS:
# find all invocations
get_invocation = self._format_action_invocation
invocations = [get_invocation(action)]
for subaction in self._iter_indented_subactions(action):
invocations.append(get_invocation(subaction))
# update the maximum item length
invocation_length = max(map(len, invocations))
action_length = invocation_length + self._current_indent
self._action_max_length = max(self._action_max_length,
action_length)
# add the item to the list
self._add_item(self._format_action, [action])
| (self, action) |
8,110 | argparse | add_arguments | null | def add_arguments(self, actions):
for action in actions:
self.add_argument(action)
| (self, actions) |
8,111 | argparse | add_text | null | def add_text(self, text):
if text is not SUPPRESS and text is not None:
self._add_item(self._format_text, [text])
| (self, text) |
8,112 | argparse | add_usage | null | def add_usage(self, usage, actions, groups, prefix=None):
if usage is not SUPPRESS:
args = usage, actions, groups, prefix
self._add_item(self._format_usage, args)
| (self, usage, actions, groups, prefix=None) |
8,113 | argparse | end_section | null | def end_section(self):
self._current_section = self._current_section.parent
self._dedent()
| (self) |
8,114 | argparse | format_help | null | def format_help(self):
help = self._root_section.format_help()
if help:
help = self._long_break_matcher.sub('\n\n', help)
help = help.strip('\n') + '\n'
return help
| (self) |
8,115 | argparse | start_section | null | def start_section(self, heading):
self._indent()
section = self._Section(self, self._current_section, heading)
self._add_item(section.format_help, [])
self._current_section = section
| (self, heading) |
8,116 | entrypoint2 | _correct_args |
Convert a dictionary of arguments including __argv into a list
for passing to the function.
| def _correct_args(func, kwargs):
"""
Convert a dictionary of arguments including __argv into a list
for passing to the function.
"""
args = inspect.getfullargspec(func)[0]
return [kwargs[arg] for arg in args] + kwargs["__args"]
| (func, kwargs) |
8,117 | entrypoint2 | _listLike | null | def _listLike(ann, t):
ret = ann is List[t] or ann is Sequence[t] or ann is Iterable[t]
if PY39PLUS:
ret = ret or ann == list[t]
return ret
| (ann, t) |
8,118 | entrypoint2 | _module_version | null | def _module_version(func):
version = None
for v in "__version__ VERSION version".split():
version = func.__globals__.get(v)
if version:
break
return version
| (func) |
8,119 | entrypoint2 | _parse_doc |
Converts a well-formed docstring into documentation
to be fed into argparse.
See signature_parser for details.
shorts: (-k for --keyword -k, or "from" for "frm/from")
metavars: (FILE for --input=FILE)
helps: (docs for --keyword: docs)
description: the stuff before
epilog: the stuff after
| def _parse_doc(docs):
"""
Converts a well-formed docstring into documentation
to be fed into argparse.
See signature_parser for details.
shorts: (-k for --keyword -k, or "from" for "frm/from")
metavars: (FILE for --input=FILE)
helps: (docs for --keyword: docs)
description: the stuff before
epilog: the stuff after
"""
name = "(?:[a-zA-Z][a-zA-Z0-9-_]*)"
re_var = re.compile(r"^ *(%s)(?: */(%s))? *:(.*)$" % (name, name))
re_opt = re.compile(
r"^ *(?:(-[a-zA-Z0-9]),? +)?--(%s)(?: *=(%s))? *:(.*)$" % (name, name)
)
shorts, metavars, helps, description, epilog = {}, {}, {}, "", ""
if docs:
prev = ""
for line in docs.split("\n"):
line = line.strip()
# remove starting ':param'
if line.startswith(":param"):
line = line[len(":param") :]
# skip ':rtype:' row
if line.startswith(":rtype:"):
continue
if line.strip() == "----":
break
m = re_var.match(line)
if m:
if epilog:
helps[prev] += epilog.strip()
epilog = ""
if m.group(2):
shorts[m.group(1)] = m.group(2)
helps[m.group(1)] = m.group(3).strip()
prev = m.group(1)
previndent = len(line) - len(line.lstrip())
continue
m = re_opt.match(line)
if m:
if epilog:
helps[prev] += epilog.strip()
epilog = ""
name = m.group(2).replace("-", "_")
helps[name] = m.group(4)
prev = name
if m.group(1):
shorts[name] = m.group(1)
if m.group(3):
metavars[name] = m.group(3)
previndent = len(line) - len(line.lstrip())
continue
if helps:
if line.startswith(" " * (previndent + 1)):
helps[prev] += "\n" + line.strip()
else:
epilog += "\n" + line.strip()
else:
description += "\n" + line.strip()
if line.strip():
previndent = len(line) - len(line.lstrip())
return shorts, metavars, helps, description, epilog
| (docs) |
8,120 | entrypoint2 | _signature_parser | null | def _signature_parser(func):
# args, varargs, varkw, defaults = inspect.getargspec(func)
(
args,
varargs,
varkw,
defaults,
kwonlyargs,
kwonlydefaults,
annotations,
) = inspect.getfullargspec(func)
# print(f"func: {func}")
# print(f"args: {args}")
# print(f"varargs: {varargs}")
# print(f"varkw: {varkw}")
# print(f"defaults: {defaults}")
# print(f"kwonlyargs: {kwonlyargs}")
# print(f"kwonlydefaults: {kwonlydefaults}")
# print(f"annotations: {annotations}")
if not args:
args = []
if not defaults:
defaults = []
if varkw:
raise ValueError("Can't wrap a function with **kwargs")
# Compulsary positional options
needed = args[0 : len(args) - len(defaults)]
# Optional flag options
params = args[len(needed) :]
shorts, metavars, helps, description, epilog = _parse_doc(func.__doc__)
parser = argparse.ArgumentParser(
description=description,
epilog=epilog,
formatter_class=_ParagraphPreservingArgParseFormatter,
)
# special flags
special_flags = []
special_flags += ["debug"]
defaults += (False,)
helps["debug"] = "set logging level to DEBUG"
if _module_version(func):
special_flags += ["version"]
defaults += (False,)
helps["version"] = "show program's version number and exit"
params += special_flags
# Optional flag options f(p=1)
used_shorts = set()
for param, default in zip(params, defaults):
args = ["--%s" % param.replace("_", "-")]
short = None
if param in shorts:
short = shorts[param]
else:
if param not in special_flags and len(param) > 1:
first_char = param[0]
if first_char not in used_shorts:
used_shorts.add(first_char)
short = "-" + first_char
# -h conflicts with 'help'
if short and short != "-h":
args = [short] + args
d = {"default": default, "dest": param.replace("-", "_")}
ann = annotations.get(param)
if param == "version":
d["action"] = "version"
d["version"] = _module_version(func)
elif default is True:
d["action"] = "store_false"
elif default is False:
d["action"] = "store_true"
elif ann:
d["action"], d["type"], _ = _useAnnotation(ann)
elif isinstance(default, list):
d["action"] = "append"
d["type"] = _toStr
elif isinstance(default, str):
d["action"] = "store"
d["type"] = _toStr
elif isinstance(default, bytes):
d["action"] = "store"
d["type"] = _toBytes
elif default is None:
d["action"] = "store"
d["type"] = _toStr
else:
d["action"] = "store"
d["type"] = type(default)
if param in helps:
d["help"] = helps[param]
if param in metavars:
d["metavar"] = metavars[param]
parser.add_argument(*args, **d)
# Compulsary positional options f(p1,p2)
for need in needed:
ann = annotations.get(need)
d = {"action": "store"}
if ann:
d["action"], d["type"], nargs = _useAnnotation(ann, positional=True)
if nargs:
d["nargs"] = nargs
else:
d["type"] = _toStr
if need in helps:
d["help"] = helps[need]
if need in shorts:
args = [shorts[need]]
else:
args = [need]
parser.add_argument(*args, **d)
# The trailing arguments f(*args)
if varargs:
d = {"action": "store", "type": _toStr, "nargs": "*"}
if varargs in helps:
d["help"] = helps[varargs]
if varargs in shorts:
d["metavar"] = shorts[varargs]
else:
d["metavar"] = varargs
parser.add_argument("__args", **d)
return parser
| (func) |
8,121 | entrypoint2 | _toBool | null | def _toBool(x):
return x.strip().lower() not in ["false", "0", "no", ""]
| (x) |
8,122 | entrypoint2 | _toBytes | null | def _toBytes(x):
return bytes(x, "utf-8")
| (x) |
8,123 | entrypoint2 | _toStr | null | def _toStr(x):
return x
| (x) |
8,124 | entrypoint2 | _useAnnotation | null | def _useAnnotation(ann, positional=False):
# https://stackoverflow.com/questions/48572831/how-to-access-the-type-arguments-of-typing-generic
d = {}
d["action"] = "store"
d["type"] = _toStr
islist = False
if ann is str:
pass
elif ann is bytes:
d["type"] = _toBytes
elif ann is bool:
d["type"] = _toBool
elif _listLike(ann, str):
islist = True
elif _listLike(ann, bytes):
islist = True
d["type"] = _toBytes
elif _listLike(ann, int):
islist = True
d["type"] = int
elif _listLike(ann, float):
islist = True
d["type"] = float
elif _listLike(ann, complex):
islist = True
d["type"] = complex
elif _listLike(ann, bool):
islist = True
d["type"] = _toBool
elif ann is Any:
pass
elif ann is Optional[str]:
pass
elif ann is Optional[bytes]:
d["type"] = _toBytes
elif ann is Optional[int]:
d["type"] = int
elif ann is Optional[float]:
d["type"] = float
elif ann is Optional[complex]:
d["type"] = complex
elif ann is Optional[bool]:
d["type"] = _toBool
else:
d["type"] = ann
nargs = None
if islist:
if positional:
nargs = "*"
else:
d["action"] = "append"
return d["action"], d["type"], nargs
| (ann, positional=False) |
8,126 | entrypoint2 | entrypoint | null | def entrypoint(func: Callable) -> Callable:
frame_local = sys._getframe(1).f_locals
if "__name__" in frame_local and frame_local["__name__"] == "__main__":
argv = sys.argv[1:]
# print("__annotations__ ", func.__annotations__)
# print("__total__", func.__total__)
parser = _signature_parser(func)
kwargs = parser.parse_args(argv).__dict__
# special cli flags
# --version is handled by ArgParse
# if kwargs.get('version'):
# print module_version(func)
# return
if "version" in kwargs.keys():
del kwargs["version"]
# --debug
FORMAT = "%(asctime)-6s: %(name)s - %(levelname)s - %(message)s"
if kwargs.get("debug"):
logging.basicConfig(
level=logging.DEBUG,
format=FORMAT,
)
del kwargs["debug"]
if "__args" in kwargs:
return func(*_correct_args(func, kwargs))
else:
return func(**kwargs)
return func
| (func: Callable) -> Callable |
8,133 | versioningit.errors | ConfigError |
Raised when the ``versioningit`` configuration contain invalid settings
| class ConfigError(Error, ValueError):
"""
Raised when the ``versioningit`` configuration contain invalid settings
"""
pass
| null |
8,134 | versioningit.errors | Error | Base class of all ``versioningit``-specific errors | class Error(Exception):
"""Base class of all ``versioningit``-specific errors"""
pass
| null |
8,135 | versioningit.core | FallbackReport |
.. versionadded:: 2.0.0
A report of the version extracted from a :file:`PKG-INFO` file in an sdist
| class FallbackReport:
"""
.. versionadded:: 2.0.0
A report of the version extracted from a :file:`PKG-INFO` file in an sdist
"""
#: The version
version: str
| (version: str) -> None |
8,136 | versioningit.core | __eq__ | null | from __future__ import annotations
from dataclasses import dataclass
import os
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional
from .config import Config
from .errors import Error, MethodError, NotSdistError, NotVCSError, NotVersioningitError
from .logging import log, warn_bad_version
from .methods import VersioningitMethod
from .onbuild import OnbuildFileProvider, SetuptoolsFileProvider
from .util import is_sdist, parse_version_from_metadata
if TYPE_CHECKING:
from setuptools import Distribution
@dataclass
class VCSDescription:
"""A description of the state of a version control repository"""
#: The name of the most recent tag in the repository (possibly after
#: applying any match or exclusion rules based on user parameters) from
#: which the current repository state is descended
tag: str
#: The relationship of the repository's current state to the tag. If the
#: repository state is exactly the tagged state, this field should equal
#: ``"exact"``; otherwise, it will be a string that will be used as a key
#: in the ``format`` subtable of the versioningit configuration.
#: Recommended values are ``"distance"``, ``"dirty"``, and
#: ``"distance-dirty"``.
state: str
#: The name of the repository's current branch, or `None` if it cannot be
#: determined or does not apply
branch: Optional[str]
#: A `dict` of additional information about the repository state to make
#: available to the ``format`` method. Custom ``vcs`` methods are advised
#: to adhere closely to the set of fields used by the built-in methods.
fields: dict[str, Any]
| (self, other) |
8,138 | versioningit.core | __repr__ | null | def run(
self, write: bool = False, fallback: bool = True
) -> Report | FallbackReport:
"""
.. versionadded:: 2.0.0
Run all of the steps for the project — aside from "onbuild" and,
optionally, "write" — and return an object containing the final version
and intermediate values.
If ``write`` is true, then the file specified in the ``write`` subtable
of the versioningit configuration, if any, will be updated.
If ``fallback`` is true, then if ``project_dir`` is not under version
control (or if the VCS executable is not installed), ``versioningit``
will assume that the directory is an unpacked sdist and will read the
version from the :file:`PKG-INFO` file, returning a `FallbackReport`
instance instead of a `Report`.
:raises NotVCSError:
if ``fallback`` is false and ``project_dir`` is not under version
control
:raises NotSdistError:
if ``fallback`` is true, ``project_dir`` is not under version
control, and there is no :file:`PKG-INFO` file in ``project_dir``
:raises ConfigError:
if any of the values in ``config`` are not of the correct type
:raises MethodError: if a method returns a value of the wrong type
"""
description: Optional[VCSDescription] = None
base_version: Optional[str] = None
next_version: Optional[str] = None
using_default_version: bool = False
try:
description = self.do_vcs()
base_version = self.do_tag2version(description.tag)
next_version = self.do_next_version(base_version, description.branch)
if description.state == "exact":
log.info("Tag is exact match; returning extracted version")
version = base_version
else:
log.info("VCS state is %r; formatting version", description.state)
version = self.do_format(
description=description,
base_version=base_version,
next_version=next_version,
)
log.info("Final version: %s", version)
except Error as e:
if (
isinstance(e, NotVCSError)
and fallback
and (is_sdist(self.project_dir) or self.default_version is None)
):
log.info("Could not get VCS data from %s: %s", self.project_dir, str(e))
log.info("Falling back to reading from PKG-INFO")
return FallbackReport(
version=get_version_from_pkg_info(self.project_dir)
)
if self.default_version is not None:
log.error("%s: %s", type(e).__name__, str(e))
log.info("Falling back to default-version")
version = self.default_version
using_default_version = True
else:
raise
except Exception: # pragma: no cover
if self.default_version is not None:
log.exception("An unexpected error occurred:")
log.info("Falling back to default-version")
version = self.default_version
using_default_version = True
else:
raise
warn_bad_version(version, "Final version")
template_fields = self.do_template_fields(
version=version,
description=description,
base_version=base_version,
next_version=next_version,
)
if write:
self.do_write(template_fields)
return Report(
version=version,
description=description,
base_version=base_version,
next_version=next_version,
template_fields=template_fields,
using_default_version=using_default_version,
)
| (self) |
8,139 | versioningit.errors | InvalidTagError |
Raised by ``tag2version`` methods when passed a tag that they cannot work
with
| class InvalidTagError(Error, ValueError):
"""
Raised by ``tag2version`` methods when passed a tag that they cannot work
with
"""
pass
| null |
8,140 | versioningit.errors | InvalidVersionError |
Raised by ``next-version`` and ``template-fields`` methods when passed a
version that they cannot work with
| class InvalidVersionError(Error, ValueError):
"""
Raised by ``next-version`` and ``template-fields`` methods when passed a
version that they cannot work with
"""
pass
| null |
8,141 | versioningit.errors | MethodError | Raised when a method is invalid or returns an invalid value | class MethodError(Error):
"""Raised when a method is invalid or returns an invalid value"""
pass
| null |
8,142 | versioningit.errors | NoTagError | Raised when a tag cannot be found in version control | class NoTagError(Error):
"""Raised when a tag cannot be found in version control"""
pass
| null |
8,143 | versioningit.errors | NotSdistError |
Raised when attempting to read a :file:`PKG-INFO` file from a directory
that doesn't have one
| class NotSdistError(Error):
"""
Raised when attempting to read a :file:`PKG-INFO` file from a directory
that doesn't have one
"""
pass
| null |
8,144 | versioningit.errors | NotVCSError |
Raised when ``versioningit`` is run in a directory that is not under
version control or when the relevant VCS program is not installed
| class NotVCSError(Error):
"""
Raised when ``versioningit`` is run in a directory that is not under
version control or when the relevant VCS program is not installed
"""
pass
| null |
8,145 | versioningit.errors | NotVersioningitError |
Raised when ``versioningit`` is used on a project that does not have
``versioningit`` enabled
| class NotVersioningitError(Error):
"""
Raised when ``versioningit`` is used on a project that does not have
``versioningit`` enabled
"""
pass
| null |
8,146 | versioningit.onbuild | OnbuildFile |
.. versionadded:: 3.0.0
An abstract base class for opening a file in a project currently being
built
| class OnbuildFile(ABC):
"""
.. versionadded:: 3.0.0
An abstract base class for opening a file in a project currently being
built
"""
@overload
def open(
self,
mode: TextMode = "r",
encoding: str | None = None,
errors: str | None = None,
newline: str | None = None,
) -> TextIO:
...
@overload
def open(
self,
mode: BinaryMode,
encoding: None = None,
errors: None = None,
newline: None = None,
) -> IO[bytes]:
...
@abstractmethod
def open(
self,
mode: TextMode | BinaryMode = "r",
encoding: str | None = None,
errors: str | None = None,
newline: str | None = None,
) -> IO:
"""
Open the associated file. ``mode`` must be ``"r"``, ``"w"``, ``"a"``,
``"rb"``, ``"br"``, ``"wb"``, ``"bw"``, ``"ab"``, or ``"ba"``.
When opening a file for writing or appending, if the file does not
already exist, any parent directories are created automatically.
"""
...
| () |
8,147 | versioningit.onbuild | open |
Open the associated file. ``mode`` must be ``"r"``, ``"w"``, ``"a"``,
``"rb"``, ``"br"``, ``"wb"``, ``"bw"``, ``"ab"``, or ``"ba"``.
When opening a file for writing or appending, if the file does not
already exist, any parent directories are created automatically.
| @abstractmethod
def open(
self,
mode: TextMode | BinaryMode = "r",
encoding: str | None = None,
errors: str | None = None,
newline: str | None = None,
) -> IO:
"""
Open the associated file. ``mode`` must be ``"r"``, ``"w"``, ``"a"``,
``"rb"``, ``"br"``, ``"wb"``, ``"bw"``, ``"ab"``, or ``"ba"``.
When opening a file for writing or appending, if the file does not
already exist, any parent directories are created automatically.
"""
...
| (self, mode: 'TextMode | BinaryMode' = 'r', encoding: 'str | None' = None, errors: 'str | None' = None, newline: 'str | None' = None) -> 'IO' |
8,148 | versioningit.onbuild | OnbuildFileProvider |
.. versionadded:: 3.0.0
An abstract base class for accessing files that are about to be included in
an sdist or wheel currently being built
| class OnbuildFileProvider(ABC):
"""
.. versionadded:: 3.0.0
An abstract base class for accessing files that are about to be included in
an sdist or wheel currently being built
"""
@abstractmethod
def get_file(
self, source_path: str | PurePath, install_path: str | PurePath, is_source: bool
) -> OnbuildFile:
"""
Get an object for reading & writing a file in the project being built.
:param source_path:
the path to the file relative to the root of the project's source
:param install_path:
the path to the same file when it's in a wheel, relative to the
root of the wheel (or, equivalently, the path to the file when it's
installed in a site-packages directory, relative to that directory)
:param is_source:
`True` if building an sdist or other artifact that preserves source
paths, `False` if building a wheel or other artifact that uses
install paths
"""
...
| () |
8,149 | versioningit.onbuild | get_file |
Get an object for reading & writing a file in the project being built.
:param source_path:
the path to the file relative to the root of the project's source
:param install_path:
the path to the same file when it's in a wheel, relative to the
root of the wheel (or, equivalently, the path to the file when it's
installed in a site-packages directory, relative to that directory)
:param is_source:
`True` if building an sdist or other artifact that preserves source
paths, `False` if building a wheel or other artifact that uses
install paths
| @abstractmethod
def get_file(
self, source_path: str | PurePath, install_path: str | PurePath, is_source: bool
) -> OnbuildFile:
"""
Get an object for reading & writing a file in the project being built.
:param source_path:
the path to the file relative to the root of the project's source
:param install_path:
the path to the same file when it's in a wheel, relative to the
root of the wheel (or, equivalently, the path to the file when it's
installed in a site-packages directory, relative to that directory)
:param is_source:
`True` if building an sdist or other artifact that preserves source
paths, `False` if building a wheel or other artifact that uses
install paths
"""
...
| (self, source_path: str | pathlib.PurePath, install_path: str | pathlib.PurePath, is_source: bool) -> versioningit.onbuild.OnbuildFile |
8,150 | versioningit.core | Report |
.. versionadded:: 2.0.0
A report of the intermediate & final values calculated during a
``versioningit`` run
| class Report:
"""
.. versionadded:: 2.0.0
A report of the intermediate & final values calculated during a
``versioningit`` run
"""
#: The final version
version: str
#: A description of the state of the version control repository; `None` if
#: the "vcs" step failed
description: Optional[VCSDescription]
#: A version string extracted from the VCS tag; `None` if the "tag2version"
#: step or a previous step failed
base_version: Optional[str]
#: A "next version" calculated by the "next-version" step; `None` if the
#: step or a previous one failed
next_version: Optional[str]
#: A `dict` of fields for use in templating by the "write" and "onbuild"
#: steps
template_fields: dict[str, Any]
#: `True` iff an error occurred during version calculation, causing a
#: ``default-version`` setting to be used
using_default_version: bool
| (version: str, description: Optional[versioningit.core.VCSDescription], base_version: Optional[str], next_version: Optional[str], template_fields: dict[str, typing.Any], using_default_version: bool) -> None |
8,154 | versioningit.core | VCSDescription | A description of the state of a version control repository | class VCSDescription:
"""A description of the state of a version control repository"""
#: The name of the most recent tag in the repository (possibly after
#: applying any match or exclusion rules based on user parameters) from
#: which the current repository state is descended
tag: str
#: The relationship of the repository's current state to the tag. If the
#: repository state is exactly the tagged state, this field should equal
#: ``"exact"``; otherwise, it will be a string that will be used as a key
#: in the ``format`` subtable of the versioningit configuration.
#: Recommended values are ``"distance"``, ``"dirty"``, and
#: ``"distance-dirty"``.
state: str
#: The name of the repository's current branch, or `None` if it cannot be
#: determined or does not apply
branch: Optional[str]
#: A `dict` of additional information about the repository state to make
#: available to the ``format`` method. Custom ``vcs`` methods are advised
#: to adhere closely to the set of fields used by the built-in methods.
fields: dict[str, Any]
| (tag: str, state: str, branch: Optional[str], fields: dict[str, typing.Any]) -> None |
8,158 | versioningit.core | Versioningit |
A class for getting a version-controlled project's current version based on
its most recent tag and the difference therefrom
| class Versioningit:
"""
A class for getting a version-controlled project's current version based on
its most recent tag and the difference therefrom
"""
#: The path to the root of the project directory (usually the location of a
#: :file:`pyproject.toml` file)
#:
#: :meta private:
project_dir: Path
#: The default version, if any, to use if an error occurs
#:
#: :meta private:
default_version: Optional[str]
#: The method to call for the ``vcs`` step
#:
#: :meta private:
vcs: VersioningitMethod
#: The method to call for the ``tag2version`` step
#:
#: :meta private:
tag2version: VersioningitMethod
#: The method to call for the ``next-version`` step
#:
#: :meta private:
next_version: VersioningitMethod
#: The method to call for the ``format`` step
#:
#: :meta private:
format: VersioningitMethod
#: The method to call for the ``template-fields`` step
#:
#: :meta private:
template_fields: VersioningitMethod
#: The method to call for the ``write`` step
#:
#: :meta private:
write: Optional[VersioningitMethod]
#: The method to call for the ``onbuild`` step
#:
#: :meta private:
onbuild: Optional[VersioningitMethod]
@classmethod
def from_project_dir(
cls, project_dir: str | Path = os.curdir, config: Optional[dict] = None
) -> Versioningit:
"""
Construct a `Versioningit` object for the project rooted at
``project_dir`` (default: the current directory).
If ``config`` is `None`, then ``project_dir`` must contain a
:file:`pyproject.toml` file containing either a ``[tool.versioningit]``
table or a ``[tool.hatch.version]`` table with the ``source`` key set
to ``"versioningit"``; if it does not, a `NotVersioningitError` is
raised. If ``config`` is not `None`, then any :file:`pyproject.toml`
file in ``project_dir`` will be ignored, and the configuration will be
taken from ``config`` instead. See ":ref:`config_dict`".
:raises NotVersioningitError:
- if ``config`` is `None` and ``project_dir`` does not contain a
:file:`pyproject.toml` file
- if ``config`` is `None` and the :file:`pyproject.toml` file does
not contain a versioningit configuration table
:raises ConfigError:
if the configuration object/table or any of its subfields are not
of the correct type
"""
if config is None:
try:
cfg = Config.parse_toml_file(Path(project_dir, "pyproject.toml"))
except FileNotFoundError:
raise NotVersioningitError(f"No pyproject.toml file in {project_dir}")
else:
cfg = Config.parse_obj(config)
return cls.from_config(project_dir, cfg)
@classmethod
def from_config(cls, project_dir: str | Path, config: Config) -> Versioningit:
"""
Construct a `Versioningit` object from a parsed configuration object
:meta private:
"""
project_dir = Path(project_dir)
return cls(
project_dir=project_dir,
default_version=config.default_version,
vcs=config.vcs.load(project_dir),
tag2version=config.tag2version.load(project_dir),
next_version=config.next_version.load(project_dir),
format=config.format.load(project_dir),
template_fields=config.template_fields.load(project_dir),
write=config.write.load(project_dir) if config.write is not None else None,
onbuild=config.onbuild.load(project_dir)
if config.onbuild is not None
else None,
)
def get_version(self, write: bool = False, fallback: bool = True) -> str:
"""
Determine the version for the project.
If ``write`` is true, then the file specified in the ``write`` subtable
of the versioningit configuration, if any, will be updated.
If ``fallback`` is true, then if ``project_dir`` is not under version
control (or if the VCS executable is not installed), ``versioningit``
will assume that the directory is an unpacked sdist and will read the
version from the :file:`PKG-INFO` file.
.. versionchanged:: 2.0.0
``write`` and ``fallback`` arguments added
:raises NotVCSError:
if ``fallback`` is false and ``project_dir`` is not under version
control
:raises NotSdistError:
if ``fallback`` is true, ``project_dir`` is not under version
control, and there is no :file:`PKG-INFO` file in ``project_dir``
:raises ConfigError:
if any of the values in ``config`` are not of the correct type
:raises MethodError: if a method returns a value of the wrong type
"""
return self.run(write=write, fallback=fallback).version
def run(
self, write: bool = False, fallback: bool = True
) -> Report | FallbackReport:
"""
.. versionadded:: 2.0.0
Run all of the steps for the project — aside from "onbuild" and,
optionally, "write" — and return an object containing the final version
and intermediate values.
If ``write`` is true, then the file specified in the ``write`` subtable
of the versioningit configuration, if any, will be updated.
If ``fallback`` is true, then if ``project_dir`` is not under version
control (or if the VCS executable is not installed), ``versioningit``
will assume that the directory is an unpacked sdist and will read the
version from the :file:`PKG-INFO` file, returning a `FallbackReport`
instance instead of a `Report`.
:raises NotVCSError:
if ``fallback`` is false and ``project_dir`` is not under version
control
:raises NotSdistError:
if ``fallback`` is true, ``project_dir`` is not under version
control, and there is no :file:`PKG-INFO` file in ``project_dir``
:raises ConfigError:
if any of the values in ``config`` are not of the correct type
:raises MethodError: if a method returns a value of the wrong type
"""
description: Optional[VCSDescription] = None
base_version: Optional[str] = None
next_version: Optional[str] = None
using_default_version: bool = False
try:
description = self.do_vcs()
base_version = self.do_tag2version(description.tag)
next_version = self.do_next_version(base_version, description.branch)
if description.state == "exact":
log.info("Tag is exact match; returning extracted version")
version = base_version
else:
log.info("VCS state is %r; formatting version", description.state)
version = self.do_format(
description=description,
base_version=base_version,
next_version=next_version,
)
log.info("Final version: %s", version)
except Error as e:
if (
isinstance(e, NotVCSError)
and fallback
and (is_sdist(self.project_dir) or self.default_version is None)
):
log.info("Could not get VCS data from %s: %s", self.project_dir, str(e))
log.info("Falling back to reading from PKG-INFO")
return FallbackReport(
version=get_version_from_pkg_info(self.project_dir)
)
if self.default_version is not None:
log.error("%s: %s", type(e).__name__, str(e))
log.info("Falling back to default-version")
version = self.default_version
using_default_version = True
else:
raise
except Exception: # pragma: no cover
if self.default_version is not None:
log.exception("An unexpected error occurred:")
log.info("Falling back to default-version")
version = self.default_version
using_default_version = True
else:
raise
warn_bad_version(version, "Final version")
template_fields = self.do_template_fields(
version=version,
description=description,
base_version=base_version,
next_version=next_version,
)
if write:
self.do_write(template_fields)
return Report(
version=version,
description=description,
base_version=base_version,
next_version=next_version,
template_fields=template_fields,
using_default_version=using_default_version,
)
def do_vcs(self) -> VCSDescription:
"""
Run the ``vcs`` step
:raises MethodError: if the method does not return a `VCSDescription`
"""
description = self.vcs(project_dir=self.project_dir)
if not isinstance(description, VCSDescription):
raise MethodError(
f"vcs method returned {description!r} instead of a VCSDescription"
)
log.info("vcs returned tag %s", description.tag)
log.debug("vcs state: %s", description.state)
log.debug("vcs branch: %s", description.branch)
log.debug("vcs fields: %r", description.fields)
return description
def do_tag2version(self, tag: str) -> str:
"""
Run the ``tag2version`` step
:raises MethodError: if the method does not return a `str`
"""
version = self.tag2version(tag=tag)
if not isinstance(version, str):
raise MethodError(
f"tag2version method returned {version!r} instead of a string"
)
log.info("tag2version returned version %s", version)
warn_bad_version(version, "Version extracted from tag")
return version
def do_next_version(self, version: str, branch: Optional[str]) -> str:
"""
Run the ``next-version`` step
:raises MethodError: if the method does not return a `str`
"""
next_version = self.next_version(version=version, branch=branch)
if not isinstance(next_version, str):
raise MethodError(
f"next-version method returned {next_version!r} instead of a string"
)
log.info("next-version returned version %s", next_version)
warn_bad_version(next_version, "Calculated next version")
return next_version
def do_format(
self, description: VCSDescription, base_version: str, next_version: str
) -> str:
"""
Run the ``format`` step
.. versionchanged:: 2.0.0
The ``version`` argument was renamed to ``base_version``.
:raises MethodError: if the method does not return a `str`
"""
new_version = self.format(
description=description,
base_version=base_version,
next_version=next_version,
)
if not isinstance(new_version, str):
raise MethodError(
f"format method returned {new_version!r} instead of a string"
)
return new_version
def do_template_fields(
self,
version: str,
description: Optional[VCSDescription],
base_version: Optional[str],
next_version: Optional[str],
) -> dict:
"""
.. versionadded:: 2.0.0
Run the ``template_fields`` step
:raises MethodError: if the method does not return a `dict`
"""
fields = self.template_fields(
version=version,
description=description,
base_version=base_version,
next_version=next_version,
)
if not isinstance(fields, dict):
raise MethodError(
f"template-fields method returned {fields!r} instead of a dict"
)
log.debug("Template fields available to `write` and `onbuild`: %r", fields)
return fields
def do_write(self, template_fields: dict[str, Any]) -> None:
"""
Run the ``write`` step
.. versionchanged:: 2.0.0
``version`` argument replaced with ``template_fields``
"""
if self.write is not None:
self.write(project_dir=self.project_dir, template_fields=template_fields)
else:
log.info("'write' step not configured; not writing anything")
def do_onbuild(
self,
file_provider: OnbuildFileProvider,
is_source: bool,
template_fields: dict[str, Any],
) -> None:
"""
.. versionadded:: 1.1.0
Run the ``onbuild`` step
.. versionchanged:: 2.0.0
``version`` argument replaced with ``template_fields``
.. versionchanged:: 3.0.0
``build_dir`` argument replaced with ``file_provider``
"""
if self.onbuild is not None:
self.onbuild(
file_provider=file_provider,
is_source=is_source,
template_fields=template_fields,
)
else:
log.info("'onbuild' step not configured; not doing anything")
| (project_dir: pathlib.Path, default_version: Optional[str], vcs: versioningit.methods.VersioningitMethod, tag2version: versioningit.methods.VersioningitMethod, next_version: versioningit.methods.VersioningitMethod, format: versioningit.methods.VersioningitMethod, template_fields: versioningit.methods.VersioningitMethod, write: Optional[versioningit.methods.VersioningitMethod], onbuild: Optional[versioningit.methods.VersioningitMethod]) -> None |
Subsets and Splits