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