Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🔧 Use future annotations in all modules #1111

Merged
merged 1 commit into from
Feb 15, 2024
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
12 changes: 6 additions & 6 deletions sphinx_needs/api/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
All functions here are available under ``sphinxcontrib.api``. So do not import this module directly.
"""

from typing import Callable, List, Optional
from __future__ import annotations

from typing import Callable

from docutils.parsers.rst import directives
from sphinx.application import Sphinx
Expand All @@ -17,7 +19,7 @@
from sphinx_needs.functions.functions import DynamicFunction


def get_need_types(app: Sphinx) -> List[str]:
def get_need_types(app: Sphinx) -> list[str]:
"""
Returns a list of directive-names from all configured need_types.

Expand Down Expand Up @@ -91,7 +93,7 @@ def add_extra_option(app: Sphinx, name: str) -> None:
NEEDS_CONFIG.extra_options[name] = directives.unchanged


def add_dynamic_function(app: Sphinx, function: DynamicFunction, name: Optional[str] = None) -> None:
def add_dynamic_function(app: Sphinx, function: DynamicFunction, name: str | None = None) -> None:
"""
Registers a new dynamic function for sphinx-needs.

Expand Down Expand Up @@ -122,9 +124,7 @@ def my_function(app, need, needs, *args, **kwargs):
WarningCheck = Callable[[NeedsInfoType, SphinxLoggerAdapter], bool]


def add_warning(
app: Sphinx, name: str, function: Optional[WarningCheck] = None, filter_string: Optional[str] = None
) -> None:
def add_warning(app: Sphinx, name: str, function: WarningCheck | None = None, filter_string: str | None = None) -> None:
"""
Registers a warning.

Expand Down
2 changes: 2 additions & 0 deletions sphinx_needs/api/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from sphinx.errors import SphinxError, SphinxWarning


Expand Down
36 changes: 19 additions & 17 deletions sphinx_needs/api/need.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from __future__ import annotations

import hashlib
import os
import re
from typing import Any, List, Optional, Union
from typing import Any

from docutils import nodes
from docutils.parsers.rst.states import RSTState
Expand Down Expand Up @@ -40,13 +42,13 @@ def add_need(
lineno: int,
need_type,
title: str,
id: Optional[str] = None,
id: str | None = None,
content: str = "",
status: Optional[str] = None,
status: str | None = None,
tags=None,
constraints=None,
constraints_passed=None,
links_string: Optional[str] = None,
links_string: str | None = None,
delete: bool = False,
jinja_content: bool = False,
hide: bool = False,
Expand All @@ -56,10 +58,10 @@ def add_need(
style=None,
layout=None,
template=None,
pre_template: Optional[str] = None,
post_template: Optional[str] = None,
pre_template: str | None = None,
post_template: str | None = None,
is_external: bool = False,
external_url: Optional[str] = None,
external_url: str | None = None,
external_css: str = "external_link",
**kwargs,
):
Expand Down Expand Up @@ -523,15 +525,15 @@ def del_need(app: Sphinx, need_id: str) -> None:
def add_external_need(
app: Sphinx,
need_type,
title: Optional[str] = None,
id: Optional[str] = None,
external_url: Optional[str] = None,
title: str | None = None,
id: str | None = None,
external_url: str | None = None,
external_css: str = "external_link",
content: str = "",
status: Optional[str] = None,
tags: Optional[str] = None,
constraints: Optional[str] = None,
links_string: Optional[str] = None,
status: str | None = None,
tags: str | None = None,
constraints: str | None = None,
links_string: str | None = None,
**kwargs: Any,
):
"""
Expand Down Expand Up @@ -621,7 +623,7 @@ def _render_plantuml_template(content: str, docname: str, lineno: int, state: RS
return node_need_content


def _read_in_links(links_string: Union[str, List[str]]) -> List[str]:
def _read_in_links(links_string: str | list[str]) -> list[str]:
# Get links
links = []
if links_string:
Expand All @@ -646,7 +648,7 @@ def _read_in_links(links_string: Union[str, List[str]]) -> List[str]:
return _fix_list_dyn_func(links)


def make_hashed_id(app: Sphinx, need_type: str, full_title: str, content: str, id_length: Optional[int] = None) -> str:
def make_hashed_id(app: Sphinx, need_type: str, full_title: str, content: str, id_length: int | None = None) -> str:
"""
Creates an ID based on title or need.

Expand Down Expand Up @@ -683,7 +685,7 @@ def make_hashed_id(app: Sphinx, need_type: str, full_title: str, content: str, i
return f"{type_prefix}{cal_hashed_id[:id_length]}"


def _fix_list_dyn_func(list: List[str]) -> List[str]:
def _fix_list_dyn_func(list: list[str]) -> list[str]:
"""
This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".

Expand Down
14 changes: 8 additions & 6 deletions sphinx_needs/builder.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import os
from typing import Iterable, List, Optional, Sequence, Set
from typing import Iterable, Sequence

from docutils import nodes
from sphinx import version_info
Expand Down Expand Up @@ -78,7 +80,7 @@ def finish(self) -> None:
from sphinx_needs.filter_common import filter_needs

filter_string = needs_config.builder_filter
filtered_needs: List[NeedsInfoType] = filter_needs(
filtered_needs: list[NeedsInfoType] = filter_needs(
data.get_or_create_needs().values(), needs_config, filter_string
)

Expand All @@ -96,11 +98,11 @@ def finish(self) -> None:
else:
LOGGER.info("Needs successfully exported")

def get_target_uri(self, _docname: str, _typ: Optional[str] = None) -> str:
def get_target_uri(self, _docname: str, _typ: str | None = None) -> str:
# only needed if the write phase is run
return ""

def prepare_writing(self, _docnames: Set[str]) -> None:
def prepare_writing(self, _docnames: set[str]) -> None:
# only needed if the write phase is run
pass

Expand Down Expand Up @@ -242,7 +244,7 @@ def finish(self) -> None:
def get_outdated_docs(self) -> Iterable[str]:
return []

def prepare_writing(self, _docnames: Set[str]) -> None:
def prepare_writing(self, _docnames: set[str]) -> None:
pass

def write_doc_serialized(self, _docname: str, _doctree: nodes.document) -> None:
Expand All @@ -251,7 +253,7 @@ def write_doc_serialized(self, _docname: str, _doctree: nodes.document) -> None:
def cleanup(self) -> None:
pass

def get_target_uri(self, _docname: str, _typ: Optional[str] = None) -> str:
def get_target_uri(self, _docname: str, _typ: str | None = None) -> str:
return ""


Expand Down
6 changes: 4 additions & 2 deletions sphinx_needs/defaults.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import os
from typing import Any, Dict
from typing import Any

from docutils.parsers.rst import directives

Expand Down Expand Up @@ -202,7 +204,7 @@
TITLE_REGEX = r'([^\s]+) as "([^"]+)"'


NEED_DEFAULT_OPTIONS: Dict[str, Any] = {
NEED_DEFAULT_OPTIONS: dict[str, Any] = {
"id": directives.unchanged_required,
"status": directives.unchanged_required,
"tags": directives.unchanged_required,
Expand Down
16 changes: 9 additions & 7 deletions sphinx_needs/diagrams_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
diagram related directive. E.g. needflow and needsequence.
"""

from __future__ import annotations

import html
import os
import textwrap
from typing import Any, Dict, List, Optional, Tuple, TypedDict
from typing import Any, TypedDict
from urllib.parse import urlparse

from docutils import nodes
Expand All @@ -27,14 +29,14 @@ class DiagramAttributesType(TypedDict):
show_legend: bool
show_filters: bool
show_link_names: bool
link_types: List[str]
link_types: list[str]
config: str
config_names: str
scale: str
highlight: str
align: Optional[str]
align: str | None
debug: bool
caption: Optional[str]
caption: str | None


class DiagramBase(SphinxDirective):
Expand All @@ -52,7 +54,7 @@ class DiagramBase(SphinxDirective):
"debug": directives.flag,
}

def create_target(self, target_name: str) -> Tuple[int, str, nodes.target]:
def create_target(self, target_name: str) -> tuple[int, str, nodes.target]:
id = self.env.new_serialno(target_name)
targetid = f"{target_name}-{self.env.docname}-{id}"
targetnode = nodes.target("", "", ids=[targetid])
Expand Down Expand Up @@ -184,8 +186,8 @@ def calculate_link(app: Sphinx, need_info: NeedsPartsInfoType, _fromdocname: str
return link


def create_legend(need_types: List[Dict[str, Any]]) -> str:
def create_row(need_type: Dict[str, Any]) -> str:
def create_legend(need_types: list[dict[str, Any]]) -> str:
def create_row(need_type: dict[str, Any]) -> str:
return "\n|<back:{color}> {color} </back>| {name} |".format(color=need_type["color"], name=need_type["title"])

rows = map(create_row, need_types)
Expand Down
6 changes: 4 additions & 2 deletions sphinx_needs/directives/list2need.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from __future__ import annotations

import hashlib
import re
from contextlib import suppress
from typing import Any, List, Sequence
from typing import Any, Sequence

from docutils import nodes
from docutils.parsers.rst import directives
Expand Down Expand Up @@ -201,7 +203,7 @@ def make_hashed_id(self, type_prefix: str, title: str, id_length: int) -> str:
type_prefix, hashlib.sha1(hashable_content.encode("UTF-8")).hexdigest().upper()[:id_length]
)

def get_down_needs(self, list_needs: List[Any], index: int) -> List[str]:
def get_down_needs(self, list_needs: list[Any], index: int) -> list[str]:
"""
Return all needs which are directly under the one given by the index
"""
Expand Down
30 changes: 16 additions & 14 deletions sphinx_needs/directives/need.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import hashlib
import re
from typing import Any, Dict, List, Optional, Sequence, Tuple
from typing import Any, Sequence

from docutils import nodes
from docutils.parsers.rst.states import RSTState, RSTStateMachine
Expand Down Expand Up @@ -53,8 +55,8 @@ class NeedDirective(SphinxDirective):
def __init__(
self,
name: str,
arguments: List[str],
options: Dict[str, Any],
arguments: list[str],
options: dict[str, Any],
content: StringList,
lineno: int,
content_offset: int,
Expand Down Expand Up @@ -149,7 +151,7 @@ def run(self) -> Sequence[nodes.Node]:
add_doc(env, self.docname)
return need_nodes # type: ignore[no-any-return]

def read_in_links(self, name: str) -> List[str]:
def read_in_links(self, name: str) -> list[str]:
# Get links
links_string = self.options.get(name)
links = []
Expand Down Expand Up @@ -229,12 +231,12 @@ def _get_full_title(self) -> str:


def get_sections_and_signature_and_needs(
need_node: Optional[nodes.Node],
) -> Tuple[List[str], Optional[nodes.Text], List[str]]:
need_node: nodes.Node | None,
) -> tuple[list[str], nodes.Text | None, list[str]]:
"""Gets the hierarchy of the section nodes as a list starting at the
section of the current need and then its parent sections"""
sections = []
parent_needs: List[str] = []
parent_needs: list[str] = []
signature = None
current_node = need_node
while current_node:
Expand Down Expand Up @@ -299,7 +301,7 @@ def analyse_need_locations(app: Sphinx, doctree: nodes.document) -> None:

needs = SphinxNeedsData(env).get_or_create_needs()

hidden_needs: List[Need] = []
hidden_needs: list[Need] = []
for need_node in doctree.findall(Need):
need_id = need_node["refid"]
need_info = needs[need_id]
Expand Down Expand Up @@ -346,7 +348,7 @@ def analyse_need_locations(app: Sphinx, doctree: nodes.document) -> None:
need_node.parent.remove(need_node)


def previous_sibling(node: nodes.Node) -> Optional[nodes.Node]:
def previous_sibling(node: nodes.Node) -> nodes.Node | None:
"""Return preceding sibling node or ``None``."""
try:
i = node.parent.index(node)
Expand Down Expand Up @@ -408,7 +410,7 @@ def process_need_nodes(app: Sphinx, doctree: nodes.document, fromdocname: str) -


@profile("NEED_FORMAT")
def format_need_nodes(app: Sphinx, doctree: nodes.document, fromdocname: str, found_needs_nodes: List[Need]) -> None:
def format_need_nodes(app: Sphinx, doctree: nodes.document, fromdocname: str, found_needs_nodes: list[Need]) -> None:
"""Replace need nodes in the document with node trees suitable for output"""
env = app.env
needs = SphinxNeedsData(env).get_or_create_needs()
Expand All @@ -428,7 +430,7 @@ def format_need_nodes(app: Sphinx, doctree: nodes.document, fromdocname: str, fo
build_need(layout, node_need, app, fromdocname=fromdocname)


def check_links(needs: Dict[str, NeedsInfoType], config: NeedsSphinxConfig) -> None:
def check_links(needs: dict[str, NeedsInfoType], config: NeedsSphinxConfig) -> None:
"""Checks if set links are valid or are dead (referenced need does not exist.)

For needs with dead links, an extra ``has_dead_links`` field is added and,
Expand Down Expand Up @@ -471,7 +473,7 @@ def check_links(needs: Dict[str, NeedsInfoType], config: NeedsSphinxConfig) -> N
)


def create_back_links(needs: Dict[str, NeedsInfoType], config: NeedsSphinxConfig) -> None:
def create_back_links(needs: dict[str, NeedsInfoType], config: NeedsSphinxConfig) -> None:
"""Create back-links in all found needs.

These are fields for each link type, ``<link_name>_back``,
Expand All @@ -482,7 +484,7 @@ def create_back_links(needs: Dict[str, NeedsInfoType], config: NeedsSphinxConfig
option_back = f"{option}_back"

for key, need in needs.items():
need_link_value: List[str] = [need[option]] if isinstance(need[option], str) else need[option] # type: ignore[literal-required]
need_link_value: list[str] = [need[option]] if isinstance(need[option], str) else need[option] # type: ignore[literal-required]
for need_id_full in need_link_value:
need_id_main, need_id_part = split_need_id(need_id_full)

Expand All @@ -497,7 +499,7 @@ def create_back_links(needs: Dict[str, NeedsInfoType], config: NeedsSphinxConfig
needs[need_id_main]["parts"][need_id_part][option_back].append(key) # type: ignore[literal-required]


def _fix_list_dyn_func(list: List[str]) -> List[str]:
def _fix_list_dyn_func(list: list[str]) -> list[str]:
"""
This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".

Expand Down
Loading
Loading