3
# Copyright (C) 2012 Yahoo! Inc.
5
# Author: Joshua Harlow <harlowja@yahoo-inc.com>
7
# This program is free software: you can redistribute it and/or modify
8
# it under the terms of the GNU General Public License version 3, as
9
# published by the Free Software Foundation.
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
# GNU General Public License for more details.
16
# You should have received a copy of the GNU General Public License
17
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
from six import StringIO
21
from cloudinit.distros.parsers import chop_comment
25
# or http://unixhelp.ed.ac.uk/CGI/man-cgi?hosts
26
# or http://tinyurl.com/6lmox3
27
class HostsConf(object):
28
def __init__(self, text):
33
if self._contents is None:
34
self._contents = self._parse(self._text)
36
def get_entry(self, ip):
39
for (line_type, components) in self._contents:
40
if line_type == 'option':
41
(pieces, _tail) = components
42
if len(pieces) and pieces[0] == ip:
43
options.append(pieces[1:])
46
def del_entries(self, ip):
49
for (line_type, components) in self._contents:
50
if line_type != 'option':
51
n_entries.append((line_type, components))
54
(pieces, _tail) = components
55
if len(pieces) and pieces[0] == ip:
58
n_entries.append((line_type, list(components)))
59
self._contents = n_entries
61
def add_entry(self, ip, canonical_hostname, *aliases):
63
self._contents.append(('option',
64
([ip, canonical_hostname] + list(aliases), '')))
66
def _parse(self, contents):
68
for line in contents.splitlines():
69
if not len(line.strip()):
70
entries.append(('blank', [line]))
72
(head, tail) = chop_comment(line.strip(), '#')
74
entries.append(('all_comment', [line]))
76
entries.append(('option', [head.split(None), tail]))
82
for (line_type, components) in self._contents:
83
if line_type == 'blank':
84
contents.write("%s\n" % (components[0]))
85
elif line_type == 'all_comment':
86
contents.write("%s\n" % (components[0]))
87
elif line_type == 'option':
88
(pieces, tail) = components
89
pieces = [str(p) for p in pieces]
90
pieces = "\t".join(pieces)
91
contents.write("%s%s\n" % (pieces, tail))
92
return contents.getvalue()