bzlink.py (2195B)
1 # This Source Code Form is subject to the terms of the Mozilla Public 2 # License, v. 2.0. If a copy of the MPL was not distributed with this 3 # file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 5 import re 6 7 from docutils.nodes import Text, paragraph, reference 8 from sphinx.transforms import SphinxTransform 9 10 11 class ConvertBugsToLinks(SphinxTransform): 12 # Convert text entries in paragraphs that are in the style of "bug xxxxx" 13 # to a hyperlink that leads to the appropriate bugzilla bug link. 14 15 default_priority = 400 16 bz_url = "https://bugzilla.mozilla.org/show_bug.cgi?id={0}" 17 bz_reg = r"bug[' '][0-9]\d*" 18 19 def apply(self): 20 def check_if_paragraph(o): 21 return isinstance(o, paragraph) 22 23 def check_if_text(o): 24 return ( 25 not isinstance(o.parent, reference) 26 and isinstance(o, Text) 27 and re.search(self.bz_reg, o, re.IGNORECASE) 28 ) 29 30 changed = True 31 while changed: 32 changed = self.textToReferences(check_if_paragraph, check_if_text) 33 34 def textToReferences(self, check_if_paragraph, check_if_text): 35 # Analyses the document and replaces from the paragraph nodes 36 # the Text element(s) that contain bz_reg matching strings. 37 # Whevever the matching strings are more than one and 38 # a correction is made, the function returns True. 39 40 for node in self.document.traverse(check_if_paragraph): 41 for text in node.traverse(check_if_text): 42 bugs = re.findall(self.bz_reg, text, re.IGNORECASE) 43 if len(bugs) == 0: 44 continue 45 bug = bugs[0] 46 txtparts = text.split(bug, 1) 47 new_ref = reference( 48 bug, 49 bug, 50 refuri=self.bz_url.format(bug.split()[1]), 51 ) 52 txt_0 = Text(txtparts[0]) 53 txt_1 = Text(txtparts[1]) 54 text.parent.replace(text, [txt_0, new_ref, txt_1]) 55 if len(bugs) > 1: 56 return True 57 return False 58 59 60 def setup(app): 61 app.add_transform(ConvertBugsToLinks)