Skip to content

Commit

Permalink
Added option to 'include-markdown' to disable includer comments
Browse files Browse the repository at this point in the history
  • Loading branch information
mondeja committed Dec 23, 2020
1 parent bca121a commit 3e11ee2
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 48 deletions.
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,14 @@ content to include.

- **start**: Delimiter that marks the beginning of the content to include.
- **end**: Delimiter that marks the end of the content to include.
- **rewrite_relative_urls**: When this option is enabled, Markdown links and
images in the content that are specified by a relative URL are rewritten to
work correctly in their new location. Default: `true`. Possible values are
- **rewrite_relative_urls** (*true*): When this option is enabled (default),
Markdown links and images in the content that are specified by a relative URL
are rewritten to work correctly in their new location. Possible values are
`true` and `false`.
- **comments** (*true*): When this option is enabled (default), the content to
include is wrapped by `<!-- BEGIN INCLUDE -->` and `<!-- END INCLUDE -->`
comments which help to identify that the content has been included. Possible
values are `true` and `false`.

> Note that the **start** and **end** strings may contain usual (Python-style)
escape sequences like `\n`, which is handy if you need to match on a multi-line
Expand All @@ -63,6 +67,7 @@ start or end trigger.
start="<!--\n\ttable-start\n-->"
end="<!--\n\ttable-end\n-->"
rewrite_relative_urls=false
comments=false
%}
```

Expand Down
2 changes: 1 addition & 1 deletion mkdocs_include_markdown_plugin/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
__title__ = 'mkdocs_include_markdown_plugin'
__version__ = '2.1.2'
__version__ = '2.2.0'
__description__ = 'Mkdocs Markdown includer plugin.'
36 changes: 25 additions & 11 deletions mkdocs_include_markdown_plugin/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
from mkdocs_include_markdown_plugin import process


TRUE_FALSE_STR_BOOL = {
'true': True,
'false': False
}

INCLUDE_TAG_REGEX = re.compile(
r'''
{% # opening tag
Expand All @@ -25,9 +30,10 @@
include\-markdown # directive name
\s+
"(?P<filename>[^"]+)" # "filename"
(?:\s+start="(?P<start>[^"]+)")? # optional start expression
(?:\s+end="(?P<end>[^"]+)")? # optional end expression
(?:\s+rewrite_relative_urls=(?P<rewrite_relative_urls>\w*))? # option
(?:\s+start="(?P<start>[^"]+)")?
(?:\s+end="(?P<end>[^"]+)")?
(?:\s+rewrite_relative_urls=(?P<rewrite_relative_urls>\w*))?
(?:\s+comments=(?P<comments>\w*))?
\s*
%} # closing tag
''',
Expand Down Expand Up @@ -64,13 +70,18 @@ def found_include_markdown_tag(match):
if end is not None:
end = process.interpret_escapes(end)

option_value = match.group('rewrite_relative_urls') or 'true'
if option_value not in ['true', 'false']:
raise ValueError(
'Unknown value for \'rewrite_relative_urls\'. Possible values '
'are: true, false'
)
should_rewrite_relative = {'true': True, 'false': False}[option_value]
bool_options = {
'rewrite_relative_urls': True,
'comments': True
}

for opt_name in bool_options:
try:
bool_options[opt_name] = TRUE_FALSE_STR_BOOL[
match.group(opt_name) or 'true']
except KeyError:
raise ValueError(('Unknown value for \'%s\'. Possible values '
'are: true, false') % opt_name)

file_path_abs = page_src_path.parent / filename

Expand All @@ -84,13 +95,16 @@ def found_include_markdown_tag(match):
if end is not None:
text_to_include, _, _ = text_to_include.partition(end)

if should_rewrite_relative:
if bool_options['rewrite_relative_urls']:
text_to_include = process.rewrite_relative_urls(
text_to_include,
source_path=file_path_abs,
destination_path=page_src_path,
)

if not bool_options['comments']:
return text_to_include

return (
'<!-- BEGIN INCLUDE %s %s %s -->\n' % (
filename, html.escape(start or ''), html.escape(end or '')
Expand Down
4 changes: 2 additions & 2 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
[bumpversion]
current_version = 2.1.2
current_version = 2.2.0

[bumpversion:file:mkdocs_include_markdown_plugin/__init__.py]

[coverage:run]
omit = mkdocs_include_markdown_plugin/plugin.py

[coverage:report]
exclude_lines =
exclude_lines =
pragma: no cover

[flake8]
Expand Down
66 changes: 35 additions & 31 deletions tests/test_include_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,17 @@
<!-- END INCLUDE -->
''',
)
),
# Exclude comments
(
'''{%
include-markdown "{filepath}"
comments=false
%}''',
'''Foo''',
'''Foo''',
),
),
)
def test_include_markdown(includer_schema, content_to_include,
Expand Down Expand Up @@ -171,14 +181,11 @@ def test_include_markdown(includer_schema, content_to_include,


def test_include_markdown_filepath_error(page):
page_content = '''# Header
{%
include-markdown "/path/to/file/that/does/not/exists"
start="<!--start-here-->"
end="<!--end-here-->"
%}
'''
page_content = '''{%
include-markdown "/path/to/file/that/does/not/exists"
start="<!--start-here-->"
end="<!--end-here-->"
%}'''

with tempfile.NamedTemporaryFile(suffix='.md') as f_includer:
f_includer.write(page_content.encode("utf-8"))
Expand All @@ -188,13 +195,11 @@ def test_include_markdown_filepath_error(page):
_on_page_markdown(page_content, page(f_includer.name))


@pytest.mark.parametrize('should_rewrite', [True, False, None])
def test_include_markdown_relative_rewrite(page, tmp_path, should_rewrite):
option_value = {
True: 'rewrite_relative_urls=true',
False: 'rewrite_relative_urls=false',
None: '',
}[should_rewrite]
@pytest.mark.parametrize('rewrite_relative_urls', ['true', 'false', None])
def test_include_markdown_relative_rewrite(page, tmp_path,
rewrite_relative_urls):
option_value = '' if rewrite_relative_urls is None else (
'rewrite_relative_urls=' + rewrite_relative_urls)

includer_path = tmp_path / 'includer.md'
includer_path.write_text(textwrap.dedent(f'''
Expand Down Expand Up @@ -226,7 +231,7 @@ def test_include_markdown_relative_rewrite(page, tmp_path, should_rewrite):
page(str(includer_path))
)

if should_rewrite in [True, None]:
if rewrite_relative_urls in ['true', None]:
assert output == textwrap.dedent('''
# Heading
Expand Down Expand Up @@ -257,19 +262,18 @@ def test_include_markdown_relative_rewrite(page, tmp_path, should_rewrite):
''') # noqa: E501


def test_include_markdown_relative_rewrite_invalid_option(page):
page_content = textwrap.dedent('''
# Header
{%
include-markdown "subfile.md"
rewrite_relative_urls=invalidoption
%}
''')
@pytest.mark.parametrize('opt_name', ('rewrite_relative_urls', 'comments'))
def test_include_markdown_invalid_bool_option(opt_name, page):
page_content = textwrap.dedent('''{%
include-markdown "subfile.md"
{opt_name}=invalidoption
%}''').replace('{opt_name}', opt_name)

with pytest.raises(ValueError) as excinfo:
_on_page_markdown(page_content, page('page.md'))
with tempfile.NamedTemporaryFile(suffix='.md') as f_includer:
with pytest.raises(ValueError) as excinfo:
_on_page_markdown(page_content, page(f_includer.name))

expected_exc_message = ('Unknown value for \'rewrite_relative_urls\'.'
' Possible values are: true, false')
assert expected_exc_message == str(excinfo.value)
expected_exc_message = (
'Unknown value for \'%(opt_name)s\'.'
' Possible values are: true, false') % {'opt_name': opt_name}
assert expected_exc_message == str(excinfo.value)

0 comments on commit 3e11ee2

Please sign in to comment.