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, metadata): 31 32 "Initialise the theme with the given 'metadata'." 33 34 self.metadata = metadata 35 36 # Obtain essential metadata. 37 38 self.linker = metadata.get_linker() 39 self.output = metadata.get_output() 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 if not self.output.can_write(): 68 return 69 70 pathname = self.get_resource(filename) 71 outpath = self.output.get_filename(target or filename) 72 73 self.copy(pathname, outpath) 74 75 def copy(self, pathname, outpath): 76 77 "Copy 'pathname' to 'outpath'." 78 79 if isfile(pathname): 80 outdir = split(outpath)[0] 81 if outdir and not exists(outdir): 82 makedirs(outdir) 83 copy(pathname, outpath) 84 else: 85 if not exists(outpath): 86 makedirs(outpath) 87 for filename in listdir(pathname): 88 self.copy(join(pathname, filename), join(outpath, filename)) 89 90 def load_resource(self, filename): 91 92 "Return the textual content of the resource with the given 'filename'." 93 94 f = open(self.get_resource(filename)) 95 try: 96 return f.read() 97 finally: 98 f.close() 99 100 # vim: tabstop=4 expandtab shiftwidth=4