1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
|
"""
Collection of common sphinx-needs functions for dynamic values
.. note:: The function parameters ``app``, ``need``, ``needs`` are set automatically and can not be overridden by user.
"""
from __future__ import annotations
import contextlib
import re
from typing import Any
from sphinx.application import Sphinx
from sphinx_needs.api.exceptions import NeedsInvalidFilter
from sphinx_needs.config import NeedsSphinxConfig
from sphinx_needs.data import NeedsInfoType, NeedsMutable
from sphinx_needs.filter_common import (
filter_needs,
filter_single_need,
)
from sphinx_needs.logging import log_warning
from sphinx_needs.utils import logger
from sphinx_needs.views import NeedsView
def test(
app: Sphinx,
need: NeedsInfoType | None,
needs: NeedsMutable | NeedsView,
*args: Any,
**kwargs: Any,
) -> str:
"""
Test function for dynamic functions in sphinx needs.
Collects every given args and kwargs and returns a single string, which contains their values/keys.
.. need-example::
.. req:: test requirement
:ndf:`test('arg_1', [1,2,3], my_keyword='awesome')`
:return: single test string
"""
need_id = "none" if need is None else need["id"]
return f"Test output of dynamic function; need: {need_id}; args: {args}; kwargs: {kwargs}"
def echo(
app: Sphinx,
need: NeedsInfoType | None,
needs: NeedsMutable | NeedsView,
text: str,
*args: Any,
**kwargs: Any,
) -> str:
"""
.. versionadded:: 0.6.3
Just returns the given string back.
Mostly useful for tests.
.. need-example::
A nice :ndf:`echo("first test")` for a dynamic function.
"""
return text
def copy(
app: Sphinx,
need: NeedsInfoType | None,
needs: NeedsMutable | NeedsView,
option: str,
need_id: str | None = None,
lower: bool = False,
upper: bool = False,
filter: str | None = None,
) -> Any:
"""
Copies the value of one need option to another
.. need-example::
.. req:: copy-example
:id: copy_1
:tags: tag_1, tag_2, tag_3
:status: open
.. spec:: copy-example implementation
:id: copy_2
:status: [[copy("status", "copy_1")]]
:links: copy_1
:comment: [[copy("id")]]
Copies status of ``copy_1`` to own status.
Sets also a comment, which copies the id of own need.
.. test:: test of specification and requirement
:id: copy_3
:links: copy_2; [[copy('links', 'copy_2')]]
:tags: [[copy('tags', 'copy_1')]]
Set own link to ``copy_2`` and also copies all links from it.
Also copies all tags from copy_1.
If the filter_string needs to compare a value from the current need and the value is unknown yet,
you can reference the valued field by using ``current_need["my_field"]`` inside the filter string.
Small example::
.. test:: test of current_need value
:id: copy_4
The following copy command copies the title of the first need found under the same highest
section (headline):
:ndf:`copy('title', filter='current_need["sections"][-1]==sections[-1]')`
.. test:: test of current_need value
:id: copy_4
The following copy command copies the title of the first need found under the same highest
section (headline):
:ndf:`copy('title', filter='current_need["sections"][-1]==sections[-1]')`
:param option: Name of the option to copy
:param need_id: id of the need, which contains the source option. If None, current need is taken
:param upper: Is set to True, copied value will be uppercase
:param lower: Is set to True, copied value will be lowercase
:param filter: :ref:`filter_string`, which first result is used as copy source.
:return: string of copied need option
"""
if need_id:
need = needs[need_id]
if filter:
location = (
(need["docname"], need["lineno"]) if need and need["docname"] else None
)
result = filter_needs(
needs.values(),
NeedsSphinxConfig(app.config),
filter,
need,
location=location,
)
if result:
need = result[0]
if need is None:
raise ValueError("Need not found")
if option not in need:
raise ValueError(f"Option {option} not found in need {need['id']}")
value = need[option] # type: ignore[literal-required]
if lower:
return str(value).lower()
if upper:
return str(value).upper()
return value
def check_linked_values(
app: Sphinx,
need: NeedsInfoType | None,
needs: NeedsMutable | NeedsView,
result: Any,
search_option: str,
search_value: Any,
filter_string: str | None = None,
one_hit: bool = False,
) -> Any:
"""
Returns a specific value, if for all linked needs a given option has a given value.
The linked needs can be filtered by using the ``filter`` option.
If ``one_hit`` is set to True, only one linked need must have a positive match for the searched value.
**Examples**
**Needs used as input data**
.. need-example::
.. req:: Input A
:id: clv_A
:status: in progress
.. req:: Input B
:id: clv_B
:status: in progress
.. spec:: Input C
:id: clv_C
:status: closed
**Example 1: Positive check**
Status gets set to *progress*.
.. need-example::
.. spec:: result 1: Positive check
:links: clv_A, clv_B
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
:collapse: False
**Example 2: Negative check**
Status gets not set to *progress*, because status of linked need *clv_C* does not match *"in progress"*.
.. need-example::
.. spec:: result 2: Negative check
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
:collapse: False
**Example 3: Positive check thanks of used filter**
status gets set to *progress*, because linked need *clv_C* is not part of the filter.
.. need-example::
.. spec:: result 3: Positive check thanks of used filter
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', 'type == "req" ' )]]
:collapse: False
**Example 4: Positive check thanks of one_hit option**
Even *clv_C* has not the searched status, status gets anyway set to *progress*.
That's because ``one_hit`` is used so that only one linked need must have the searched
value.
.. need-example::
.. spec:: result 4: Positive check thanks of one_hit option
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]]
:collapse: False
**Result 5: Two checks and a joint status**
Two checks are performed and both are positive. So their results get joined.
.. need-example::
.. spec:: result 5: Two checks and a joint status
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]] [[check_linked_values('closed', 'status', 'closed', one_hit=True )]]
:collapse: False
:param result: value, which gets returned if all linked needs have parsed the checks
:param search_option: option name, which is used n linked needs for the search
:param search_value: value, which an option of a linked need must match
:param filter_string: Checks are only performed on linked needs, which pass the defined filter
:param one_hit: If True, only one linked need must have a positive check
:return: result, if all checks are positive
"""
if need is None:
raise ValueError("No need given for check_linked_values")
needs_config = NeedsSphinxConfig(app.config)
links = need["links"]
if not isinstance(search_value, list):
search_value = [search_value]
for link in links:
need = needs[link]
if filter_string:
try:
if not filter_single_need(need, needs_config, filter_string):
continue
except Exception as e:
log_warning(
logger,
f"CheckLinkedValues: Filter {filter_string} not valid: Error: {e}",
"filter",
None,
)
need_value = need[search_option] # type: ignore[literal-required]
if not one_hit and need_value not in search_value:
return None
elif one_hit and need_value in search_value:
return result
return result
def calc_sum(
app: Sphinx,
need: NeedsInfoType | None,
needs: NeedsMutable | NeedsView,
option: str,
filter: str | None = None,
links_only: bool = False,
) -> float:
"""
Sums the values of a given option in filtered needs up to single number.
Useful e.g. for calculating the amount of needed hours for implementation of all linked
specification needs.
**Input data**
.. spec:: Do this
:id: sum_input_1
:hours: 7
:collapse: False
.. spec:: Do that
:id: sum_input_2
:hours: 15
:collapse: False
.. spec:: Do too much
:id: sum_input_3
:hours: 110
:collapse: False
**Example 2**
.. need-example::
.. req:: Result 1
:amount: [[calc_sum("hours")]]
:collapse: False
**Example 2**
.. need-example::
.. req:: Result 2
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10")]]
:collapse: False
**Example 3**
.. need-example::
.. req:: Result 3
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", links_only="True")]]
:collapse: False
**Example 4**
.. need-example::
.. req:: Result 4
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10", "True")]]
:collapse: False
:param option: Options, from which the numbers shall be taken
:param filter: Filter string, which all needs must passed to get their value added.
:param links_only: If "True", only linked needs are taken into account.
:return: A float number
"""
if need is None:
raise ValueError("No need given for check_linked_values")
needs_config = NeedsSphinxConfig(app.config)
check_needs = (
[needs[link] for link in need["links"]] if links_only else needs.values()
)
calculated_sum = 0.0
for check_need in check_needs:
if filter:
try:
if not filter_single_need(check_need, needs_config, filter):
continue
except ValueError:
pass
except NeedsInvalidFilter as ex:
log_warning(
logger,
f"Given filter is not valid. Error: {ex}",
"filter",
None,
)
with contextlib.suppress(ValueError):
calculated_sum += float(check_need[option]) # type: ignore[literal-required]
return calculated_sum
def links_from_content(
app: Sphinx,
need: NeedsInfoType | None,
needs: NeedsMutable | NeedsView,
need_id: str | None = None,
filter: str | None = None,
) -> list[str]:
"""
Extracts links from content of a need.
All need-links set by using ``:need:`NEED_ID``` get extracted.
Same links are only added once.
Example:
.. req:: Requirement 1
:id: CON_REQ_1
.. req:: Requirement 2
:id: CON_REQ_2
.. spec:: Test spec
:id: CON_SPEC_1
:links: [[links_from_content()]]
This specification cares about the realisation of:
* :need:`CON_REQ_1`
* :need:`My need <CON_REQ_2>`
.. spec:: Test spec 2
:id: CON_SPEC_2
:links: [[links_from_content('CON_SPEC_1')]]
Links retrieved from content of :need:`CON_SPEC_1`
Used code of **CON_SPEC_1**::
.. spec:: Test spec
:id: CON_SPEC_1
:links: [[links_from_content()]]
This specification cares about the realisation of:
* :need:`CON_REQ_1`
* :need:`CON_REQ_2`
.. spec:: Test spec 2
:id: CON_SPEC_2
:links: [[links_from_content('CON_SPEC_1')]]
Links retrieved from content of :need:`CON_SPEC_1`
:param need_id: ID of need, which provides the content. If not set, current need is used.
:param filter: :ref:`filter_string`, which a found need-link must pass.
:return: List of linked need-ids in content
"""
source_need = needs[need_id] if need_id else need
if source_need is None:
raise ValueError("No need found for links_from_content")
links = re.findall(r":need:`(\w+)`|:need:`.+\<(.+)\>`", source_need["content"])
raw_links = []
for link in links:
if link[0] and link[0] not in raw_links:
raw_links.append(link[0])
elif link[1] and link[0] not in raw_links:
raw_links.append(link[1])
if filter:
needs_config = NeedsSphinxConfig(app.config)
filtered_links = []
for link in raw_links:
if link not in filtered_links and filter_single_need(
needs[link], needs_config, filter
):
filtered_links.append(link)
return filtered_links
return raw_links
|