コード例 #1
0
def test_parseargkwarg_1():
    s = "title='bah', name='john', purple='haze', none=None, i=1"
    args, kwargs = parse_argkwarg(s)
    assert args == []
    assert kwargs == {
        "title": "bah",
        "name": "john",
        "purple": "haze",
        "none": None,
        "i": 1,
    }
コード例 #2
0
def test_parseargkwarg_error():

    with pytest.raises(AssertionError):
        s = "'assets/tables/table.csv', sep = '\r\t', 'another path'"
        args, kwargs = parse_argkwarg(s)
コード例 #3
0
def test_parseargkwarg_7():
    s = "'table with space.csv', sep = '\r\t'"
    args, kwargs = parse_argkwarg(s)
    assert args == ["table with space.csv"]
    assert kwargs == {"sep": "\r\t"}
コード例 #4
0
def test_parseargkwarg_6():
    s = "'assets/tables/table.csv' ,  sep = '\r\t'"
    args, kwargs = parse_argkwarg(s)
    assert args == ["assets/tables/table.csv"]
    assert kwargs == {"sep": "\r\t"}
コード例 #5
0
def test_parseargkwarg_2():
    s = "'assets/tables/table.csv'"
    args, kwargs = parse_argkwarg(s)
    assert args == ["assets/tables/table.csv"]
    assert kwargs == {}
コード例 #6
0
    def on_page_markdown(self, markdown, page, config, files, **kwargs):
        """
        Replace jinja tag {{ read_csv() }} in markdown with markdown table.

        The page_markdown event is called after the page's markdown is loaded
        from file and can be used to alter the Markdown source text.
        The meta- data has been stripped off and is available as page.meta
        at this point.

        https://www.mkdocs.org/user-guide/plugins/#on_page_markdown

        Args:
            markdown (str): Markdown source text of page as string
            page: mkdocs.nav.Page instance
            config: global configuration object
            site_navigation: global navigation object

        Returns:
            str: Markdown source text of page as string
        """

        mkdocs_dir = os.path.dirname(os.path.abspath(config["config_file_path"]))

        for reader, function in READERS.items():
            
            # Regex pattern for tags like {{ read_csv(..) }}
            # match group 0: to extract any leading whitespace 
            # match group 1: to extract the arguments (positional and keywords)
            tag_pattern = re.compile(
                "( *)\{\{\s+%s\((.+)\)\s+\}\}" % reader, flags=re.IGNORECASE
            )

            matches = re.findall(tag_pattern, markdown)
            
            
            for result in matches:

                # Safely parse the arguments
                pd_args, pd_kwargs = parse_argkwarg(result[1])

                # Make sure the path is relative to "data_path"
                if len(pd_args) > 0:
                    pd_args[0] = os.path.join(self.config.get("data_path"), pd_args[0])
                    file_path = pd_args[0]

                if pd_kwargs.get("filepath_or_buffer"):
                    file_path = pd_kwargs["filepath_or_buffer"]
                    file_path = os.path.join(self.config.get("data_path"), file_path)
                    pd_kwargs["filepath_or_buffer"] = file_path

                # Load the table
                with cd(mkdocs_dir):
                    if not os.path.exists(file_path):
                        raise FileNotFoundError(
                            "[table-reader-plugin]: File does not exist: %s" % file_path
                        )

                    markdown_table = function(*pd_args, **pd_kwargs)

                # Deal with indentation
                # f.e. relevant when used inside content tabs
                leading_spaces = result[0]
                # make sure it's in multiples of 4 spaces
                leading_spaces = int(len(leading_spaces) / 4) * "    "
                # indent entire table
                fixed_lines = []
                for line in markdown_table.split('\n'):
                    fixed_lines.append(textwrap.indent(line, leading_spaces))
                
                markdown_table = "\n".join(fixed_lines)

                # Insert markdown table
                # By replacing first occurance of the regex pattern
                markdown = tag_pattern.sub(markdown_table, markdown, count=1)


        return markdown