1 #!/usr/bin/env python 2 3 """ 4 Filesystem utilities. 5 6 Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from imiptools.config import DEFAULT_PERMISSIONS 23 from os.path import abspath, commonprefix, exists, join 24 from os import chmod, makedirs 25 26 def check_dir(base, dir): 27 return commonprefix([base, abspath(dir)]) == base 28 29 def fix_permissions(filename): 30 try: 31 chmod(filename, DEFAULT_PERMISSIONS) 32 except OSError: 33 pass 34 35 class FileBase: 36 37 "Basic filesystem operations." 38 39 def __init__(self, store_dir): 40 self.store_dir = store_dir 41 if not exists(self.store_dir): 42 makedirs(self.store_dir) 43 44 def get_file_object(self, base, *parts): 45 pathname = join(base, *parts) 46 return check_dir(base, pathname) and pathname or None 47 48 def get_object_in_store(self, *parts): 49 50 """ 51 Return the name of any valid object stored within a hierarchy specified 52 by the given 'parts'. 53 """ 54 55 parent = expected = self.store_dir 56 57 for part in parts: 58 filename = self.get_file_object(expected, part) 59 if not filename: 60 return False 61 parent = expected 62 expected = filename 63 64 if not exists(parent): 65 makedirs(parent) 66 67 return filename 68 69 # vim: tabstop=4 expandtab shiftwidth=4