1 #!/usr/bin/env python 2 3 """ 4 AttachList macro for Moin compatibility. 5 6 Copyright (C) 2019, 2022 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 mimetypes import guess_type 23 from moinformat.macros.common import Macro 24 from moinformat.tree.moin import Link, LinkLabel, List, ListItem, Text 25 from moinformat.utils.links import LinkTarget 26 27 class AttachListMacro(Macro): 28 29 "An attachment list macro." 30 31 name = "AttachList" 32 33 def evaluate(self): 34 35 "Evaluate the macro, producing a list of attachments." 36 37 # Obtain the parameters. 38 39 args = self.node.args 40 41 pagename = args and args[0] or self.metadata.get("pagename") 42 mimetype = len(args) > 1 and args[1] or None 43 44 # Access the input context to get the attachment details. 45 46 input = self.metadata.get_input() 47 48 # Select attachments by type. 49 50 all_filenames = pagename and input.get_attachments(pagename) or [] 51 52 if mimetype: 53 filenames = [] 54 55 for filename in all_filenames: 56 type, encoding = guess_type(filename) 57 58 if type == mimetype: 59 filenames.append(filename) 60 else: 61 filenames = all_filenames 62 63 # Sort the filenames. 64 # NOTE: The actual sort order should be controlled. 65 66 filenames.sort() 67 68 # Prepare a list of links. 69 70 items = [] 71 indent = 0 72 marker = "*" 73 space = " " 74 num = None 75 76 for filename in filenames: 77 text = [Text(filename)] 78 nodes = [Link([LinkLabel(text)], LinkTarget("attachment", filename, 79 pagename=pagename))] 80 items.append(ListItem(nodes, indent, marker, space, num)) 81 82 # Replace the macro node with the list. 83 84 macro = self.node 85 macro.parent.replace(macro, List(items)) 86 87 macro = AttachListMacro 88 89 # vim: tabstop=4 expandtab shiftwidth=4