Skip to content

Commit

Permalink
✨ NEW: suppress warnings in docutils (#655)
Browse files Browse the repository at this point in the history
with `myst_suppress_warnings` option, which works the same as sphinx `suppress_warnings`.
  • Loading branch information
chrisjsewell committed Jan 4, 2023
1 parent 9a4de68 commit 1b84a5b
Show file tree
Hide file tree
Showing 16 changed files with 241 additions and 146 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ A warning (of type `myst.nested_header`) is now emitted when this occurs.
- ✨ NEW: Add warning types `myst.subtype`:
All parsing warnings are assigned a type/subtype, and also the messages are appended with them.
These warning types can be suppressed with the sphinx `suppress_warnings` config option.
See [How-to suppress warnings](howto/warnings) for more information.
See [How-to suppress warnings](myst-warnings) for more information.

## 0.13.3 - 2021-01-20

Expand Down
2 changes: 2 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,11 @@ def setup(app: Sphinx):
DirectiveDoc,
DocutilsCliHelpDirective,
MystConfigDirective,
MystWarningsDirective,
)

app.add_css_file("custom.css")
app.add_directive("myst-config", MystConfigDirective)
app.add_directive("docutils-cli-help", DocutilsCliHelpDirective)
app.add_directive("doc-directive", DirectiveDoc)
app.add_directive("myst-warnings", MystWarningsDirective)
23 changes: 23 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,26 @@ substitution

tasklist
: Add check-boxes to the start of list items, [see here](syntax/tasklists) for details

(howto/warnings)=
(myst-warnings)=
## Build Warnings

Below lists the MyST specific warnings that may be emitted during the build process. These will be prepended to the end of the warning message, e.g.

```
WARNING: Non-consecutive header level increase; H1 to H3 [myst.header]
```

**In general, if your build logs any warnings, you should either fix them or [raise an Issue](https://github.com/executablebooks/MyST-Parser/issues/new/choose) if you think the warning is erroneous.**

However, in some circumstances if you wish to suppress the warning you can use the [`suppress_warnings`](https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-suppress_warnings) configuration option, e.g.

```python
suppress_warnings = ["myst.header"]
```

Or use `--myst-suppress-warnings="myst.header"` for the [docutils CLI](myst-docutils).

```{myst-warnings}
```
21 changes: 1 addition & 20 deletions docs/faq/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,28 +172,9 @@ like so:
{ref}`path/to/file_1:My Subtitle`
```

(howto/warnings)=
### Suppress warnings

In general, if your build logs any warnings, you should either fix them or [raise an Issue](https://github.com/executablebooks/MyST-Parser/issues/new/choose) if you think the warning is erroneous.
However, in some circumstances if you wish to suppress the warning you can use the [`suppress_warnings`](https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-suppress_warnings) configuration option.
All myst-parser warnings are prepended by their type, e.g. to suppress:

```md
# Title
### Subtitle
```

```
WARNING: Non-consecutive header level increase; H1 to H3 [myst.header]
```

Add to your `conf.py`:

```python
suppress_warnings = ["myst.header"]
```

Moved to [](myst-warnings)

### Sphinx-specific page front matter

Expand Down
2 changes: 1 addition & 1 deletion docs/syntax/optional.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ For example, `~~strikethrough with *emphasis*~~` renders as: ~~strikethrough wit
:::{warning}
This extension is currently only supported for HTML output,
and you will need to suppress the `myst.strikethrough` warning
(see [](howto/warnings))
(see [](myst-warnings))
:::

(syntax/math)=
Expand Down
32 changes: 30 additions & 2 deletions myst_parser/_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
from ._compat import get_args, get_origin
from .config.main import MdParserConfig
from .parsers.docutils_ import Parser as DocutilsParser
from .warnings_ import MystWarnings

logger = logging.getLogger(__name__)
LOGGER = logging.getLogger(__name__)


class _ConfigBase(SphinxDirective):
Expand Down Expand Up @@ -72,6 +73,9 @@ def run(self):
count = 0
for name, value, field in config.as_triple():

if field.metadata.get("deprecated"):
continue

# filter by sphinx options
if "sphinx" in self.options and field.metadata.get("sphinx_exclude"):
continue
Expand Down Expand Up @@ -146,7 +150,7 @@ def run(self):
name, self.state.memo.language, self.state.document
)
if klass is None:
logger.warning(f"Directive {name} not found.", line=self.lineno)
LOGGER.warning(f"Directive {name} not found.", line=self.lineno)
return []
content = " ".join(self.content)
text = f"""\
Expand Down Expand Up @@ -196,3 +200,27 @@ def convert_opt(name, func):
if func is other.int_or_nothing:
return "integer"
return ""


class MystWarningsDirective(SphinxDirective):
"""Directive to print all known warnings."""

has_content = False
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False

def run(self):
"""Run the directive."""
from sphinx.pycode import ModuleAnalyzer

analyzer = ModuleAnalyzer.for_module(MystWarnings.__module__)
qname = MystWarnings.__qualname__
analyzer.analyze()
warning_names = [
(e.value, analyzer.attr_docs[(qname, e.name)]) for e in MystWarnings
]
text = [f"- `myst.{name}`: {' '.join(doc)}" for name, doc in warning_names]
node = nodes.Element()
self.state.nested_parse(text, 0, node)
return node.children
43 changes: 28 additions & 15 deletions myst_parser/config/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
cast,
)

from myst_parser.warnings_ import MystWarnings
from .dc_validators import (
deep_iterable,
deep_mapping,
Expand Down Expand Up @@ -126,15 +127,6 @@ class MdParserConfig:
},
)

highlight_code_blocks: bool = dc.field(
default=True,
metadata={
"validator": instance_of(bool),
"help": "Syntax highlight code blocks with pygments",
"docutils_only": True,
},
)

number_code_blocks: Sequence[str] = dc.field(
default_factory=list,
metadata={
Expand Down Expand Up @@ -282,6 +274,27 @@ class MdParserConfig:
},
)

# docutils only (replicating aspects of sphinx config)

suppress_warnings: Sequence[str] = dc.field(
default_factory=list,
metadata={
"validator": deep_iterable(instance_of(str), instance_of((list, tuple))),
"help": "A list of warning types to suppress warning messages",
"docutils_only": True,
"global_only": True,
},
)

highlight_code_blocks: bool = dc.field(
default=True,
metadata={
"validator": instance_of(bool),
"help": "Syntax highlight code blocks with pygments",
"docutils_only": True,
},
)

def __post_init__(self):
validate_fields(self)

Expand Down Expand Up @@ -311,7 +324,7 @@ def as_triple(self) -> Iterable[Tuple[str, Any, dc.Field]]:
def merge_file_level(
config: MdParserConfig,
topmatter: Dict[str, Any],
warning: Callable[[str, str], None],
warning: Callable[[MystWarnings, str], None],
) -> MdParserConfig:
"""Merge the file-level topmatter with the global config.
Expand All @@ -324,21 +337,21 @@ def merge_file_level(
updates: Dict[str, Any] = {}
myst = topmatter.get("myst", {})
if not isinstance(myst, dict):
warning("topmatter", f"'myst' key not a dict: {type(myst)}")
warning(MystWarnings.MD_TOPMATTER, f"'myst' key not a dict: {type(myst)}")
else:
updates = myst

# allow html_meta and substitutions at top-level for back-compatibility
if "html_meta" in topmatter:
warning(
"topmatter",
MystWarnings.MD_TOPMATTER,
"top-level 'html_meta' key is deprecated, "
"place under 'myst' key instead",
)
updates["html_meta"] = topmatter["html_meta"]
if "substitutions" in topmatter:
warning(
"topmatter",
MystWarnings.MD_TOPMATTER,
"top-level 'substitutions' key is deprecated, "
"place under 'myst' key instead",
)
Expand All @@ -351,15 +364,15 @@ def merge_file_level(
for name, value in updates.items():

if name not in fields:
warning("topmatter", f"Unknown field: {name}")
warning(MystWarnings.MD_TOPMATTER, f"Unknown field: {name}")
continue

old_value, field = fields[name]

try:
validate_field(new, field, value)
except Exception as exc:
warning("topmatter", str(exc))
warning(MystWarnings.MD_TOPMATTER, str(exc))
continue

if field.metadata.get("merge_topmatter"):
Expand Down

0 comments on commit 1b84a5b

Please sign in to comment.