Skip to content
Closed
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
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.13.11
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@

This provides decorators and collecting of decorated code, formatting it and writing to yaml file.

## Requirements

- Python >= 3.13

## Installation

The package name is `reqstool-python-decorators`.
Expand Down Expand Up @@ -45,7 +49,7 @@ reqstool-python-decorators = "<version>"
Import decorators:

```
from reqstool-decorators.decorators.decorators import Requirements, SVCs
from reqstool_python_decorators.decorators.decorators import Requirements, SVCs
```

Example usage of the decorators:
Expand All @@ -65,7 +69,7 @@ def test_somefunction():
Import processor:

```
from reqstool.processors.decorator_processor import DecoratorProcessor
from reqstool_python_decorators.processors.decorator_processor import DecoratorProcessor
```

Main function to collect decorators data and generate yaml file:
Expand All @@ -81,4 +85,4 @@ process_decorated_data(path_to_python_files, output_file)

## License

This project is licensed under the MIT License - see the LICENSE.md file for details.
This project is licensed under the MIT License.
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ dynamic = ["version"]
authors = [{ name = "reqstool" }]
description = "Reqstool Python Decorators"
readme = "README.md"
requires-python = ">=3.10"
requires-python = ">=3.13"
classifiers = [
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
Expand Down Expand Up @@ -48,7 +48,7 @@ dependencies = [

[tool.black]
line-length = 120
target-version = ['py310']
target-version = ['py313']

[tool.flake8]
ignore = ["W503"]
Expand Down
1 change: 1 addition & 0 deletions src/reqstool_python_decorators/decorators/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Copyright © LFV
14 changes: 8 additions & 6 deletions src/reqstool_python_decorators/decorators/decorators.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
# Copyright © LFV

from collections.abc import Callable

def Requirements(*requirements):
def decorator(func):
func.requirements = requirements

def Requirements[T: Callable](*requirements: str) -> Callable[[T], T]:
def decorator(func: T) -> T:
func.requirements = requirements # type: ignore[attr-defined]
return func

return decorator


def SVCs(*svc_ids):
def decorator(func):
func.svc_ids = svc_ids
def SVCs[T: Callable](*svc_ids: str) -> Callable[[T], T]:
def decorator(func: T) -> T:
func.svc_ids = svc_ids # type: ignore[attr-defined]
return func

return decorator
83 changes: 58 additions & 25 deletions src/reqstool_python_decorators/processors/decorator_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from enum import Enum, unique
import os
from typing import ReadOnly, TypedDict
from ruamel.yaml import YAML
import ast

Expand All @@ -19,6 +20,35 @@ def get_from_to(self):
return f"from: {self.from_value}, to: {self.to_value}"


class DecoratorInfo(TypedDict):
name: ReadOnly[str]
args: ReadOnly[list[str]]


class ElementResult(TypedDict):
fullyQualifiedName: ReadOnly[str]
elementKind: ReadOnly[str]
name: ReadOnly[str]
decorators: ReadOnly[list[DecoratorInfo]]


class FormattedEntry(TypedDict):
elementKind: str
fullyQualifiedName: str


class RequirementAnnotations(TypedDict):
implementations: dict[str, list[FormattedEntry]]
tests: dict[str, list[FormattedEntry]]


class FormattedData(TypedDict):
requirement_annotations: RequirementAnnotations


type Results = list[ElementResult]


class DecoratorProcessor:
"""
A class for collecting and processing Requirements and SVCs annotations on functions and classes in a directory.
Expand Down Expand Up @@ -47,14 +77,14 @@ def __init__(self, *args, **kwargs):

"""
super().__init__(*args, **kwargs)
self.req_svc_results = []
self.req_svc_results: Results = []

def find_python_files(self, directory):
def find_python_files(self, directory: str | os.PathLike) -> list[str]:
"""
Find Python files in the given directory.

Parameters:
- `directory` (str): The directory to search for Python files.
- `directory` (str | PathLike): The directory to search for Python files.

Returns:
- `python_files` (list): List of Python files found in the directory.
Expand All @@ -66,17 +96,16 @@ def find_python_files(self, directory):
python_files.append(os.path.join(root, file))
return python_files

def get_functions_and_classes(self, file_path, decorator_names):
def get_functions_and_classes(
self, file_path: str | os.PathLike, decorator_names: list[str]
) -> None:
"""
Get information about functions and classes, if annotated with "Requirements" or "SVCs":
decorator filepath, elementKind, name and decorators is saved to list that is returned.

Parameters:
- `file_path` (str): The path to the Python file.
- `decorator_names` (list): List of decorator names to search for.

Returns:
- `results` (list): List of dictionaries containing information about functions and classes.
- `file_path` (str | PathLike): The path to the Python file.
- `decorator_names` (list[str]): List of decorator names to search for.

Each dictionary includes:
- `fullyQualifiedName` (str): The fully qualified name of the file.
Expand All @@ -85,11 +114,11 @@ def get_functions_and_classes(self, file_path, decorator_names):
- `decorators` (list): List of dictionaries with decorator info including name and arguments e.g. "REQ_001".
"""
with open(file_path, "r") as file:
tree = ast.parse(file.read(), filename=file_path)
tree = ast.parse(file.read(), filename=str(file_path))

for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
decorators_info = []
decorators_info: list[DecoratorInfo] = []
for decorator_node in getattr(node, "decorator_list", []):
if isinstance(decorator_node, ast.Call) and isinstance(decorator_node.func, ast.Name):
decorator_name = decorator_node.func.id
Expand All @@ -100,18 +129,18 @@ def get_functions_and_classes(self, file_path, decorator_names):
self.req_svc_results.append(
{
"fullyQualifiedName": str(file_path).replace("/", "."),
"elementKind": str(type(node)).split(".")[-1][:-5].upper(),
"elementKind": node.__class__.__name__[:-3].upper(),
"name": node.name,
"decorators": decorators_info,
}
)

def write_to_yaml(self, output_file, formatted_data):
def write_to_yaml(self, output_file: str | os.PathLike, formatted_data) -> None:
"""
Write formatted data to a YAML file.

Parameters:
- `output_file` (str): The path to the output YAML file.
- `output_file` (str | PathLike): The path to the output YAML file.
- `formatted_data` (dict): The formatted data to be written to the YAML file.

Writes the formatted data to the specified YAML file.
Expand All @@ -135,25 +164,25 @@ def map_type(self, input_str) -> str:
mapping = {item.from_value: item.to_value for item in DECORATOR_TYPES}
return mapping.get(input_str, input_str)

def format_results(self, results):
def format_results(self, results: Results) -> FormattedData:
"""
Format the collected results into a structured data format for YAML.

Parameters:
- `results` (list): List of dictionaries containing information about functions and classes.

Returns:
- `formatted_data` (dict): Formatted data in a structured `yaml_language_server` compatible format.
- `formatted_data` (FormattedData): Formatted data in a structured `yaml_language_server` compatible format.

This function formats a list of decorated data into the structure required by the `yaml_language_server`.
It includes version information, requirement annotations, and relevant element information.
"""

formatted_data = {}
implementations = {}
tests = {}
requirement_annotations = {"implementations": implementations, "tests": tests}
formatted_data["requirement_annotations"] = requirement_annotations
implementations: dict[str, list[FormattedEntry]] = {}
tests: dict[str, list[FormattedEntry]] = {}
formatted_data: FormattedData = {
"requirement_annotations": {"implementations": implementations, "tests": tests}
}

for result in results:
for decorator_info in result["decorators"]:
Expand All @@ -174,31 +203,35 @@ def format_results(self, results):

return formatted_data

def create_dir_from_path(self, filepath: str) -> None:
def create_dir_from_path(self, filepath: str | os.PathLike) -> None:
"""
Creates directory of provided filepath if it does not exists

Parameters:
- `filepath` (str): Filepath to check and create directory from.
- `filepath` (str | PathLike): Filepath to check and create directory from.
"""
directory = os.path.dirname(filepath)
if not os.path.exists(directory):
os.makedirs(directory)

def process_decorated_data(
self, path_to_python_files: str, output_file: str = "build/reqstool/annotations.yml"
self,
path_to_python_files: list[str | os.PathLike],
output_file: str | os.PathLike = "build/reqstool/annotations.yml",
) -> None:
"""
"Main" function, runs all functions resulting in a yaml file containing decorated data.

Parameters:
- `path_to_python_files` (list): List of directories containing Python files.
- `output_file` (str): Set path for output file, defaults to build/annotations.yml
- `output_file` (str | PathLike): Set path for output file, defaults to build/annotations.yml

This method takes a list of directories containing Python files, collects decorated data from these files,
formats the collected data, and writes the formatted results to YAML file for Requirements and SVCs annotations.
"""

self.req_svc_results = []

for path in path_to_python_files:
python_files = self.find_python_files(directory=path)
for file_path in python_files:
Expand Down
2 changes: 1 addition & 1 deletion tests/resources/test_decorators/requirements_decorators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from src.reqstool_decorators.decorators.decorators import Requirements
from reqstool_python_decorators.decorators.decorators import Requirements


@Requirements("REQ_001", "REQ_222")
Expand Down
2 changes: 1 addition & 1 deletion tests/resources/test_decorators/svc_decorators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from src.reqstool_decorators.decorators.decorators import SVCs
from reqstool_python_decorators.decorators.decorators import SVCs


@SVCs("SVC_999")
Expand Down
Loading
Loading