certbot/certbot-nginx/certbot_nginx/_internal/nginxparser.py

314 lines
11 KiB
Python
Raw Normal View History

"""Very low-level nginx config parser based on pyparsing."""
2016-06-27 15:44:53 -04:00
# Forked from https://github.com/fatiherikli/nginxparser (MIT Licensed)
import copy
2016-06-16 21:18:33 -04:00
import logging
import operator
import typing
from typing import Any
from typing import IO
from typing import Iterable
from typing import Iterator
from typing import List
from typing import overload
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Union
2015-03-23 13:53:44 -04:00
from pyparsing import Combine
from pyparsing import Forward
from pyparsing import Group
from pyparsing import Literal
from pyparsing import Optional
from pyparsing import ParseResults
from pyparsing import QuotedString
from pyparsing import Regex
2015-07-11 03:15:59 -04:00
from pyparsing import restOfLine
from pyparsing import stringEnd
from pyparsing import White
from pyparsing import ZeroOrMore
2015-03-23 13:53:44 -04:00
if TYPE_CHECKING:
from typing_extensions import SupportsIndex # typing.SupportsIndex not supported on Python 3.6
2016-06-16 21:18:33 -04:00
logger = logging.getLogger(__name__)
2015-09-06 05:21:03 -04:00
class RawNginxParser:
# pylint: disable=pointless-statement
2015-04-18 13:20:19 -04:00
"""A class that parses nginx configuration with pyparsing."""
2015-03-23 13:53:44 -04:00
# constants
space = Optional(White()).leaveWhitespace()
required_space = White().leaveWhitespace()
2015-03-23 13:53:44 -04:00
left_bracket = Literal("{").suppress()
right_bracket = space + Literal("}").suppress()
2015-03-23 13:53:44 -04:00
semicolon = Literal(";").suppress()
dquoted = QuotedString('"', multiline=True, unquoteResults=False, escChar='\\')
squoted = QuotedString("'", multiline=True, unquoteResults=False, escChar='\\')
quoted = dquoted | squoted
head_tokenchars = Regex(r"(\$\{)|[^{};\s'\"]") # if (last_space)
tail_tokenchars = Regex(r"(\$\{)|[^{;\s]") # else
tokenchars = Combine(head_tokenchars + ZeroOrMore(tail_tokenchars))
paren_quote_extend = Combine(quoted + Literal(')') + ZeroOrMore(tail_tokenchars))
# note: ')' allows extension, but then we fall into else, not last_space.
2016-06-07 20:17:17 -04:00
token = paren_quote_extend | tokenchars | quoted
2016-06-30 18:07:28 -04:00
whitespace_token_group = space + token + ZeroOrMore(required_space + token) + space
assignment = whitespace_token_group + semicolon
comment = space + Literal('#') + restOfLine
block = Forward()
# order matters! see issue 518, and also http { # server { \n}
contents = Group(comment) | Group(block) | Group(assignment)
block_begin = Group(whitespace_token_group)
block_innards = Group(ZeroOrMore(contents) + space).leaveWhitespace()
block << block_begin + left_bracket + block_innards + right_bracket
2016-06-30 18:07:28 -04:00
script = ZeroOrMore(contents) + space + stringEnd
script.parseWithTabs().leaveWhitespace()
2015-03-23 13:53:44 -04:00
def __init__(self, source: str) -> None:
2016-06-15 20:26:38 -04:00
self.source = source
2015-03-23 13:53:44 -04:00
def parse(self) -> ParseResults:
2015-04-18 13:20:19 -04:00
"""Returns the parsed tree."""
2015-03-23 13:53:44 -04:00
return self.script.parseString(self.source)
def as_list(self) -> List[Any]:
2015-04-18 13:20:19 -04:00
"""Returns the parsed tree as a list."""
2015-03-23 13:53:44 -04:00
return self.parse().asList()
class RawNginxDumper:
2016-06-07 17:46:49 -04:00
"""A class that dumps nginx configuration from the provided tree."""
def __init__(self, blocks: List[Any]) -> None:
2016-06-07 17:46:49 -04:00
self.blocks = blocks
def __iter__(self, blocks: typing.Optional[List[Any]] = None) -> Iterator[str]:
2016-06-07 17:46:49 -04:00
"""Iterates the dumped nginx content."""
blocks = blocks or self.blocks
for b0 in blocks:
if isinstance(b0, str):
yield b0
2016-06-15 19:42:47 -04:00
continue
item = copy.deepcopy(b0)
if spacey(item[0]):
yield item.pop(0) # indentation
if not item:
continue
2016-06-07 21:19:58 -04:00
if isinstance(item[0], list): # block
yield "".join(item.pop(0)) + '{'
for parameter in item.pop(0):
2016-06-24 19:13:12 -04:00
for line in self.__iter__([parameter]): # negate "for b0 in blocks"
2016-06-07 17:46:49 -04:00
yield line
yield '}'
else: # not a block - list of strings
semicolon = ";"
if isinstance(item[0], str) and item[0].strip() == '#': # comment
semicolon = ""
yield "".join(item) + semicolon
2016-06-07 17:46:49 -04:00
def __str__(self) -> str:
2016-06-07 17:46:49 -04:00
"""Return the parsed block as a string."""
return ''.join(self)
2016-06-07 17:46:49 -04:00
spacey = lambda x: (isinstance(x, str) and x.isspace()) or x == ''
class UnspacedList(List[Any]):
"""Wrap a list [of lists], making any whitespace entries magically invisible"""
def __init__(self, list_source: Iterable[Any]) -> None:
2016-06-18 17:52:07 -04:00
# ensure our argument is not a generator, and duplicate any sublists
self.spaced = copy.deepcopy(list(list_source))
self.dirty = False
# Turn self into a version of the source list that has spaces removed
2016-06-07 17:46:49 -04:00
# and all sub-lists also UnspacedList()ed
super().__init__(list_source)
for i, entry in reversed(list(enumerate(self))):
if isinstance(entry, list):
2016-06-17 17:32:24 -04:00
sublist = UnspacedList(entry)
super().__setitem__(i, sublist)
self.spaced[i] = sublist.spaced
elif spacey(entry):
2016-06-18 17:52:07 -04:00
# don't delete comments
if "#" not in self[:i]:
super().__delitem__(i)
@overload
def _coerce(self, inbound: None) -> Tuple[None, None]: ...
2016-06-07 17:46:49 -04:00
@overload
def _coerce(self, inbound: str) -> Tuple[str, str]: ...
@overload
def _coerce(self, inbound: List[Any]) -> Tuple["UnspacedList", List[Any]]: ...
def _coerce(self, inbound: Any) -> Tuple[Any, Any]:
"""
Coerce some inbound object to be appropriately usable in this object
:param inbound: string or None or list or UnspacedList
:returns: (coerced UnspacedList or string or None, spaced equivalent)
:rtype: tuple
"""
if not isinstance(inbound, list): # str or None
Lint certbot code on Python 3, and update Pylint to the latest version (#7551) Part of #7550 This PR makes appropriate corrections to run pylint on Python 3. Why not keeping the dependencies unchanged and just run pylint on Python 3? Because the old version of pylint breaks horribly on Python 3 because of unsupported version of astroid. Why updating pylint + astroid to the latest version ? Because this version only fixes some internal errors occuring during the lint of Certbot code, and is also ready to run gracefully on Python 3.8. Why upgrading mypy ? Because the old version does not support the new version of astroid required to run pylint correctly. Why not upgrading mypy to its latest version ? Because this latest version includes a new typshed version, that adds a lot of new type definitions, and brings dozens of new errors on the Certbot codebase. I would like to fix that in a future PR. That said so, the work has been to find the correct set of new dependency versions, then configure pylint for sane configuration errors in our situation, disable irrelevant lintings errors, then fixing (or ignoring for good reason) the remaining mypy errors. I also made PyLint and MyPy checks run correctly on Windows. * Start configuration * Reconfigure travis * Suspend a check specific to python 3. Start fixing code. * Repair call_args * Fix return + elif lints * Reconfigure development to run mainly on python3 * Remove incompatible Python 3.4 jobs * Suspend pylint in some assertions * Remove pylint in dev * Take first mypy that supports typed-ast>=1.4.0 to limit the migration path * Various return + else lint errors * Find a set of deps that is working with current mypy version * Update local oldest requirements * Remove all current pylint errors * Rebuild letsencrypt-auto * Update mypy to fix pylint with new astroid version, and fix mypy issues * Explain type: ignore * Reconfigure tox, fix none path * Simplify pinning * Remove useless directive * Remove debugging code * Remove continue * Update requirements * Disable unsubscriptable-object check * Disable one check, enabling two more * Plug certbot dev version for oldest requirements * Remove useless disable directives * Remove useless no-member disable * Remove no-else-* checks. Use elif in symetric branches. * Add back assertion * Add new line * Remove unused pylint disable * Remove other pylint disable
2019-12-10 17:12:50 -05:00
return inbound, inbound
2016-06-18 17:52:07 -04:00
else:
2016-06-20 18:56:19 -04:00
if not hasattr(inbound, "spaced"):
inbound = UnspacedList(inbound)
Lint certbot code on Python 3, and update Pylint to the latest version (#7551) Part of #7550 This PR makes appropriate corrections to run pylint on Python 3. Why not keeping the dependencies unchanged and just run pylint on Python 3? Because the old version of pylint breaks horribly on Python 3 because of unsupported version of astroid. Why updating pylint + astroid to the latest version ? Because this version only fixes some internal errors occuring during the lint of Certbot code, and is also ready to run gracefully on Python 3.8. Why upgrading mypy ? Because the old version does not support the new version of astroid required to run pylint correctly. Why not upgrading mypy to its latest version ? Because this latest version includes a new typshed version, that adds a lot of new type definitions, and brings dozens of new errors on the Certbot codebase. I would like to fix that in a future PR. That said so, the work has been to find the correct set of new dependency versions, then configure pylint for sane configuration errors in our situation, disable irrelevant lintings errors, then fixing (or ignoring for good reason) the remaining mypy errors. I also made PyLint and MyPy checks run correctly on Windows. * Start configuration * Reconfigure travis * Suspend a check specific to python 3. Start fixing code. * Repair call_args * Fix return + elif lints * Reconfigure development to run mainly on python3 * Remove incompatible Python 3.4 jobs * Suspend pylint in some assertions * Remove pylint in dev * Take first mypy that supports typed-ast>=1.4.0 to limit the migration path * Various return + else lint errors * Find a set of deps that is working with current mypy version * Update local oldest requirements * Remove all current pylint errors * Rebuild letsencrypt-auto * Update mypy to fix pylint with new astroid version, and fix mypy issues * Explain type: ignore * Reconfigure tox, fix none path * Simplify pinning * Remove useless directive * Remove debugging code * Remove continue * Update requirements * Disable unsubscriptable-object check * Disable one check, enabling two more * Plug certbot dev version for oldest requirements * Remove useless disable directives * Remove useless no-member disable * Remove no-else-* checks. Use elif in symetric branches. * Add back assertion * Add new line * Remove unused pylint disable * Remove other pylint disable
2019-12-10 17:12:50 -05:00
return inbound, inbound.spaced
def insert(self, i: "SupportsIndex", x: Any) -> None:
"""Insert object before index."""
idx = operator.index(i)
item, spaced_item = self._coerce(x)
slicepos = self._spaced_position(idx) if idx < len(self) else len(self.spaced)
self.spaced.insert(slicepos, spaced_item)
if not spacey(item):
super().insert(idx, item)
self.dirty = True
def append(self, x: Any) -> None:
"""Append object to the end of the list."""
item, spaced_item = self._coerce(x)
self.spaced.append(spaced_item)
if not spacey(item):
super().append(item)
self.dirty = True
def extend(self, x: Any) -> None:
"""Extend list by appending elements from the iterable."""
item, spaced_item = self._coerce(x)
self.spaced.extend(spaced_item)
super().extend(item)
self.dirty = True
def __add__(self, other: List[Any]) -> "UnspacedList":
new_list = copy.deepcopy(self)
new_list.extend(other)
new_list.dirty = True
return new_list
2016-06-07 17:46:49 -04:00
def pop(self, *args: Any, **kwargs: Any) -> None:
"""Function pop() is not implemented for UnspacedList"""
raise NotImplementedError("UnspacedList.pop() not yet implemented")
def remove(self, *args: Any, **kwargs: Any) -> None:
"""Function remove() is not implemented for UnspacedList"""
raise NotImplementedError("UnspacedList.remove() not yet implemented")
def reverse(self) -> None:
"""Function reverse() is not implemented for UnspacedList"""
raise NotImplementedError("UnspacedList.reverse() not yet implemented")
def sort(self, *_args: Any, **_kwargs: Any) -> None:
"""Function sort() is not implemented for UnspacedList"""
raise NotImplementedError("UnspacedList.sort() not yet implemented")
def __setslice__(self, *args: Any, **kwargs: Any) -> None:
raise NotImplementedError("Slice operations on UnspacedLists not yet implemented")
def __setitem__(self, i: Union["SupportsIndex", slice], value: Any) -> None:
if isinstance(i, slice):
raise NotImplementedError("Slice operations on UnspacedLists not yet implemented")
2016-06-20 18:56:19 -04:00
item, spaced_item = self._coerce(value)
self.spaced.__setitem__(self._spaced_position(i), spaced_item)
if not spacey(item):
super().__setitem__(i, item)
self.dirty = True
def __delitem__(self, i: Union["SupportsIndex", slice]) -> None:
if isinstance(i, slice):
raise NotImplementedError("Slice operations on UnspacedLists not yet implemented")
self.spaced.__delitem__(self._spaced_position(i))
super().__delitem__(i)
self.dirty = True
def __deepcopy__(self, memo: Any) -> "UnspacedList":
new_spaced = copy.deepcopy(self.spaced, memo=memo)
new_list = UnspacedList(new_spaced)
new_list.dirty = self.dirty
return new_list
2016-06-17 17:32:24 -04:00
def is_dirty(self) -> bool:
"""Recurse through the parse tree to figure out if any sublists are dirty"""
if self.dirty:
return True
return any((isinstance(x, UnspacedList) and x.is_dirty() for x in self))
2016-06-17 17:32:24 -04:00
def _spaced_position(self, idx: "SupportsIndex") -> int:
"""Convert from indexes in the unspaced list to positions in the spaced one"""
int_idx = operator.index(idx)
pos = spaces = 0
# Normalize indexes like list[-1] etc, and save the result
if int_idx < 0:
int_idx = len(self) + int_idx
if not 0 <= int_idx < len(self):
raise IndexError("list index out of range")
int_idx0 = int_idx
# Count the number of spaces in the spaced list before int_idx in the unspaced one
while int_idx != -1:
if spacey(self.spaced[pos]):
spaces += 1
else:
int_idx -= 1
pos += 1
return int_idx0 + spaces
# Shortcut functions to respect Python's serialization interface
# (like pyyaml, picker or json)
def loads(source: str) -> UnspacedList:
"""Parses from a string.
:param str source: The string to parse
:returns: The parsed tree
:rtype: list
"""
return UnspacedList(RawNginxParser(source).as_list())
def load(file_: IO[Any]) -> UnspacedList:
"""Parses from a file.
:param file file_: The file to parse
:returns: The parsed tree
:rtype: list
"""
return loads(file_.read())
def dumps(blocks: UnspacedList) -> str:
"""Dump to a Unicode string.
:param UnspacedList blocks: The parsed tree
:rtype: six.text_type
"""
return str(RawNginxDumper(blocks.spaced))
def dump(blocks: UnspacedList, file_: IO[Any]) -> None:
"""Dump to a file.
:param UnspacedList blocks: The parsed tree
:param IO[Any] file_: The file stream to dump to. It must be opened with
Unicode encoding.
:rtype: None
"""
file_.write(dumps(blocks))