More Python 3 fixes, mostly about string/byte/unicode handling.
[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 import sys as _sys
21 import types as _types
22
23
24 class Storage (object):
25     "A storage bakend for loading and saving `Config` instances"
26     def load(self, config, merge=False, **kwargs):
27         if merge:
28             self.clear()
29         self._load(config=config, **kwargs)
30         config.set_storage(storage=self)
31
32     def _load(self, config, **kwargs):
33         raise NotImplementedError()
34
35     def save(self, config, merge=False, **kwargs):
36         if merge:
37             self.clear()
38         self._save(config=config, **kwargs)
39         config._storage = self
40
41     def _save(self, config, **kwargs):
42         raise NotImplementedError()
43
44     def clear(self):
45         raise NotImplementedError()
46
47
48 class FileStorage (Storage):
49     "`Config` storage backend by a single file"
50     extension = None
51
52     def __init__(self, filename=None):
53         self._filename = filename
54
55     def _create_basedir(self, filename):
56         dirname = _os_path.dirname(filename)
57         if dirname and not _os_path.isdir(dirname):
58             _os.makedirs(dirname)
59
60
61 def is_string(x):
62     if _sys.version_info >= (3,):
63         return isinstance(x, (bytes, str))
64     else:  # Python 2 compatibility
65         return isinstance(x, _types.StringTypes)