Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 25 additions & 22 deletions cloudinit/distros/parsers/hosts.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# This file is part of cloud-init. See LICENSE file for license information.

from io import StringIO
from typing import Any, List, Tuple

from cloudinit.distros.parsers import chop_comment

Expand All @@ -13,69 +14,71 @@
# or https://linux.die.net/man/5/hosts
# or https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/configtuning-configfiles.html # noqa
class HostsConf:
def __init__(self, text):
def __init__(self, text: str) -> None:
self._text = text
self._contents = None
self._contents: List[Tuple[str, List[Any]]] = []

def parse(self):
if self._contents is None:
def parse(self) -> None:
if not self._contents:
self._contents = self._parse(self._text)

def get_entry(self, ip):
def get_entry(self, ip: str) -> List[List[str]]:
self.parse()
options = []
options: List[List[str]] = []
for line_type, components in self._contents:
if line_type == "option":
(pieces, _tail) = components
pieces, _tail = components
if len(pieces) and pieces[0] == ip:
options.append(pieces[1:])
return options

def del_entries(self, ip):
def del_entries(self, ip: str) -> None:
self.parse()
n_entries = []
n_entries: List[Tuple[str, List[Any]]] = []
for line_type, components in self._contents:
if line_type != "option":
n_entries.append((line_type, components))
continue
else:
(pieces, _tail) = components
pieces, _tail = components
if len(pieces) and pieces[0] == ip:
pass
elif len(pieces):
n_entries.append((line_type, list(components)))
self._contents = n_entries

def add_entry(self, ip, canonical_hostname, *aliases):
def add_entry(
self, ip: str, canonical_hostname: str, *aliases: str
) -> None:
self.parse()
self._contents.append(
("option", ([ip, canonical_hostname] + list(aliases), ""))
("option", [[ip, canonical_hostname] + list(aliases), ""])
)

def _parse(self, contents):
entries = []
def _parse(self, contents: str) -> List[Tuple[str, List[Any]]]:
entries: List[Tuple[str, List[Any]]] = []
Comment on lines +58 to +59

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any reason this can't be List[Tuple[str, List[str]]]?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question. The inner list can't be List[str] because option entries store [head.split(None), tail] - that's [list[str], str], so the two elements are different types. Changing it to List[str] would make mypy flag every place we do pieces, _tail = components (it would see a list of strings being unpacked into two str variables, losing the fact that pieces is itself a list). List[Any] is the minimal correct annotation here without introducing a custom TypeAlias or a NamedTuple. Happy to tighten it further if you'd prefer a TypeAlias approach.

for line in contents.splitlines():
if not len(line.strip()):
entries.append(("blank", [line]))
continue
(head, tail) = chop_comment(line.strip(), "#")
head, tail = chop_comment(line.strip(), "#")
if not len(head):
entries.append(("all_comment", [line]))
continue
entries.append(("option", [head.split(None), tail]))
return entries

def __str__(self):
def __str__(self) -> str:
self.parse()
contents = StringIO()
for line_type, components in self._contents:
if line_type == "blank":
contents.write("%s\n" % (components[0]))
contents.write("%s\n" % components[0])
elif line_type == "all_comment":
contents.write("%s\n" % (components[0]))
contents.write("%s\n" % components[0])
elif line_type == "option":
(pieces, tail) = components
pieces = [str(p) for p in pieces]
pieces = "\t".join(pieces)
contents.write("%s%s\n" % (pieces, tail))
raw_pieces, tail = components
str_pieces = [str(p) for p in raw_pieces]
joined = "\t".join(str_pieces)
contents.write(f"{joined}{tail}\n")
return contents.getvalue()
2 changes: 0 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ module = [
"cloudinit.distros.bsd",
"cloudinit.distros.opensuse",
"cloudinit.distros.parsers.hostname",
"cloudinit.distros.parsers.hosts",
"cloudinit.distros.parsers.resolv_conf",
"cloudinit.distros.ug_util",
"cloudinit.helpers",
Expand Down Expand Up @@ -114,7 +113,6 @@ module = [
"tests.unittests.config.test_cc_zypper_add_repo",
"tests.unittests.config.test_modules",
"tests.unittests.config.test_schema",
"tests.unittests.distros.test_hosts",
"tests.unittests.distros.test_ifconfig",
"tests.unittests.distros.test_netbsd",
"tests.unittests.distros.test_netconfig",
Expand Down
4 changes: 2 additions & 2 deletions tests/unittests/distros/test_hosts.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ def test_parse(self):
["foo.mydomain.org", "foo"],
["bar.mydomain.org", "bar"],
]
eh = str(eh)
assert eh.startswith("# Example")
eh_str = str(eh)
assert eh_str.startswith("# Example")

def test_add(self):
eh = hosts.HostsConf(BASE_ETC)
Expand Down
Loading