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
24
# Parser that knows how to work with /etc/hostname format
25
class HostnameConf(object):
26
def __init__(self, text):
31
if self._contents is None:
32
self._contents = self._parse(self._text)
37
for (line_type, components) in self._contents:
38
if line_type == 'blank':
39
contents.write("%s\n" % (components[0]))
40
elif line_type == 'all_comment':
41
contents.write("%s\n" % (components[0]))
42
elif line_type == 'hostname':
43
(hostname, tail) = components
44
contents.write("%s%s\n" % (hostname, tail))
45
# Ensure trailing newline
46
contents = contents.getvalue()
47
if not contents.endswith("\n"):
54
for (line_type, components) in self._contents:
55
if line_type == 'hostname':
59
def set_hostname(self, your_hostname):
60
your_hostname = your_hostname.strip()
65
for (line_type, components) in self._contents:
66
if line_type == 'hostname':
67
components[0] = str(your_hostname)
70
self._contents.append(('hostname', [str(your_hostname), '']))
72
def _parse(self, contents):
74
hostnames_found = set()
75
for line in contents.splitlines():
76
if not len(line.strip()):
77
entries.append(('blank', [line]))
79
(head, tail) = chop_comment(line.strip(), '#')
81
entries.append(('all_comment', [line]))
83
entries.append(('hostname', [head, tail]))
84
hostnames_found.add(head)
85
if len(hostnames_found) > 1:
86
raise IOError("Multiple hostnames (%s) found!"