00d6ccade0817ea7a7e0a9069a05b860d6898bd6
[h5config.git] / h5config / storage / __init__.py
1 # Copyright (C) 2011 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of h5config.
4 #
5 # h5config is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation, either version 3 of the License, or (at your
8 # option) any later version.
9 #
10 # h5config is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with h5config.  If not, see <http://www.gnu.org/licenses/>.
17
18 import os as _os
19 import os.path as _os_path
20
21
22 class Storage (object):
23     "A storage bakend for loading and saving `Config` instances"
24     def load(self, config, merge=False, **kwargs):
25         if merge:
26             self.clear()
27         self._load(config=config, **kwargs)
28         config.set_storage(storage=self)
29
30     def _load(self, config, **kwargs):
31         raise NotImplementedError()
32
33     def save(self, config, merge=False, **kwargs):
34         if merge:
35             self.clear()
36         self._save(config=config, **kwargs)
37         config._storage = self
38
39     def _save(self, config, **kwargs):
40         raise NotImplementedError()
41
42     def clear(self):
43         raise NotImplementedError()
44
45
46 class FileStorage (Storage):
47     "`Config` storage backend by a single file"
48     extension = None
49
50     def __init__(self, filename=None):
51         self._filename = filename
52
53     def _create_basedir(self, filename):
54         dirname = _os_path.dirname(filename)
55         if dirname and not _os_path.isdir(dirname):
56             _os.makedirs(dirname)