Skip to content

Commit

Permalink
Adds strict-mode for needextend (#748)
Browse files Browse the repository at this point in the history
* Adds strict-mode for needextend

* Added documentation for needextend strict option

* Added testcase for needextend strict option

* Updated testcase for needextend strict option

* Resolved some mistakes in documentation.

Co-authored-by: Duodu Randy <[email protected]>
  • Loading branch information
danwos and iSOLveIT authored Nov 8, 2022
1 parent 764f322 commit 791ffa5
Show file tree
Hide file tree
Showing 11 changed files with 338 additions and 7 deletions.
4 changes: 3 additions & 1 deletion docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ License
-----
Under development

* Improvement: Fixed :ref:`needextend` error handling by adding a strict-mode option to it.
(`#747 <https://github.com/useblocks/sphinx-needs/issues/747>`_)
* Improvement: Fixed issue with handling needs-variants by default.
(`#776 <https://github.com/useblocks/sphinx-needs/issues/776>`_)
* Improvement: Performance fix needs processing.
Expand Down Expand Up @@ -81,7 +83,7 @@ Released: 22.09.2022
* Improvement: Renamed jinja function `need` to `flow` for :ref:`needuml`.
* Improvement: Added directive :ref:`needarch`.
* Improvement: Added configuration option :ref:`needs_ide_snippets_id` to support custom need ID for :ref:`ide` snippets.
* Improvement: Provides jinja function :ref:`needarch_jinja_import` for :ref:`needarch` to execute :ref:`needuml_jinja_uml`
* Improvement: Provides jinja function :ref:`needarch_jinja_import` for :ref:`needarch` to execute :ref:`jinja_uml`
automatically for all the links defined in the need :ref:`need_links` options.
* Improvement: Added configuration :ref:`needs_ide_directive_snippets` to support custom directive snippets for IDE features.
(`#640 <https://github.com/useblocks/sphinx-needs/issues/640>`_)
Expand Down
9 changes: 9 additions & 0 deletions docs/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1694,6 +1694,15 @@ keys:
{% endraw %}
.. _needs_needextend_strict:
needs_needextend_strict
~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 1.0.3
``needs_needextend_strict`` allows you to deactivate or activate
the :ref:`strict <needextend_strict>` option behaviour for all :ref:`needextend` directives.
.. _needs_table_classes:
needs_table_classes
Expand Down
2 changes: 1 addition & 1 deletion docs/directives/need.rst
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ from any NeedLists or NeedDicts including the ``needs.json`` file.

This option allows a user to have multiple need-objects with the same id, but only one is shown in the documentation.

If set to **False**, the need is not removed.
If set to ``false``, the need is not removed.

Allowed values:

Expand Down
29 changes: 29 additions & 0 deletions docs/directives/needextend.rst
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,35 @@ Also, you can add links or delete tags.
.. This is a useless comment, but needed to supress a bug in docutils 0.18.1 , which can not handle
.. the above needextend if followed by a new sections.
Options
-------

.. _needextend_strict:

strict
~~~~~~
The purpose of the ``:strict:`` option is to handle whether an exception gets thrown
or a log-info message gets written if there is no need object to match the ``needextend's``
required argument (e.g. an ID).

If you set the ``:strict:`` option value to ``true``,
``needextend`` raises an exception because the given ID does not exist, and the build stops.

If you set the ``:strict:`` option value to ``false``,
``needextend`` logs an info-level message in the console, and the build continues.

Allowed values:

* true or
* false

Default: true

.. note::

We have a configuration (conf.py) option called :ref:`needs_needextend_strict`
that deactivates or activates the ``:strict:`` option behaviour for all ``needextend`` directives in a project.


Single need modification
------------------------
Expand Down
27 changes: 22 additions & 5 deletions sphinx_needs/directives/needextend.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,23 @@
from typing import Any, Callable, Dict, Sequence

from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives
from sphinx.application import Sphinx
from sphinx.util.docutils import SphinxDirective

from sphinx_needs.api.exceptions import NeedsInvalidFilter
from sphinx_needs.filter_common import filter_needs
from sphinx_needs.logging import get_logger
from sphinx_needs.utils import add_doc, unwrap

logger = get_logger(__name__)


class Needextend(nodes.General, nodes.Element):
pass


class NeedextendDirective(Directive):
class NeedextendDirective(SphinxDirective):
"""
Directive to modify existing needs
"""
Expand All @@ -28,7 +32,9 @@ class NeedextendDirective(Directive):
optional_arguments = 0
final_argument_whitespace = True

option_spec: Dict[str, Callable[[str], Any]] = {}
option_spec: Dict[str, Callable[[str], Any]] = {
"strict": directives.unchanged_required,
}

def run(self) -> Sequence[nodes.Node]:
env = self.state.document.settings.env
Expand All @@ -47,13 +53,20 @@ def run(self) -> Sequence[nodes.Node]:
if not extend_filter:
raise NeedsInvalidFilter(f"Filter of needextend must be set. See {env.docname}:{self.lineno}")

strict_option = self.options.get("strict", str(self.env.app.config.needs_needextend_strict))
if strict_option.upper() == "TRUE":
strict = True
elif strict_option.upper() == "FALSE":
strict = False

env.need_all_needextend[targetid] = {
"docname": env.docname,
"lineno": self.lineno,
"target_node": targetnode,
"env": env,
"filter": self.arguments[0] if self.arguments else None,
"modifications": self.options,
"strict": strict,
}

add_doc(env, env.docname)
Expand Down Expand Up @@ -89,8 +102,12 @@ def process_needextend(app: Sphinx, doctree: nodes.document, fromdocname: str) -
need_filter = f'id == "{need_filter}"'
# If it looks like a need id, but we haven't found one, raise an exception
elif re.fullmatch(app.config.needs_id_regex, need_filter):
raise NeedsInvalidFilter(f"Provided id {need_filter} for needextend does not exist.")

error = f"Provided id {need_filter} for needextend does not exist."
if current_needextend["strict"]:
raise NeedsInvalidFilter(error)
else:
logger.info(error)
continue
try:
found_needs = filter_needs(app, env.needs_all_needs.values(), need_filter)
except NeedsInvalidFilter as e:
Expand Down
2 changes: 2 additions & 0 deletions sphinx_needs/needs.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ def setup(app: Sphinx) -> Dict[str, Any]:
app.add_config_value("needs_duration_option", "duration", "html")
app.add_config_value("needs_completion_option", "completion", "html")

app.add_config_value("needs_needextend_strict", True, "html", types=[bool])

# If given, only the defined status are allowed.
# Values needed for each status:
# * name
Expand Down
20 changes: 20 additions & 0 deletions tests/doc_test/doc_needextend_strict/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = needstestdocs
SOURCEDIR = .
BUILDDIR = _build

# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
158 changes: 158 additions & 0 deletions tests/doc_test/doc_needextend_strict/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
#
# needs test docs documentation build configuration file, created by
# sphinx-quickstart on Tue Mar 28 11:37:14 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys

sys.path.insert(0, os.path.abspath("../../sphinxcontrib"))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.

extensions = ["sphinx_needs"]

needs_id_regex = "^[A-Za-z0-9_]*"
needs_types = [
{"directive": "story", "title": "User Story", "prefix": "US_", "color": "#BFD8D2", "style": "node"},
{"directive": "spec", "title": "Specification", "prefix": "SP_", "color": "#FEDCD2", "style": "node"},
{"directive": "impl", "title": "Implementation", "prefix": "IM_", "color": "#DF744A", "style": "node"},
{"directive": "test", "title": "Test Case", "prefix": "TC_", "color": "#DCB239", "style": "node"},
]

plantuml = "java -jar %s" % os.path.join(os.path.dirname(__file__), "..", "utils", "plantuml.jar")
plantuml_output_format = "svg"

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"

# The master toctree document.
master_doc = "index"

# General information about the project.
project = "needs test docs"
copyright = "2017, team useblocks"
author = "team useblocks"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = "1.0"
# The full version, including alpha/beta/rc tags.
release = "1.0"

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster"

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = "needstestdocsdoc"

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, "needstestdocs.tex", "needs test docs Documentation", "team useblocks", "manual"),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "needstestdocs", "needs test docs Documentation", [author], 1)]

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
"needstestdocs",
"needs test docs Documentation",
author,
"needstestdocs",
"One line description of project.",
"Miscellaneous",
),
]
28 changes: 28 additions & 0 deletions tests/doc_test/doc_needextend_strict/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
needextend strict-mode disabled
===============================

.. toctree::

page_1

.. story:: needextend Example 3
:id: extend_test_003

Had no outgoing links.
Got an outgoing link ``extend_test_004``.

.. story:: needextend Example 4
:id: extend_test_004

Had no links.
Got an incoming links ``extend_test_003`` and ``extend_test_006``.

.. needextend:: extend_test_003
:links: extend_test_004

.. needextend:: strict_disable_extend_test
:status: open
:strict: false

.. needextend:: strict_enable_extend_test
:status: closed
Loading

0 comments on commit 791ffa5

Please sign in to comment.