1 #!/usr/bin/env python 2 3 """ 4 Theming common functionality. 5 6 Copyright (C) 2018 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 os import listdir, makedirs 23 from os.path import exists, isfile, join, split 24 from shutil import copy 25 26 class Theme: 27 28 "A common theme abstraction." 29 30 def __init__(self, output, linker, pagename): 31 32 """ 33 Initialise the theme with the given 'output' context, 'linker' and 34 'pagename'. 35 """ 36 37 self.output = output 38 self.linker = linker 39 self.pagename = pagename 40 41 def apply(self, text): 42 43 "Apply this theme to the given 'text', returning a themed version." 44 45 return text 46 47 def get_resource_base(self): 48 49 "Return the filesystem base of resources for instances of this class." 50 51 return split(self.__class__.origin)[0] 52 53 def get_resource(self, filename): 54 55 "Return the complete path for the resource with the given 'filename'." 56 57 base = self.get_resource_base() 58 return join(base, filename) 59 60 def install_resource(self, filename, target=None): 61 62 """ 63 Install the resource with the given 'filename' into a location having 64 the given 'target' name (or 'filename' if 'target' is omitted). 65 """ 66 67 pathname = self.get_resource(filename) 68 outpath = self.output.get_filename(target or filename) 69 70 self.copy(pathname, outpath) 71 72 def copy(self, pathname, outpath): 73 74 "Copy 'pathname' to 'outpath'." 75 76 if isfile(pathname): 77 outdir = split(outpath)[0] 78 if outdir and not exists(outdir): 79 makedirs(outdir) 80 copy(pathname, outpath) 81 else: 82 if not exists(outpath): 83 makedirs(outpath) 84 for filename in listdir(pathname): 85 self.copy(join(pathname, filename), join(outpath, filename)) 86 87 def load_resource(self, filename): 88 89 "Return the textual content of the resource with the given 'filename'." 90 91 f = open(self.get_resource(filename)) 92 try: 93 return f.read() 94 finally: 95 f.close() 96 97 # vim: tabstop=4 expandtab shiftwidth=4