2
# -*- coding: utf-8 -*-
4
# Copyright 2014-2015 Canonical Limited.
6
# This file is part of charm-helpers.
8
# charm-helpers is free software: you can redistribute it and/or modify
9
# it under the terms of the GNU Lesser General Public License version 3 as
10
# published by the Free Software Foundation.
12
# charm-helpers is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
23
__author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>'
26
class Fstab(io.FileIO):
27
"""This class extends file in order to implement a file reader/writer
32
"""Entry class represents a non-comment line on the `/etc/fstab` file
34
def __init__(self, device, mountpoint, filesystem,
37
self.mountpoint = mountpoint
38
self.filesystem = filesystem
43
self.options = options
48
return str(self) == str(o)
51
return "{} {} {} {} {} {}".format(self.device,
58
DEFAULT_PATH = os.path.join(os.path.sep, 'etc', 'fstab')
60
def __init__(self, path=None):
64
self._path = self.DEFAULT_PATH
65
super(Fstab, self).__init__(self._path, 'rb+')
67
def _hydrate_entry(self, line):
68
# NOTE: use split with no arguments to split on any
69
# whitespace including tabs
70
return Fstab.Entry(*filter(
71
lambda x: x not in ('', None),
72
line.strip("\n").split()))
77
for line in self.readlines():
78
line = line.decode('us-ascii')
80
if line.strip() and not line.strip().startswith("#"):
81
yield self._hydrate_entry(line)
85
def get_entry_by_attr(self, attr, value):
86
for entry in self.entries:
87
e_attr = getattr(entry, attr)
92
def add_entry(self, entry):
93
if self.get_entry_by_attr('device', entry.device):
96
self.write((str(entry) + '\n').encode('us-ascii'))
100
def remove_entry(self, entry):
103
lines = [l.decode('us-ascii') for l in self.readlines()]
106
for index, line in enumerate(lines):
107
if line.strip() and not line.strip().startswith("#"):
108
if self._hydrate_entry(line) == entry:
118
self.write(''.join(lines).encode('us-ascii'))
123
def remove_by_mountpoint(cls, mountpoint, path=None):
124
fstab = cls(path=path)
125
entry = fstab.get_entry_by_attr('mountpoint', mountpoint)
127
return fstab.remove_entry(entry)
131
def add(cls, device, mountpoint, filesystem, options=None, path=None):
132
return cls(path=path).add_entry(Fstab.Entry(device,
133
mountpoint, filesystem,