From 30ccf03fa849b5c6b550ab85aabce860a16b16cf Mon Sep 17 00:00:00 2001 From: David Luevano Alvarado Date: Wed, 15 Feb 2023 22:05:29 -0600 Subject: add more testing and fix small bugs --- src/pymdvar/__init__.py | 3 +++ src/pymdvar/py.typed | 0 src/pymdvar/pymdvar.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 src/pymdvar/__init__.py create mode 100644 src/pymdvar/py.typed create mode 100644 src/pymdvar/pymdvar.py (limited to 'src') diff --git a/src/pymdvar/__init__.py b/src/pymdvar/__init__.py new file mode 100644 index 0000000..b64a3b6 --- /dev/null +++ b/src/pymdvar/__init__.py @@ -0,0 +1,3 @@ +from .pymdvar import VariableExtension + +__all__ = ['VariableExtension'] \ No newline at end of file diff --git a/src/pymdvar/py.typed b/src/pymdvar/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/src/pymdvar/pymdvar.py b/src/pymdvar/pymdvar.py new file mode 100644 index 0000000..b6ea344 --- /dev/null +++ b/src/pymdvar/pymdvar.py @@ -0,0 +1,44 @@ +from os import getenv +from markdown.extensions import Extension +from markdown.inlinepatterns import Pattern + +VARIABLE_RE = r'(\$\{)([a-zA-Z_]*)(\})' + + +class VariablePattern(Pattern): + # need to redefine as an extra attribute needs to be passed + def __init__(self, pattern, variables, enable_env, md=None): + self.variables = variables + self.enable_env = enable_env + super().__init__(pattern, md) + + def handleMatch(self, m): + # for some reason the group is offest by 1 + variable = m.group(3) + value = '' + + if variable in self.variables: + value = self.variables[variable] + else: + if self.enable_env: + value = getenv(variable, '') + return value + + +class VariableExtension(Extension): + def __init__(self, **kwargs): + self.config = { + 'enable_env': [False, 'Enable environment variables parsing.'], + 'variables': [dict(), 'Dictionary holding variables to be used.'] + } + super().__init__(**kwargs) + + def extendMarkdown(self, md): + variables = self.getConfig('variables', dict()) + enable_env = self.getConfig('enable_env', False) + variable_pattern = VariablePattern(VARIABLE_RE, variables, enable_env) + md.inlinePatterns.register(variable_pattern, 'variable', 175) + + +def makeExtension(*args, **kwargs): + return VariableExtension(*args, **kwargs) -- cgit v1.2.3-70-g09d2