1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/imiptools/filesys.py Mon Jan 12 23:07:33 2015 +0100
1.3 @@ -0,0 +1,69 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Filesystem utilities.
1.8 +
1.9 +Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This program is free software; you can redistribute it and/or modify it under
1.12 +the terms of the GNU General Public License as published by the Free Software
1.13 +Foundation; either version 3 of the License, or (at your option) any later
1.14 +version.
1.15 +
1.16 +This program is distributed in the hope that it will be useful, but WITHOUT
1.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
1.19 +details.
1.20 +
1.21 +You should have received a copy of the GNU General Public License along with
1.22 +this program. If not, see <http://www.gnu.org/licenses/>.
1.23 +"""
1.24 +
1.25 +from imiptools.config import DEFAULT_PERMISSIONS
1.26 +from os.path import abspath, commonprefix, exists, join
1.27 +from os import chmod, makedirs
1.28 +
1.29 +def check_dir(base, dir):
1.30 + return commonprefix([base, abspath(dir)]) == base
1.31 +
1.32 +def fix_permissions(filename):
1.33 + try:
1.34 + chmod(filename, DEFAULT_PERMISSIONS)
1.35 + except OSError:
1.36 + pass
1.37 +
1.38 +class FileBase:
1.39 +
1.40 + "Basic filesystem operations."
1.41 +
1.42 + def __init__(self, store_dir):
1.43 + self.store_dir = store_dir
1.44 + if not exists(self.store_dir):
1.45 + makedirs(self.store_dir)
1.46 +
1.47 + def get_file_object(self, base, *parts):
1.48 + pathname = join(base, *parts)
1.49 + return check_dir(base, pathname) and pathname or None
1.50 +
1.51 + def get_object_in_store(self, *parts):
1.52 +
1.53 + """
1.54 + Return the name of any valid object stored within a hierarchy specified
1.55 + by the given 'parts'.
1.56 + """
1.57 +
1.58 + parent = expected = self.store_dir
1.59 +
1.60 + for part in parts:
1.61 + filename = self.get_file_object(expected, part)
1.62 + if not filename:
1.63 + return False
1.64 + parent = expected
1.65 + expected = filename
1.66 +
1.67 + if not exists(parent):
1.68 + makedirs(parent)
1.69 +
1.70 + return filename
1.71 +
1.72 +# vim: tabstop=4 expandtab shiftwidth=4