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