def createToken(self, info, parent): content = info['block'] if 'block' in info else info['inline'] if self.settings['prefix'] is None: msg = "The 'prefix' option is required." raise exceptions.TokenizeException(msg) # Extract the unordered list self.reader.parse(parent, content, MooseDocs.BLOCK) ul = parent.children[-1] ul.parent = None # Check the list type if not isinstance(ul, tokens.UnorderedList): msg = "The content is required to be an unordered list (i.e., use '-')." raise exceptions.TokenizeException(msg) # Build the matrix prefix = self.settings['prefix'] label = u'{}{:d}'.format(prefix, self.extension.increment(prefix)) matrix = SQARequirementMatrix(parent) heading = self.settings['heading'] if heading is not None: matrix.heading = tokens.Token(None) #pylint: disable=attribute-defined-outside-init self.reader.parse(matrix.heading, heading, MooseDocs.INLINE) for i, item in enumerate(ul.children): matrix_item = SQARequirementMatrixItem(matrix, label=u'{}.{:d}'.format( label, i)) for child in item: child.parent = matrix_item return parent
def sub(match): key = match.group('key') if key not in key_values: msg = "The template argument '{}' was not defined in the !sqa load command." raise exceptions.TokenizeException(msg, key) return key_values[key]
def createToken(self, info, parent): #TODO: make root path a config item in extension location = os.path.join(MooseDocs.ROOT_DIR, 'framework', 'doc', 'templates', 'sqa', self.settings['template']) if not os.path.exists(location): msg = "The template file does not exist: {}." raise exceptions.TokenizeException(msg, location) with codecs.open(location, 'r', encoding='utf-8') as fid: content = fid.read() # Replace key/value arguments template_args = info['inline'] if 'inline' in info else info['block'] _, key_values = common.match_settings(dict(), template_args) def sub(match): key = match.group('key') if key not in key_values: msg = "The template argument '{}' was not defined in the !sqa load command." raise exceptions.TokenizeException(msg, key) return key_values[key] content = re.sub(r'{{(?P<key>.*?)}}', sub, content) # Tokenize the template self.translator.reader.parse(parent, content) return parent
def createToken(self, match, parent): try: return self._createTable(match, parent) except Exception as e: msg = 'Failed to build table, the syntax is likely not correct:\n' raise exceptions.TokenizeException(msg, e.message)
def createToken(self, info, parent): """Create a LatexBlockEquation token.""" # Raw LaTeX appropriate for passing to KaTeX render method tex = r'{}'.format(info['equation']).strip('\n').replace( '\n', ' ').encode('string-escape') # Define a unique equation ID for use by KaTeX eq_id = 'moose-equation-{}'.format(uuid.uuid4()) # Build the token is_numbered = not info['cmd'].endswith('*') prefix = unicode(self.extension.get('prefix')) if is_numbered else None token = LatexBlockEquation(parent, tex=tex, prefix=prefix, id_=eq_id) # Add a label label = self.LABEL_RE.search(info['equation']) if label and not is_numbered: msg = "TeX non-numbered equations (e.g., equations*) may not include a \\label, since" \ "it will not be possible to refer to the equation." raise exceptions.TokenizeException(msg) elif label: token.tex = token.tex.replace(label.group().encode('ascii'), '') #pylint: disable=attribute-defined-outside-init tokens.Shortcut(parent.root, key=label.group('id'), link=u'#{}'.format(eq_id), content=u'{} {}'.format(prefix, token.number)) return parent
def createToken(self, match, parent): if self.settings['module'] is None: raise exceptions.TokenizeException( "The 'module' setting is required.") if self.settings['object'] is None: raise exceptions.TokenizeException( "The 'object' setting is required.") master = floats.Float(parent, **self.attributes) if self.settings['caption']: caption = floats.Caption(master, prefix=self.settings['prefix'], key=self.attributes['id']) grammar = self.reader.lexer.grammar('inline') self.reader.lexer.tokenize(caption, grammar, self.settings['caption'], match.line) try: mod = importlib.import_module(self.settings['module']) except ImportError: msg = "Unable to load the '{}' module." raise exceptions.TokenizeException(msg, self.settings['module']) try: obj = getattr(mod, self.settings['object']) except AttributeError: msg = "Unable to load the '{}' attribute from the '{}' module." raise exceptions.TokenizeException(msg, self.settings['object'], self.settings['module']) if hasattr(obj, 'defaultSettings'): settings = obj.defaultSettings() elif hasattr(obj, 'defaultConfig'): settings = obj.defaultConfig() else: msg = "The '{}' object in the '{}' module does not have a 'defaultSettings' or "\ "'defaultConfig' method." raise exceptions.TokenizeException(msg, mod, obj) rows = [[key, value[0], value[1]] for key, value in settings.iteritems()] tbl = table.builder(rows, headings=[u'Key', u'Default', u'Description']) tbl.parent = master return master
def createToken(self, info, parent): """ Build the tokens needed for displaying code listing. """ # Read filename filenames = common.project_find(info['subcommand']) if len(filenames) == 0: msg = "{} does not exist." raise exceptions.TokenizeException(msg, info['subcommand']) elif len(filenames) > 1: msg = "Multiple files located with matching name '{}':\n".format( info['subcommand']) for f in filenames: msg += ' {}\n'.format(f) raise exceptions.TokenizeException(msg) else: filename = filenames[0] # Listing container flt = floats.Float(parent) self.addCaption(flt) # Create code token lang = self.settings.get('language') lang = lang if lang else common.get_language(filename) tokens.Code(flt, style="max-height:{};".format(self.settings['max-height']), code=self.extractContent(filename, self.settings), language=lang) # Add bottom modal if self.settings['link']: code = tokens.Code(None, language=lang, code=common.read(filename)) floats.ModalLink(flt, url=unicode(filename), bottom=True, content=code, string=u'({})'.format( os.path.relpath(filename, MooseDocs.ROOT_DIR)), title=tokens.String(None, content=unicode(filename))) return parent
def extractInputBlocks(filename, blocks): hit = mooseutils.hit_load(filename) out = [] for block in blocks.split(' '): node = hit.find(block) if node is None: msg = "Unable to find block '{}' in {}." raise exceptions.TokenizeException(msg, block, filename) out.append(unicode(node.render())) return '\n'.join(out)
def createToken(self, info, parent): arch = self.settings['arch'] packages = self.extension.get('moose_packages', dict()) if arch not in packages: msg = "The supplied value for the 'arch' settings, {}, was not found." raise exceptions.TokenizeException(msg, arch) href = os.path.join(self.extension.get('link'), packages[arch]) tokens.Link(parent, url=unicode(href), string=unicode(packages[arch])) return parent
def createToken(self, info, parent): location = self.settings['location'] if location is None: node = self.translator.root else: func = lambda n: n.name == location and isinstance( n, page.DirectoryNode) node = anytree.search.find(self.translator.root, filter_=func) if not node: raise exceptions.TokenizeException( "Unable to locate the directory '{}'.", location) ContentsToken(parent, node=node) return parent
def createTokenFromSyntax(self, info, parent, obj): if obj.description is None: if not obj.hidden: msg = "The class description is missing for {}, it can be added using the " \ "'addClassDescription' method from within the objects validParams function." raise exceptions.TokenizeException(msg, obj.fullpath) else: tokens.Paragraph(parent, string=unicode(info[0]), class_='moose-error') return parent else: p = tokens.Paragraph(parent) self.translator.reader.parse(p, unicode(obj.description), group=MooseDocs.INLINE) return parent
def createToken(self, info, parent): marker = info['marker'] n = len(marker) token = self.TOKEN(parent) #pylint: disable=not-callable strip_regex = re.compile(r'^ {%s}(.*?)$' % n, flags=re.MULTILINE) for item in self.ITEM_RE.finditer(info['items']): content = ' ' * n + item.group('item') indent = re.search(r'^\S', content, flags=re.MULTILINE | re.UNICODE) if indent: msg = "List item content must be indented by {} to match the list item " \ "characters of '{}', to end a list item you must use two empty lines." raise exceptions.TokenizeException(msg.format(n, marker)) content = strip_regex.sub(r'\1', content) self.reader.parse(tokens.ListItem(token), content) return token
def __init__(self, *args, **kwargs): tokens.Token.__init__(self, *args, **kwargs) if self.show and self.hide: msg = "The 'show' and 'hide' properties cannot both be set." raise exceptions.TokenizeException(msg)
def testTokenizeException(self): with self.assertRaises(exceptions.TokenizeException) as e: raise exceptions.TokenizeException("{}", 'foo') self.assertEqual('foo', e.exception.message)
def __call__(self, info, parent): content = info['content'] if content == 'throw': raise exceptions.TokenizeException("testing") return tokens.Word(parent, content=content)