1 #!/usr/bin/env python 2 3 """ 4 Common linking scheme functionality. 5 6 Copyright (C) 2018, 2019 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 class Linker: 23 24 "Translate Moin links into other forms." 25 26 # Pagename whitespace conversion, configured using the "whitespace" metadata 27 # setting. 28 29 default_whitespace_map = [ 30 (" ", "_"), 31 ("\n", "_"), 32 ] 33 34 def __init__(self, metadata): 35 36 "Initialise the linker with the 'metadata'." 37 38 self.metadata = metadata 39 40 # Obtain essential metadata. 41 42 self.mapping = metadata.get("mapping", {}) 43 self.root_pagename = metadata.get("root_pagename", "FrontPage") 44 45 def resolve(path, pagename, root_pagename): 46 47 "Resolve 'path' relative to 'pagename'." 48 49 # Omit the root pagename from the resolved path components. 50 51 if pagename == root_pagename: 52 parts = [] 53 else: 54 parts = pagename.rstrip("/").split("/") 55 56 t = path.split("/") 57 58 first = True 59 60 for p in t: 61 62 # Handle replacement of the page with another. 63 64 if p == ".": 65 parts = [] 66 67 # Handle ascent in the page hierarchy. 68 69 elif p == "..": 70 if parts: 71 parts.pop() 72 73 # Any non-navigation element replaces the path at the start. 74 # Otherwise, the path is extended. 75 # Omit the root pagename from the resolved path components if it would 76 # appear at the start. 77 78 elif p: 79 if first: 80 if p == root_pagename: 81 parts = [] 82 else: 83 parts = [p] 84 else: 85 if parts or p != root_pagename: 86 parts.append(p) 87 88 first = False 89 90 return "/".join(parts) 91 92 # vim: tabstop=4 expandtab shiftwidth=4