paul@100 | 1 | #!/usr/bin/env python |
paul@100 | 2 | |
paul@100 | 3 | """ |
paul@100 | 4 | Directory output context. |
paul@100 | 5 | |
paul@100 | 6 | Copyright (C) 2018 Paul Boddie <paul@boddie.org.uk> |
paul@100 | 7 | |
paul@100 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@100 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@100 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@100 | 11 | version. |
paul@100 | 12 | |
paul@100 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT |
paul@100 | 14 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paul@100 | 15 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
paul@100 | 16 | details. |
paul@100 | 17 | |
paul@100 | 18 | You should have received a copy of the GNU General Public License along with |
paul@100 | 19 | this program. If not, see <http://www.gnu.org/licenses/>. |
paul@100 | 20 | """ |
paul@100 | 21 | |
paul@100 | 22 | from moinformat.output.common import Output |
paul@100 | 23 | from os.path import abspath, commonprefix, join |
paul@100 | 24 | |
paul@100 | 25 | def inside(filename, dirname): |
paul@100 | 26 | |
paul@100 | 27 | "Return whether 'filename' is inside 'dirname'." |
paul@100 | 28 | |
paul@100 | 29 | # Get the directory with trailing path separator. |
paul@100 | 30 | |
paul@100 | 31 | dirname = join(dirname, "") |
paul@100 | 32 | return commonprefix((filename, dirname)) == dirname |
paul@100 | 33 | |
paul@100 | 34 | |
paul@100 | 35 | |
paul@100 | 36 | class DirectoryOutput(Output): |
paul@100 | 37 | |
paul@100 | 38 | "A directory output context." |
paul@100 | 39 | |
paul@100 | 40 | def __init__(self, filename): |
paul@100 | 41 | |
paul@100 | 42 | "Initialise the context with the given 'filename'." |
paul@100 | 43 | |
paul@100 | 44 | Output.__init__(self) |
paul@100 | 45 | self.filename = abspath(filename) |
paul@100 | 46 | |
paul@100 | 47 | def get_filename(self, filename): |
paul@100 | 48 | |
paul@100 | 49 | "Return a file with the given 'filename' within the directory." |
paul@100 | 50 | |
paul@100 | 51 | # Get the absolute path for the combination of directory and filename. |
paul@100 | 52 | |
paul@100 | 53 | pathname = abspath(join(self.filename, filename)) |
paul@100 | 54 | |
paul@100 | 55 | if inside(pathname, self.filename): |
paul@100 | 56 | return pathname |
paul@100 | 57 | else: |
paul@100 | 58 | raise ValueError, filename |
paul@100 | 59 | |
paul@100 | 60 | # vim: tabstop=4 expandtab shiftwidth=4 |