Upgrade to mypy 0.812 (#8748)
Fixes #8425
This PR upgrades mypy to the latest version available, 0.812.
Given the advanced type inference capabilities provided by this newer version, this PRs also fixes various type inconsistencies that are now detected. Here are the non obvious changes done to fix types:
* typing in mixins has been solved using `Protocol` classes, as recommended by mypy (https://mypy.readthedocs.io/en/latest/more_types.html#mixin-classes, https://mypy.readthedocs.io/en/stable/protocols.html)
* `cast` when we are playing with `Union` types
This PR also disables the strict optional checks that have been enable by default in recent versions of mypy. Once this PR is merged, I will create an issue to study how these checks can be enabled.
`typing.Protocol` is available only since Python 3.8. To keep compatibility with Python 3.6, I try to import the class `Protocol` from `typing`, and fallback to assign `object` to `Protocol` if that fails. This way the code is working with all versions of Python, but the mypy check can be run only with Python 3.8+ because it needs the protocol feature. As a consequence, tox runs mypy under Python 3.8.
Alternatives are:
* importing `typing_extensions`, that proposes backport of newest typing features to Python 3.6, but this implies to add a dependency to Certbot just to run mypy
* redesign the concerned classes to not use mixins, or use them differently, but this implies to modify the code itself even if there is nothing wrong with it and it is just a matter of instructing mypy to understand in which context the mixins can be used
* ignoring type for these classes with `# type: ignore` but we loose the benefit of mypy for them
* Upgrade mypy
* First step for acme
* Cast for the rescue
* Fixing types for certbot
* Fix typing for certbot-nginx
* Finalize type fixes, configure no optional strict check for mypy in tox
* Align requirements
* Isort
* Pylint
* Protocol for python 3.6
* Use Python 3.9 for mypy, make code compatible with Python 3.8<
* Pylint and mypy
* Pragma no cover
* Pythonic NotImplemented constant
* More type definitions
* Add comments
* Simplify typing logic
* Use vararg tuple
* Relax constraints on mypy
* Add more type
* Do not silence error if target is not defined
* Conditionally import Protocol for type checking only
* Clean up imports
* Add comments
* Align python version linting with mypy and coverage
* Just ignore types in an unused module
* Add comments
* Fix lint
2021-04-02 14:54:40 -04:00
|
|
|
# type: ignore
|
|
|
|
|
# This module is not used for now, so we just skip type check for the sake of simplicity.
|
2018-10-19 15:30:32 -04:00
|
|
|
""" This file contains parsing routines and object classes to help derive meaning from
|
|
|
|
|
raw lists of tokens from pyparsing. """
|
|
|
|
|
|
|
|
|
|
import abc
|
|
|
|
|
import logging
|
2022-01-12 19:36:51 -05:00
|
|
|
from typing import Any
|
|
|
|
|
from typing import Callable
|
|
|
|
|
from typing import Iterator
|
2021-03-09 19:12:32 -05:00
|
|
|
from typing import List
|
2022-01-12 19:36:51 -05:00
|
|
|
from typing import Optional
|
|
|
|
|
from typing import Sequence
|
|
|
|
|
from typing import Tuple
|
|
|
|
|
from typing import Type
|
2019-12-09 15:50:20 -05:00
|
|
|
|
2018-10-19 15:30:32 -04:00
|
|
|
from certbot import errors
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
COMMENT = " managed by Certbot"
|
|
|
|
|
COMMENT_BLOCK = ["#", COMMENT]
|
|
|
|
|
|
2019-04-02 16:48:22 -04:00
|
|
|
|
2021-02-25 17:59:00 -05:00
|
|
|
class Parsable:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Abstract base class for "Parsable" objects whose underlying representation
|
|
|
|
|
is a tree of lists.
|
|
|
|
|
|
|
|
|
|
:param .Parsable parent: This object's parsed parent in the tree
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
__metaclass__ = abc.ABCMeta
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def __init__(self, parent: Optional["Parsable"] = None):
|
|
|
|
|
self._data: List[Any] = []
|
2018-10-19 15:30:32 -04:00
|
|
|
self._tabs = None
|
|
|
|
|
self.parent = parent
|
|
|
|
|
|
|
|
|
|
@classmethod
|
2022-01-12 19:36:51 -05:00
|
|
|
def parsing_hooks(cls) -> Tuple[Type["Block"], Type["Sentence"], Type["Statements"]]:
|
2018-10-19 15:30:32 -04:00
|
|
|
"""Returns object types that this class should be able to `parse` recusrively.
|
|
|
|
|
The order of the objects indicates the order in which the parser should
|
|
|
|
|
try to parse each subitem.
|
|
|
|
|
:returns: A list of Parsable classes.
|
|
|
|
|
:rtype list:
|
|
|
|
|
"""
|
2022-01-12 19:36:51 -05:00
|
|
|
return Block, Sentence, Statements
|
2018-10-19 15:30:32 -04:00
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
@abc.abstractmethod
|
2022-01-12 19:36:51 -05:00
|
|
|
def should_parse(lists: Any) -> bool:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Returns whether the contents of `lists` can be parsed into this object.
|
|
|
|
|
|
|
|
|
|
:returns: Whether `lists` can be parsed as this object.
|
|
|
|
|
:rtype bool:
|
|
|
|
|
"""
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
2022-01-12 19:36:51 -05:00
|
|
|
def parse(self, raw_list: List[Any], add_spaces: bool = False) -> None:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Loads information into this object from underlying raw_list structure.
|
|
|
|
|
Each Parsable object might make different assumptions about the structure of
|
|
|
|
|
raw_list.
|
|
|
|
|
|
|
|
|
|
:param list raw_list: A list or sublist of tokens from pyparsing, containing whitespace
|
|
|
|
|
as separate tokens.
|
|
|
|
|
:param bool add_spaces: If set, the method can and should manipulate and insert spacing
|
|
|
|
|
between non-whitespace tokens and lists to delimit them.
|
|
|
|
|
:raises .errors.MisconfigurationError: when the assumptions about the structure of
|
|
|
|
|
raw_list are not met.
|
|
|
|
|
"""
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
2022-01-12 19:36:51 -05:00
|
|
|
def iterate(self, expanded: bool = False,
|
|
|
|
|
match: Optional[Callable[["Parsable"], bool]] = None) -> Iterator[Any]:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Iterates across this object. If this object is a leaf object, only yields
|
|
|
|
|
itself. If it contains references other parsing objects, and `expanded` is set,
|
|
|
|
|
this function should first yield itself, then recursively iterate across all of them.
|
|
|
|
|
:param bool expanded: Whether to recursively iterate on possible children.
|
|
|
|
|
:param callable match: If provided, an object is only iterated if this callable
|
|
|
|
|
returns True when called on that object.
|
|
|
|
|
|
|
|
|
|
:returns: Iterator over desired objects.
|
|
|
|
|
"""
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
2022-01-12 19:36:51 -05:00
|
|
|
def get_tabs(self) -> str:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Guess at the tabbing style of this parsed object, based on whitespace.
|
|
|
|
|
|
|
|
|
|
If this object is a leaf, it deducts the tabbing based on its own contents.
|
|
|
|
|
Other objects may guess by calling `get_tabs` recursively on child objects.
|
|
|
|
|
|
|
|
|
|
:returns: Guess at tabbing for this object. Should only return whitespace strings
|
|
|
|
|
that does not contain newlines.
|
|
|
|
|
:rtype str:
|
|
|
|
|
"""
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
2022-01-12 19:36:51 -05:00
|
|
|
def set_tabs(self, tabs: str = " ") -> None:
|
2018-10-19 15:30:32 -04:00
|
|
|
"""This tries to set and alter the tabbing of the current object to a desired
|
|
|
|
|
whitespace string. Primarily meant for objects that were constructed, so they
|
|
|
|
|
can conform to surrounding whitespace.
|
|
|
|
|
|
|
|
|
|
:param str tabs: A whitespace string (not containing newlines).
|
|
|
|
|
"""
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def dump(self, include_spaces: bool = False) -> List[Any]:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Dumps back to pyparsing-like list tree. The opposite of `parse`.
|
|
|
|
|
|
|
|
|
|
Note: if this object has not been modified, `dump` with `include_spaces=True`
|
|
|
|
|
should always return the original input of `parse`.
|
|
|
|
|
|
|
|
|
|
:param bool include_spaces: If set to False, magically hides whitespace tokens from
|
|
|
|
|
dumped output.
|
|
|
|
|
|
|
|
|
|
:returns: Pyparsing-like list tree.
|
|
|
|
|
:rtype list:
|
|
|
|
|
"""
|
|
|
|
|
return [elem.dump(include_spaces) for elem in self._data]
|
|
|
|
|
|
2019-04-02 16:48:22 -04:00
|
|
|
|
2018-10-19 15:30:32 -04:00
|
|
|
class Statements(Parsable):
|
|
|
|
|
""" A group or list of "Statements". A Statement is either a Block or a Sentence.
|
|
|
|
|
|
|
|
|
|
The underlying representation is simply a list of these Statement objects, with
|
|
|
|
|
an extra `_trailing_whitespace` string to keep track of the whitespace that does not
|
|
|
|
|
precede any more statements.
|
|
|
|
|
"""
|
2022-01-12 19:36:51 -05:00
|
|
|
def __init__(self, parent: Optional[Parsable] = None):
|
2021-04-08 16:04:51 -04:00
|
|
|
super().__init__(parent)
|
2018-10-19 15:30:32 -04:00
|
|
|
self._trailing_whitespace = None
|
|
|
|
|
|
|
|
|
|
# ======== Begin overridden functions
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
2022-01-12 19:36:51 -05:00
|
|
|
def should_parse(lists: Any) -> bool:
|
2018-10-19 15:30:32 -04:00
|
|
|
return isinstance(lists, list)
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def set_tabs(self, tabs: str = " ") -> None:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Sets the tabbing for this set of statements. Does this by calling `set_tabs`
|
|
|
|
|
on each of the child statements.
|
|
|
|
|
|
|
|
|
|
Then, if a parent is present, sets trailing whitespace to parent tabbing. This
|
|
|
|
|
is so that the trailing } of any Block that contains Statements lines up
|
|
|
|
|
with parent tabbing.
|
|
|
|
|
"""
|
|
|
|
|
for statement in self._data:
|
|
|
|
|
statement.set_tabs(tabs)
|
|
|
|
|
if self.parent is not None:
|
|
|
|
|
self._trailing_whitespace = "\n" + self.parent.get_tabs()
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def parse(self, raw_list: List[Any], add_spaces: bool = False) -> None:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Parses a list of statements.
|
2019-04-02 16:48:22 -04:00
|
|
|
Expects all elements in `raw_list` to be parseable by `type(self).parsing_hooks`,
|
|
|
|
|
with an optional whitespace string at the last index of `raw_list`.
|
2018-10-19 15:30:32 -04:00
|
|
|
"""
|
2019-04-02 16:48:22 -04:00
|
|
|
if not isinstance(raw_list, list):
|
2018-10-19 15:30:32 -04:00
|
|
|
raise errors.MisconfigurationError("Statements parsing expects a list!")
|
|
|
|
|
# If there's a trailing whitespace in the list of statements, keep track of it.
|
2021-02-09 14:43:15 -05:00
|
|
|
if raw_list and isinstance(raw_list[-1], str) and raw_list[-1].isspace():
|
2019-04-02 16:48:22 -04:00
|
|
|
self._trailing_whitespace = raw_list[-1]
|
|
|
|
|
raw_list = raw_list[:-1]
|
|
|
|
|
self._data = [parse_raw(elem, self, add_spaces) for elem in raw_list]
|
2018-10-19 15:30:32 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def get_tabs(self) -> str:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Takes a guess at the tabbing of all contained Statements by retrieving the
|
|
|
|
|
tabbing of the first Statement."""
|
2019-04-02 16:48:22 -04:00
|
|
|
if self._data:
|
2018-10-19 15:30:32 -04:00
|
|
|
return self._data[0].get_tabs()
|
|
|
|
|
return ""
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def dump(self, include_spaces: bool = False) -> List[Any]:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Dumps this object by first dumping each statement, then appending its
|
|
|
|
|
trailing whitespace (if `include_spaces` is set) """
|
2021-04-08 16:04:51 -04:00
|
|
|
data = super().dump(include_spaces)
|
2018-10-19 15:30:32 -04:00
|
|
|
if include_spaces and self._trailing_whitespace is not None:
|
|
|
|
|
return data + [self._trailing_whitespace]
|
|
|
|
|
return data
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def iterate(self, expanded: bool = False,
|
|
|
|
|
match: Optional[Callable[["Parsable"], bool]] = None) -> Iterator[Any]:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Combines each statement's iterator. """
|
|
|
|
|
for elem in self._data:
|
|
|
|
|
for sub_elem in elem.iterate(expanded, match):
|
|
|
|
|
yield sub_elem
|
|
|
|
|
|
|
|
|
|
# ======== End overridden functions
|
|
|
|
|
|
2019-04-02 16:48:22 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _space_list(list_: Sequence[Any]) -> List[str]:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Inserts whitespace between adjacent non-whitespace tokens. """
|
2021-03-10 14:51:27 -05:00
|
|
|
spaced_statement: List[str] = []
|
2021-02-09 14:43:15 -05:00
|
|
|
for i in reversed(range(len(list_))):
|
2018-10-19 15:30:32 -04:00
|
|
|
spaced_statement.insert(0, list_[i])
|
|
|
|
|
if i > 0 and not list_[i].isspace() and not list_[i-1].isspace():
|
|
|
|
|
spaced_statement.insert(0, " ")
|
|
|
|
|
return spaced_statement
|
|
|
|
|
|
2019-04-02 16:48:22 -04:00
|
|
|
|
2018-10-19 15:30:32 -04:00
|
|
|
class Sentence(Parsable):
|
|
|
|
|
""" A list of words. Non-whitespace words are typically separated with whitespace tokens. """
|
|
|
|
|
|
|
|
|
|
# ======== Begin overridden functions
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
2022-01-12 19:36:51 -05:00
|
|
|
def should_parse(lists: Any) -> bool:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Returns True if `lists` can be parseable as a `Sentence`-- that is,
|
|
|
|
|
every element is a string type.
|
|
|
|
|
|
|
|
|
|
:param list lists: The raw unparsed list to check.
|
|
|
|
|
|
|
|
|
|
:returns: whether this lists is parseable by `Sentence`.
|
|
|
|
|
"""
|
2022-01-12 19:36:51 -05:00
|
|
|
return (isinstance(lists, list) and len(lists) > 0 and
|
|
|
|
|
all(isinstance(elem, str) for elem in lists))
|
2018-10-19 15:30:32 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def parse(self, raw_list: List[Any], add_spaces: bool = False) -> None:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Parses a list of string types into this object.
|
|
|
|
|
If add_spaces is set, adds whitespace tokens between adjacent non-whitespace tokens."""
|
|
|
|
|
if add_spaces:
|
2019-04-02 16:48:22 -04:00
|
|
|
raw_list = _space_list(raw_list)
|
2022-01-12 19:36:51 -05:00
|
|
|
if (not isinstance(raw_list, list)
|
|
|
|
|
or any(not isinstance(elem, str) for elem in raw_list)):
|
2018-10-19 15:30:32 -04:00
|
|
|
raise errors.MisconfigurationError("Sentence parsing expects a list of string types.")
|
2019-04-02 16:48:22 -04:00
|
|
|
self._data = raw_list
|
2018-10-19 15:30:32 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def iterate(self, expanded: bool = False,
|
|
|
|
|
match: Optional[Callable[[Parsable], bool]] = None) -> Iterator[Any]:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Simply yields itself. """
|
|
|
|
|
if match is None or match(self):
|
|
|
|
|
yield self
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def set_tabs(self, tabs: str = " ") -> None:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Sets the tabbing on this sentence. Inserts a newline and `tabs` at the
|
|
|
|
|
beginning of `self._data`. """
|
|
|
|
|
if self._data[0].isspace():
|
|
|
|
|
return
|
|
|
|
|
self._data.insert(0, "\n" + tabs)
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def dump(self, include_spaces: bool = False) -> List[Any]:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Dumps this sentence. If include_spaces is set, includes whitespace tokens."""
|
|
|
|
|
if not include_spaces:
|
|
|
|
|
return self.words
|
|
|
|
|
return self._data
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def get_tabs(self) -> str:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Guesses at the tabbing of this sentence. If the first element is whitespace,
|
|
|
|
|
returns the whitespace after the rightmost newline in the string. """
|
|
|
|
|
first = self._data[0]
|
|
|
|
|
if not first.isspace():
|
|
|
|
|
return ""
|
|
|
|
|
rindex = first.rfind("\n")
|
|
|
|
|
return first[rindex+1:]
|
|
|
|
|
|
|
|
|
|
# ======== End overridden functions
|
|
|
|
|
|
|
|
|
|
@property
|
2022-01-12 19:36:51 -05:00
|
|
|
def words(self) -> List[str]:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Iterates over words, but without spaces. Like Unspaced List. """
|
|
|
|
|
return [word.strip("\"\'") for word in self._data if not word.isspace()]
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def __getitem__(self, index: int) -> str:
|
2018-10-19 15:30:32 -04:00
|
|
|
return self.words[index]
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def __contains__(self, word: str) -> bool:
|
2018-10-19 15:30:32 -04:00
|
|
|
return word in self.words
|
|
|
|
|
|
2019-04-02 16:48:22 -04:00
|
|
|
|
2018-10-19 15:30:32 -04:00
|
|
|
class Block(Parsable):
|
2021-09-02 16:43:13 -04:00
|
|
|
""" Any sort of block, denoted by a block name and curly braces, like so:
|
2018-10-19 15:30:32 -04:00
|
|
|
The parsed block:
|
|
|
|
|
block name {
|
|
|
|
|
content 1;
|
|
|
|
|
content 2;
|
|
|
|
|
}
|
|
|
|
|
might be represented with the list [names, contents], where
|
|
|
|
|
names = ["block", " ", "name", " "]
|
|
|
|
|
contents = [["\n ", "content", " ", "1"], ["\n ", "content", " ", "2"], "\n"]
|
|
|
|
|
"""
|
2022-01-12 19:36:51 -05:00
|
|
|
def __init__(self, parent: Optional[Parsable] = None) -> None:
|
2021-04-08 16:04:51 -04:00
|
|
|
super().__init__(parent)
|
2022-01-12 19:36:51 -05:00
|
|
|
self.names: Optional[Sentence] = None
|
|
|
|
|
self.contents: Optional[Block] = None
|
2018-10-19 15:30:32 -04:00
|
|
|
|
|
|
|
|
@staticmethod
|
2022-01-12 19:36:51 -05:00
|
|
|
def should_parse(lists: Any) -> bool:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Returns True if `lists` can be parseable as a `Block`-- that is,
|
|
|
|
|
it's got a length of 2, the first element is a `Sentence` and the second can be
|
|
|
|
|
a `Statements`.
|
|
|
|
|
|
|
|
|
|
:param list lists: The raw unparsed list to check.
|
|
|
|
|
|
|
|
|
|
:returns: whether this lists is parseable by `Block`. """
|
|
|
|
|
return isinstance(lists, list) and len(lists) == 2 and \
|
Upgrade to mypy 0.812 (#8748)
Fixes #8425
This PR upgrades mypy to the latest version available, 0.812.
Given the advanced type inference capabilities provided by this newer version, this PRs also fixes various type inconsistencies that are now detected. Here are the non obvious changes done to fix types:
* typing in mixins has been solved using `Protocol` classes, as recommended by mypy (https://mypy.readthedocs.io/en/latest/more_types.html#mixin-classes, https://mypy.readthedocs.io/en/stable/protocols.html)
* `cast` when we are playing with `Union` types
This PR also disables the strict optional checks that have been enable by default in recent versions of mypy. Once this PR is merged, I will create an issue to study how these checks can be enabled.
`typing.Protocol` is available only since Python 3.8. To keep compatibility with Python 3.6, I try to import the class `Protocol` from `typing`, and fallback to assign `object` to `Protocol` if that fails. This way the code is working with all versions of Python, but the mypy check can be run only with Python 3.8+ because it needs the protocol feature. As a consequence, tox runs mypy under Python 3.8.
Alternatives are:
* importing `typing_extensions`, that proposes backport of newest typing features to Python 3.6, but this implies to add a dependency to Certbot just to run mypy
* redesign the concerned classes to not use mixins, or use them differently, but this implies to modify the code itself even if there is nothing wrong with it and it is just a matter of instructing mypy to understand in which context the mixins can be used
* ignoring type for these classes with `# type: ignore` but we loose the benefit of mypy for them
* Upgrade mypy
* First step for acme
* Cast for the rescue
* Fixing types for certbot
* Fix typing for certbot-nginx
* Finalize type fixes, configure no optional strict check for mypy in tox
* Align requirements
* Isort
* Pylint
* Protocol for python 3.6
* Use Python 3.9 for mypy, make code compatible with Python 3.8<
* Pylint and mypy
* Pragma no cover
* Pythonic NotImplemented constant
* More type definitions
* Add comments
* Simplify typing logic
* Use vararg tuple
* Relax constraints on mypy
* Add more type
* Do not silence error if target is not defined
* Conditionally import Protocol for type checking only
* Clean up imports
* Add comments
* Align python version linting with mypy and coverage
* Just ignore types in an unused module
* Add comments
* Fix lint
2021-04-02 14:54:40 -04:00
|
|
|
Sentence.should_parse(lists[0]) and isinstance(lists[1], list)
|
2018-10-19 15:30:32 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def set_tabs(self, tabs: str = " ") -> None:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Sets tabs by setting equivalent tabbing on names, then adding tabbing
|
|
|
|
|
to contents."""
|
|
|
|
|
self.names.set_tabs(tabs)
|
|
|
|
|
self.contents.set_tabs(tabs + " ")
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def iterate(self, expanded: bool = False,
|
|
|
|
|
match: Optional[Callable[[Parsable], bool]] = None) -> Iterator[Any]:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Iterator over self, and if expanded is set, over its contents. """
|
|
|
|
|
if match is None or match(self):
|
|
|
|
|
yield self
|
|
|
|
|
if expanded:
|
|
|
|
|
for elem in self.contents.iterate(expanded, match):
|
|
|
|
|
yield elem
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def parse(self, raw_list: List[Any], add_spaces: bool = False) -> None:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Parses a list that resembles a block.
|
|
|
|
|
|
|
|
|
|
The assumptions that this routine makes are:
|
2019-04-02 16:48:22 -04:00
|
|
|
1. the first element of `raw_list` is a valid Sentence.
|
|
|
|
|
2. the second element of `raw_list` is a valid Statement.
|
2018-10-19 15:30:32 -04:00
|
|
|
If add_spaces is set, we call it recursively on `names` and `contents`, and
|
|
|
|
|
add an extra trailing space to `names` (to separate the block's opening bracket
|
|
|
|
|
and the block name).
|
|
|
|
|
"""
|
2019-04-02 16:48:22 -04:00
|
|
|
if not Block.should_parse(raw_list):
|
2018-10-19 15:30:32 -04:00
|
|
|
raise errors.MisconfigurationError("Block parsing expects a list of length 2. "
|
2021-09-02 16:43:13 -04:00
|
|
|
"First element should be a list of string types (the block names), "
|
|
|
|
|
"and second should be another list of statements (the block content).")
|
2018-10-19 15:30:32 -04:00
|
|
|
self.names = Sentence(self)
|
|
|
|
|
if add_spaces:
|
2019-04-02 16:48:22 -04:00
|
|
|
raw_list[0].append(" ")
|
|
|
|
|
self.names.parse(raw_list[0], add_spaces)
|
2018-10-19 15:30:32 -04:00
|
|
|
self.contents = Statements(self)
|
2019-04-02 16:48:22 -04:00
|
|
|
self.contents.parse(raw_list[1], add_spaces)
|
2018-10-19 15:30:32 -04:00
|
|
|
self._data = [self.names, self.contents]
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def get_tabs(self) -> str:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Guesses tabbing by retrieving tabbing guess of self.names. """
|
|
|
|
|
return self.names.get_tabs()
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _is_comment(parsed_obj: Parsable) -> bool:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Checks whether parsed_obj is a comment.
|
|
|
|
|
|
|
|
|
|
:param .Parsable parsed_obj:
|
|
|
|
|
|
|
|
|
|
:returns: whether parsed_obj represents a comment sentence.
|
|
|
|
|
:rtype bool:
|
|
|
|
|
"""
|
|
|
|
|
if not isinstance(parsed_obj, Sentence):
|
|
|
|
|
return False
|
|
|
|
|
return parsed_obj.words[0] == "#"
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _is_certbot_comment(parsed_obj: Parsable) -> bool:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Checks whether parsed_obj is a "managed by Certbot" comment.
|
|
|
|
|
|
|
|
|
|
:param .Parsable parsed_obj:
|
|
|
|
|
|
|
|
|
|
:returns: whether parsed_obj is a "managed by Certbot" comment.
|
|
|
|
|
:rtype bool:
|
|
|
|
|
"""
|
|
|
|
|
if not _is_comment(parsed_obj):
|
|
|
|
|
return False
|
|
|
|
|
if len(parsed_obj.words) != len(COMMENT_BLOCK):
|
|
|
|
|
return False
|
|
|
|
|
for i, word in enumerate(parsed_obj.words):
|
|
|
|
|
if word != COMMENT_BLOCK[i]:
|
|
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _certbot_comment(parent: Parsable, preceding_spaces: int = 4) -> Sentence:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" A "Managed by Certbot" comment.
|
|
|
|
|
:param int preceding_spaces: Number of spaces between the end of the previous
|
|
|
|
|
statement and the comment.
|
|
|
|
|
:returns: Sentence containing the comment.
|
|
|
|
|
:rtype: .Sentence
|
|
|
|
|
"""
|
|
|
|
|
result = Sentence(parent)
|
|
|
|
|
result.parse([" " * preceding_spaces] + COMMENT_BLOCK)
|
|
|
|
|
return result
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _choose_parser(parent: Parsable, list_: Any) -> Parsable:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Choose a parser from type(parent).parsing_hooks, depending on whichever hook
|
|
|
|
|
returns True first. """
|
|
|
|
|
hooks = Parsable.parsing_hooks()
|
|
|
|
|
if parent:
|
|
|
|
|
hooks = type(parent).parsing_hooks()
|
|
|
|
|
for type_ in hooks:
|
|
|
|
|
if type_.should_parse(list_):
|
|
|
|
|
return type_(parent)
|
|
|
|
|
raise errors.MisconfigurationError(
|
|
|
|
|
"None of the parsing hooks succeeded, so we don't know how to parse this set of lists.")
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def parse_raw(lists_: Any, parent: Optional[Parsable] = None, add_spaces: bool = False) -> Parsable:
|
2018-10-19 15:30:32 -04:00
|
|
|
""" Primary parsing factory function.
|
|
|
|
|
|
|
|
|
|
:param list lists_: raw lists from pyparsing to parse.
|
|
|
|
|
:param .Parent parent: The parent containing this object.
|
|
|
|
|
:param bool add_spaces: Whether to pass add_spaces to the parser.
|
|
|
|
|
|
|
|
|
|
:returns .Parsable: The parsed object.
|
|
|
|
|
|
|
|
|
|
:raises errors.MisconfigurationError: If no parsing hook passes, and we can't
|
|
|
|
|
determine which type to parse the raw lists into.
|
|
|
|
|
"""
|
|
|
|
|
parser = _choose_parser(parent, lists_)
|
|
|
|
|
parser.parse(lists_, add_spaces)
|
|
|
|
|
return parser
|