Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 36 additions & 10 deletions src/extensions/score_metamodel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
from score_cross_module_compatibility import get_reporter
from sphinx.application import Sphinx
from sphinx_needs import logging
from sphinx_needs.data import NeedsView, SphinxNeedsData
from sphinx_needs.config import NeedType
from sphinx_needs.data import SphinxNeedsData
from sphinx_needs.need_item import NeedItem
from sphinx_needs.views import NeedsView

from src.extensions.score_metamodel.bundle_metadata import apply_bundle_metadata
from src.extensions.score_metamodel.external_needs import connect_external_needs
Expand Down Expand Up @@ -113,12 +115,12 @@ def _location_prefix(srcdir: str | Path) -> str:


def _run_checks(app: Sphinx) -> None:
# First of all postprocess the need links to convert
# type names into actual need types.
# This must be done before any checks are run.
# And it must be done after config was hashed, otherwise
# the config hash would include recusive linking between types.
postprocess_need_links(app.config.needs_types)
# Link checks use the target type's SCORE rules, so resolve the names in
# mandatory_links_str and optional_links_str to the corresponding type objects.
# Do this at write-started, after Sphinx has compared the build configuration
# for incremental rebuilds. Types can reference each other, so resolving them
# during configuration would put cycles in the values Sphinx compares.
postprocess_need_links(app.config.score_need_types)

# Filter out external needs, as checks are only intended to be run
# on internal needs.
Expand All @@ -133,7 +135,7 @@ def _run_checks(app: Sphinx) -> None:
checks_filter = parse_checks_filter(app.config.score_metamodel_checks)

for directive, option, pattern in validate_mandatory_regexes(
app.config.needs_types
app.config.score_need_types
):
log.warning(
f"metamodel: `{directive}` mandatory option `{option}` "
Expand Down Expand Up @@ -253,7 +255,32 @@ def _clear_needs_defaults(app: Sphinx):
)


def register_score_need_types(app: Sphinx, need_types: list[ScoreNeedType]) -> None:
"""Register metamodel types during extension setup."""
# SCORE checks use the full definitions, including option patterns and valid
# link targets. Keep them in a config value so Sphinx can track rule changes.
app.config.score_need_types = [*app.config.score_need_types, *need_types]
Comment thread
a-zw marked this conversation as resolved.
Resolved

# Sphinx-Needs registers directives and validates the keys in needs_types.
# Give it a separate dict with the directive and presentation fields from
# the SCORE metamodel. The checks can enrich their own definitions later.
for need_type in need_types:
sphinx_type: NeedType = {
"directive": need_type["directive"],
"title": need_type["title"],
"prefix": need_type["prefix"],
}
if "color" in need_type:
sphinx_type["color"] = need_type["color"]
if "style" in need_type:
sphinx_type["style"] = need_type["style"]
app.config.needs_types.append(sphinx_type)


def setup(app: Sphinx) -> dict[str, str | bool]:
# SCORE rules affect validation of existing Needs, so changes to the rules
# must invalidate the Sphinx environment on incremental builds.
app.add_config_value("score_need_types", [], rebuild="env", types=list)
app.add_config_value("external_needs_source", "", rebuild="env")
app.add_config_value(
"runfiles_dir",
Expand All @@ -273,9 +300,8 @@ def setup(app: Sphinx) -> dict[str, str | bool]:
override_path = Path(raw_metamodel_path) if raw_metamodel_path else None
metamodel = load_metamodel_data(override_path)

# Extend sphinx-needs config rather than overwriting
_clear_needs_defaults(app)
app.config.needs_types += metamodel.needs_types
register_score_need_types(app, metamodel.needs_types)
app.config.needs_links.update(metamodel.needs_links)
app.config.needs_fields.update(metamodel.needs_fields)
# Sphinx-Needs validates every string-link option against the active
Expand Down
4 changes: 2 additions & 2 deletions src/extensions/score_metamodel/checks/attributes_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def check_id_format(app: Sphinx, need: NeedItem, log: CheckLogger):
the requirement id or not.
---
"""
need_options = get_need_type(app.config.needs_types, need["type"])
need_options = get_need_type(app.config.score_need_types, need["type"])
expected_parts = need_options.get("parts", 3)
id_parts = need["id"].split("__")
id_parts_len = len(id_parts)
Expand Down Expand Up @@ -109,7 +109,7 @@ def _check_options_for_prohibited_words(
# req-Id: tool_req__docs_common_attr_title
@local_check
def check_for_prohibited_words(app: Sphinx, need: NeedItem, log: CheckLogger):
need_options = get_need_type(app.config.needs_types, need["type"])
need_options = get_need_type(app.config.score_need_types, need["type"])
prohibited_word_checks: list[ProhibitedWordCheck] = (
app.config.prohibited_words_checks
)
Expand Down
31 changes: 22 additions & 9 deletions src/extensions/score_metamodel/checks/check_needs_extends.py
Comment thread
a-zw marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from sphinx_needs.needs_schema import (
FieldFunctionArray,
FieldLiteralValue,
FieldsSchema,
LinksFunctionArray,
LinksLiteralValue,
)
Expand Down Expand Up @@ -181,7 +182,7 @@ def _group_needs_and_extends_by_document(
) -> _DocumentToNeedsAndExtends:
"""Build the local candidate maps shared by validation and application.

Sphinx-Needs 8.5 stores mutable Needs by ID. Its filter walks every Need
Sphinx-Needs stores mutable Needs by ID. Its filter walks every Need
it receives, even for c.this_doc(). Indexing by docname once lets every
directive scan only the Needs in its own document.
"""
Expand Down Expand Up @@ -209,7 +210,9 @@ def score_extend_needs_data_func(
all_needs: NeedsMutable,
extends: dict[str, NeedsExtendType],
needs_config: NeedsSphinxConfig,
):
*,
schema: FieldsSchema,
) -> None:
"""Validate SCORE's needextend policy, then let Sphinx-Needs apply it.

This wrapper intentionally only reports violations. The unmodified directives
Expand All @@ -223,20 +226,30 @@ def score_extend_needs_data_func(
by_docname = _group_needs_and_extends_by_document(all_needs, extends)

# Give both passes the same local map so they enforce the same scope and
# both avoid scanning the full graph. Preserve source order for diagnostics
# and for directives that depend on earlier changes.
# both avoid scanning the full graph.
for document_data in by_docname.values():
# Sphinx-Needs applies extensions in source order as well. Matching that order
# keeps warning output stable and mirrors the later application order.
ordered_extends = sorted(document_data.needextends.values(), key=_location)
# Sphinx-Needs 9.3 applies needextend directives in
# (extend_priority, docname, lineno) order, lower priority first, and
# decides all targets before applying any of them.
ordered_extends = sorted(
document_data.needextends.values(),
key=lambda needextend: (
needextend["extend_priority"],
*_location(needextend),
),
)

for needextend in ordered_extends:
target_needs = _resolve_needextend_targets(
document_data.needs, all_needs, needextend, needs_config
)
for need in target_needs:
_ensure_non_destructive_changes(need, needextend, _location(needextend))
original_function(document_data.needs, document_data.needextends, needs_config)
original_function(
document_data.needs, document_data.needextends, needs_config, schema=schema
)
Comment thread
a-zw marked this conversation as resolved.
Resolved
Comment thread
a-zw marked this conversation as resolved.
Resolved


sphinx_needs.directives.need.extend_needs_data = score_extend_needs_data_func
# Patch the binding used by the need processor so SCORE can validate the
# directives before Sphinx-Needs applies them.
sphinx_needs.directives.need.extend_needs_data = score_extend_needs_data_func # pyright: ignore[reportPrivateImportUsage]
4 changes: 2 additions & 2 deletions src/extensions/score_metamodel/checks/check_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def check_options(
Checks that required and optional options and links are present
and follow their defined patterns.
"""
need_type = get_need_type(app.config.needs_types, need["type"])
need_type = get_need_type(app.config.score_need_types, need["type"])
Comment thread
a-zw marked this conversation as resolved.
Resolved

validate_options(log, need_type, need)
validate_links(log, need_type, need)
Expand All @@ -204,7 +204,7 @@ def check_extra_options(
system attributes.
"""

production_needs_types = app.config.needs_types
production_needs_types = app.config.score_need_types
need_options = get_need_type(production_needs_types, need["type"])

# set() creates a copy to avoid modifying the original
Expand Down
2 changes: 1 addition & 1 deletion src/extensions/score_metamodel/checks/graph_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
from sphinx.application import Sphinx
from sphinx_needs import logging
from sphinx_needs.config import NeedType
from sphinx_needs.data import NeedsView
from sphinx_needs.need_item import NeedItem
from sphinx_needs.views import NeedsView

# This is the normal logger for this module, not for warnings on specific needs.
# Use CheckLogger for that, which allows us to log the need id and location together with the warning message.
Expand Down
2 changes: 1 addition & 1 deletion src/extensions/score_metamodel/checks/testcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

from score_metamodel import CheckLogger, graph_check
from sphinx.application import Sphinx
from sphinx_needs.data import NeedsView
from sphinx_needs.need_item import NeedItem
from sphinx_needs.views import NeedsView

# Link-level policy is applied only to test types for which the requirement
# defines a mapping. Other test types remain valid without an inferred mapping.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@

from score_metamodel import CheckLogger, graph_check, local_check
from sphinx.application import Sphinx
from sphinx_needs.data import NeedsView
from sphinx_needs.need_item import NeedItem
from sphinx_needs.views import NeedsView


def _link_values(need: NeedItem, link_name: str) -> list[str]:
Expand Down
2 changes: 1 addition & 1 deletion src/extensions/score_metamodel/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

from docutils.nodes import Node
from score_cross_module_compatibility import CompatibilityReporter
from sphinx.util.logging import SphinxLoggerAdapter
from sphinx_needs import logging
from sphinx_needs.logging import SphinxLoggerAdapter
from sphinx_needs.need_item import NeedItem

Location = str | tuple[str | None, int | None] | Node | None
Expand Down
47 changes: 19 additions & 28 deletions src/extensions/score_metamodel/tests/rst/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

from sphinx.application import Sphinx

from src.extensions.score_metamodel import ScoreNeedType
from src.extensions.score_metamodel import ScoreNeedType, register_score_need_types

extensions = [
"sphinx_needs",
Expand Down Expand Up @@ -81,32 +81,23 @@ def setup(app: Sphinx):
"partially_verifies_list": "^.*$",
}

test_metadata_need_type: list[ScoreNeedType] = [
{
"directive": "test_metadata",
"title": "Test Metadata",
"prefix": "test_metadata__",
"tags": [],
"parts": 2,
"mandatory_options": {"id": "^test_metadata__.*$"},
"optional_options": add_options_regex_base | add_options_test_metadata,
"mandatory_links_str": {},
"mandatory_links": {},
"optional_links_str": {},
"optional_links": {},
}
]

# At parse time these are None, as they need to be filled post-parsing when all types are available to resolve the link targets.
# The dict maps the link name to a list of need types that are allowed as targets for that link.
test_metadata_need_type: ScoreNeedType = {
"directive": "test_metadata",
"title": "Test Metadata",
"prefix": "test_metadata__",
"tags": [],
"parts": 2,
"mandatory_options": {"id": "^test_metadata__.*$"},
"optional_options": add_options_regex_base | add_options_test_metadata,
"mandatory_links_str": {},
"mandatory_links": {},
"optional_links_str": {},
"optional_links": {},
}

changed_needs_types = list(test_metadata_need_type)
all_needs_types = app.config.needs_types
if "test_metadata" not in {nt["directive"] for nt in all_needs_types}:
for need_type in all_needs_types:
opts: dict[str, Any] = need_type.get("optional_options") or {}
opts.update(add_options_regex_base)
need_type["optional_options"] = opts
changed_needs_types.append(need_type)
app.config.needs_types = changed_needs_types
# Any fixture Need can carry expected diagnostics for the checks under test.
need_types: list[ScoreNeedType] = app.config.score_need_types
for need_type in need_types:
need_type["optional_options"].update(add_options_regex_base)
register_score_need_types(app, [test_metadata_need_type])
app.config.needs_fields.update(add_needs_fields)
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def _make_needextend(target: str, *, target_is_id: bool) -> NeedsExtendType:
{
"docname": "local",
"lineno": 1,
"extend_priority": 500,
"filter": target,
"filter_is_id": target_is_id,
"strict": False,
Expand Down Expand Up @@ -77,6 +78,7 @@ def test_id_shorthand_warns_for_a_need_in_another_document(
all_needs,
{"needextend-1": _make_needextend("remote-need", target_is_id=True)},
Mock(spec=NeedsSphinxConfig),
schema=Mock(),
)

apply_needextends_mock.assert_called_once()
Expand Down Expand Up @@ -115,14 +117,17 @@ def test_both_passes_use_the_document_index(monkeypatch: pytest.MonkeyPatch):
check_needs_extends, "original_function", apply_needextends_mock
)

check_needs_extends.score_extend_needs_data_func(all_needs, needextends, config)
schema = Mock()
check_needs_extends.score_extend_needs_data_func(
all_needs, needextends, config, schema=schema
)

assert [tuple(call.args[0]) for call in filter_needs_mock.call_args_list] == [
("local-need",),
("local-need",),
]
apply_needextends_mock.assert_called_once_with(
filter_needs_mock.call_args.args[0], needextends, config
filter_needs_mock.call_args.args[0], needextends, config, schema=schema
)


Expand Down
4 changes: 2 additions & 2 deletions src/extensions/score_metamodel/tests/test_check_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def test_unknown_directive(self):
logger = fake_check_logger()
app = Mock(spec=Sphinx)
app.config = Mock()
app.config.needs_types = self.NEED_TYPE_INFO
app.config.score_need_types = self.NEED_TYPE_INFO

with pytest.raises(ValueError):
check_options(app, need_1, cast(CheckLogger, logger))
Expand Down Expand Up @@ -114,7 +114,7 @@ def test_unknown_option_present_in_neither_req_opt_neither_opt_opt(self):
logger = fake_check_logger()
app = Mock(spec=Sphinx)
app.config = Mock()
app.config.needs_types = self.NEED_TYPE_INFO_WITH_OPT_OPT
app.config.score_need_types = self.NEED_TYPE_INFO_WITH_OPT_OPT
# Expect that the checks pass
check_extra_options(app, need_1, cast(CheckLogger, logger))

Expand Down
10 changes: 6 additions & 4 deletions src/extensions/score_metamodel/tests/test_external_needs.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,11 @@ def test_extend_needs_json_exporter_uses_configured_value(
ext_needs.extend_needs_json_exporter(config, ["project_url"])
config.project_url = "https://example.test/after"

needs_list = cast(NeedsList, SimpleNamespace(needs_list={}))
export_data: dict[str, object] = {}
needs_list = cast(NeedsList, SimpleNamespace(needs_list=export_data))
NeedsList._finalise(needs_list) # pyright: ignore[reportPrivateUsage] - white-box test

assert needs_list.needs_list["project_url"] == "https://example.test/after"
assert export_data["project_url"] == "https://example.test/after"


@add_test_properties(
Expand All @@ -87,11 +88,12 @@ def test_extend_needs_json_exporter_can_override_export_metadata(
export_values={"project_url": ""},
)

needs_list = cast(NeedsList, SimpleNamespace(needs_list={}))
export_data: dict[str, object] = {}
needs_list = cast(NeedsList, SimpleNamespace(needs_list=export_data))
NeedsList._finalise(needs_list) # pyright: ignore[reportPrivateUsage] - white-box test

assert config.project_url == "https://example.test/host"
assert needs_list.needs_list["project_url"] == ""
assert export_data["project_url"] == ""


@pytest.mark.parametrize(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
from score_metamodel.tests import fake_check_logger, need as make_need
from score_pytest.attribute_plugin import add_test_properties
from sphinx_needs.config import NeedType
from sphinx_needs.data import NeedsView
from sphinx_needs.need_item import NeedItem
from sphinx_needs.views import NeedsView


class DummyNeedsView:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
import pytest
from attribute_plugin import add_test_properties # type: ignore[import-untyped]
from sphinx.application import Sphinx
from sphinx_needs.data import NeedsView
from sphinx_needs.need_item import NeedItem
from sphinx_needs.views import NeedsView

from src.extensions.score_metamodel import CheckLogger
from src.extensions.score_metamodel.__init__ import (
Expand Down
2 changes: 1 addition & 1 deletion src/extensions/score_metamodel/tests/test_testcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@

import pytest
from score_pytest.attribute_plugin import add_test_properties
from sphinx_needs.data import NeedsView
from sphinx_needs.need_item import NeedItem
from sphinx_needs.views import NeedsView

from src.extensions.score_metamodel.checks.testcase import check_testcase_metadata
from src.extensions.score_metamodel.tests import fake_check_logger, need
Expand Down
Loading
Loading