reqstool-python-decorators 0.1.dev10__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ # Copyright © LFV
@@ -1,17 +1,25 @@
1
1
  # Copyright © LFV
2
2
 
3
+ from collections.abc import Callable
3
4
 
4
- def Requirements(*requirements):
5
- def decorator(func):
6
- func.requirements = requirements
5
+
6
+ def Requirements[T: Callable](*requirements: str) -> Callable[[T], T]:
7
+ def decorator(func: T) -> T:
8
+ func.requirements = requirements # type: ignore[attr-defined]
7
9
  return func
8
10
 
9
11
  return decorator
10
12
 
11
13
 
12
- def SVCs(*svc_ids):
13
- def decorator(func):
14
- func.svc_ids = svc_ids
14
+ # Tagged here rather than on Requirements: by the time SVCs is defined, Requirements
15
+ # is already bound in module scope, so it can reference it as a decorator. Requirements
16
+ # can't self-tag this way (its own name isn't bound yet at its own def statement), but
17
+ # both factories jointly implement DECORATORS_001 -- this tag location is just where
18
+ # that fact gets recorded.
19
+ @Requirements("DECORATORS_001")
20
+ def SVCs[T: Callable](*svc_ids: str) -> Callable[[T], T]:
21
+ def decorator(func: T) -> T:
22
+ func.svc_ids = svc_ids # type: ignore[attr-defined]
15
23
  return func
16
24
 
17
25
  return decorator
@@ -2,13 +2,17 @@
2
2
 
3
3
  from enum import Enum, unique
4
4
  import os
5
+ from typing import ReadOnly, TypedDict
5
6
  from ruamel.yaml import YAML
6
7
  import ast
7
8
 
9
+ from reqstool_python_decorators.decorators.decorators import Requirements
10
+
8
11
 
9
12
  @unique
10
13
  class DECORATOR_TYPES(Enum):
11
14
  FUNCTION = ("FUNCTION", "METHOD")
15
+ ASYNCFUNCTION = ("ASYNCFUNCTION", "METHOD")
12
16
 
13
17
  def __init__(self, from_value, to_value):
14
18
  self.from_value = from_value
@@ -18,7 +22,36 @@ class DECORATOR_TYPES(Enum):
18
22
  return f"from: {self.from_value}, to: {self.to_value}"
19
23
 
20
24
 
21
- class ProcessDecorator:
25
+ class DecoratorInfo(TypedDict):
26
+ name: ReadOnly[str]
27
+ args: ReadOnly[list[str]]
28
+
29
+
30
+ class ElementResult(TypedDict):
31
+ fullyQualifiedName: ReadOnly[str]
32
+ elementKind: ReadOnly[str]
33
+ name: ReadOnly[str]
34
+ decorators: ReadOnly[list[DecoratorInfo]]
35
+
36
+
37
+ class FormattedEntry(TypedDict):
38
+ elementKind: str
39
+ fullyQualifiedName: str
40
+
41
+
42
+ class RequirementAnnotations(TypedDict):
43
+ implementations: dict[str, list[FormattedEntry]]
44
+ tests: dict[str, list[FormattedEntry]]
45
+
46
+
47
+ class FormattedData(TypedDict):
48
+ requirement_annotations: RequirementAnnotations
49
+
50
+
51
+ type Results = list[ElementResult]
52
+
53
+
54
+ class DecoratorProcessor:
22
55
  """
23
56
  A class for collecting and processing Requirements and SVCs annotations on functions and classes in a directory.
24
57
 
@@ -30,11 +63,8 @@ class ProcessDecorator:
30
63
  """
31
64
 
32
65
  decorators_to_search = ["Requirements", "SVCs"]
33
- reqsvc_yaml_path = "dist/all_annotations.yml"
34
66
 
35
- yaml_language_server = (
36
- "# yaml-language-server: $schema=https://schemas.se/requirements-tool/v1/annotations.schema.json\n"
37
- )
67
+ yaml_language_server = "# yaml-language-server: $schema=https://raw.githubusercontent.com/reqstool/reqstool-client/main/src/reqstool/resources/schemas/v1/annotations.schema.json\n" # noqa: E501
38
68
 
39
69
  def __init__(self, *args, **kwargs):
40
70
  """
@@ -49,14 +79,15 @@ class ProcessDecorator:
49
79
 
50
80
  """
51
81
  super().__init__(*args, **kwargs)
52
- self.req_svc_results = []
82
+ self.req_svc_results: Results = []
53
83
 
54
- def find_python_files(self, directory):
84
+ @Requirements("DECORATORS_002")
85
+ def find_python_files(self, directory: str | os.PathLike) -> list[str]:
55
86
  """
56
87
  Find Python files in the given directory.
57
88
 
58
89
  Parameters:
59
- - `directory` (str): The directory to search for Python files.
90
+ - `directory` (str | PathLike): The directory to search for Python files.
60
91
 
61
92
  Returns:
62
93
  - `python_files` (list): List of Python files found in the directory.
@@ -68,17 +99,15 @@ class ProcessDecorator:
68
99
  python_files.append(os.path.join(root, file))
69
100
  return python_files
70
101
 
71
- def get_functions_and_classes(self, file_path, decorator_names):
102
+ @Requirements("DECORATORS_002")
103
+ def get_functions_and_classes(self, file_path: str | os.PathLike, decorator_names: list[str]) -> None:
72
104
  """
73
105
  Get information about functions and classes, if annotated with "Requirements" or "SVCs":
74
106
  decorator filepath, elementKind, name and decorators is saved to list that is returned.
75
107
 
76
108
  Parameters:
77
- - `file_path` (str): The path to the Python file.
78
- - `decorator_names` (list): List of decorator names to search for.
79
-
80
- Returns:
81
- - `results` (list): List of dictionaries containing information about functions and classes.
109
+ - `file_path` (str | PathLike): The path to the Python file.
110
+ - `decorator_names` (list[str]): List of decorator names to search for.
82
111
 
83
112
  Each dictionary includes:
84
113
  - `fullyQualifiedName` (str): The fully qualified name of the file.
@@ -87,33 +116,34 @@ class ProcessDecorator:
87
116
  - `decorators` (list): List of dictionaries with decorator info including name and arguments e.g. "REQ_001".
88
117
  """
89
118
  with open(file_path, "r") as file:
90
- tree = ast.parse(file.read(), filename=file_path)
119
+ tree = ast.parse(file.read(), filename=str(file_path))
91
120
 
92
121
  for node in ast.walk(tree):
93
122
  if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
94
- decorators_info = []
123
+ decorators_info: list[DecoratorInfo] = []
95
124
  for decorator_node in getattr(node, "decorator_list", []):
96
125
  if isinstance(decorator_node, ast.Call) and isinstance(decorator_node.func, ast.Name):
97
126
  decorator_name = decorator_node.func.id
98
- args = [arg.s for arg in decorator_node.args if isinstance(arg, ast.Constant)]
127
+ args = [arg.value for arg in decorator_node.args if isinstance(arg, ast.Constant)]
99
128
  decorators_info.append({"name": decorator_name, "args": args})
100
129
 
101
130
  if any(decorator_info["name"] in decorator_names for decorator_info in decorators_info):
102
131
  self.req_svc_results.append(
103
132
  {
104
- "fullyQualifiedName": file_path,
105
- "elementKind": str(type(node)).split(".")[-1][:-5].upper(),
133
+ "fullyQualifiedName": str(file_path).replace("/", "."),
134
+ "elementKind": node.__class__.__name__.removesuffix("Def").upper(),
106
135
  "name": node.name,
107
136
  "decorators": decorators_info,
108
137
  }
109
138
  )
110
139
 
111
- def write_to_yaml(self, output_file, formatted_data):
140
+ @Requirements("DECORATORS_003")
141
+ def write_to_yaml(self, output_file: str | os.PathLike, formatted_data) -> None:
112
142
  """
113
143
  Write formatted data to a YAML file.
114
144
 
115
145
  Parameters:
116
- - `output_file` (str): The path to the output YAML file.
146
+ - `output_file` (str | PathLike): The path to the output YAML file.
117
147
  - `formatted_data` (dict): The formatted data to be written to the YAML file.
118
148
 
119
149
  Writes the formatted data to the specified YAML file.
@@ -133,11 +163,13 @@ class ProcessDecorator:
133
163
  yaml_file.write(self.yaml_language_server)
134
164
  yaml.dump(formatted_data, yaml_file)
135
165
 
166
+ @Requirements("DECORATORS_002")
136
167
  def map_type(self, input_str) -> str:
137
168
  mapping = {item.from_value: item.to_value for item in DECORATOR_TYPES}
138
169
  return mapping.get(input_str, input_str)
139
170
 
140
- def format_results(self, results):
171
+ @Requirements("DECORATORS_002")
172
+ def format_results(self, results: Results) -> FormattedData:
141
173
  """
142
174
  Format the collected results into a structured data format for YAML.
143
175
 
@@ -145,17 +177,17 @@ class ProcessDecorator:
145
177
  - `results` (list): List of dictionaries containing information about functions and classes.
146
178
 
147
179
  Returns:
148
- - `formatted_data` (dict): Formatted data in a structured `yaml_language_server` compatible format.
180
+ - `formatted_data` (FormattedData): Formatted data in a structured `yaml_language_server` compatible format.
149
181
 
150
182
  This function formats a list of decorated data into the structure required by the `yaml_language_server`.
151
183
  It includes version information, requirement annotations, and relevant element information.
152
184
  """
153
185
 
154
- formatted_data = {}
155
- implementations = {}
156
- tests = {}
157
- requirement_annotations = {"implementations": implementations, "tests": tests}
158
- formatted_data["requirement_annotations"] = requirement_annotations
186
+ implementations: dict[str, list[FormattedEntry]] = {}
187
+ tests: dict[str, list[FormattedEntry]] = {}
188
+ formatted_data: FormattedData = {
189
+ "requirement_annotations": {"implementations": implementations, "tests": tests}
190
+ }
159
191
 
160
192
  for result in results:
161
193
  for decorator_info in result["decorators"]:
@@ -176,21 +208,43 @@ class ProcessDecorator:
176
208
 
177
209
  return formatted_data
178
210
 
179
- def process_decorated_data(self, path_to_python_files):
211
+ @Requirements("DECORATORS_003")
212
+ def create_dir_from_path(self, filepath: str | os.PathLike) -> None:
213
+ """
214
+ Creates directory of provided filepath if it does not exists
215
+
216
+ Parameters:
217
+ - `filepath` (str | PathLike): Filepath to check and create directory from.
218
+ """
219
+ directory = os.path.dirname(filepath)
220
+ if not os.path.exists(directory):
221
+ os.makedirs(directory)
222
+
223
+ @Requirements("DECORATORS_002", "DECORATORS_003")
224
+ def process_decorated_data(
225
+ self,
226
+ path_to_python_files: list[str | os.PathLike],
227
+ output_file: str | os.PathLike = "build/reqstool/annotations.yml",
228
+ ) -> None:
180
229
  """
181
230
  "Main" function, runs all functions resulting in a yaml file containing decorated data.
182
231
 
183
232
  Parameters:
184
233
  - `path_to_python_files` (list): List of directories containing Python files.
234
+ - `output_file` (str | PathLike): Set path for output file, defaults to build/annotations.yml
185
235
 
186
236
  This method takes a list of directories containing Python files, collects decorated data from these files,
187
237
  formats the collected data, and writes the formatted results to YAML file for Requirements and SVCs annotations.
188
238
  """
189
239
 
240
+ self.req_svc_results = []
241
+
190
242
  for path in path_to_python_files:
191
243
  python_files = self.find_python_files(directory=path)
192
244
  for file_path in python_files:
193
245
  self.get_functions_and_classes(file_path=file_path, decorator_names=self.decorators_to_search)
246
+
194
247
  formatted_reqsvc_data = self.format_results(results=self.req_svc_results)
195
- reqsvc_yaml_path = "dist/annotations.yml"
196
- self.write_to_yaml(output_file=reqsvc_yaml_path, formatted_data=formatted_reqsvc_data)
248
+
249
+ self.create_dir_from_path(output_file)
250
+ self.write_to_yaml(output_file=output_file, formatted_data=formatted_reqsvc_data)
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: reqstool-python-decorators
3
+ Version: 0.2.0
4
+ Summary: Reqstool Python Decorators
5
+ Project-URL: Homepage, https://reqstool.github.io
6
+ Project-URL: Source, https://github.com/reqstool/reqstool-python-decorators.git
7
+ Project-URL: Documentation, https://github.com/reqstool/reqstool-python-decorators.git
8
+ Author: reqstool
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Requires-Python: >=3.13
15
+ Requires-Dist: ruamel-yaml==0.19.1
16
+ Description-Content-Type: text/markdown
17
+
18
+ [![Commit Activity](https://img.shields.io/github/commit-activity/m/reqstool/reqstool-python-decorators?label=commits&style=for-the-badge)](https://github.com/reqstool/reqstool-python-decorators/pulse)
19
+ [![GitHub Issues](https://img.shields.io/github/issues/reqstool/reqstool-python-decorators?style=for-the-badge&logo=github)](https://github.com/reqstool/reqstool-python-decorators/issues)
20
+ [![License](https://img.shields.io/github/license/reqstool/reqstool-python-decorators?style=for-the-badge&logo=opensourceinitiative)](https://opensource.org/license/mit/)
21
+ [![Build](https://img.shields.io/github/actions/workflow/status/reqstool/reqstool-python-decorators/build.yml?style=for-the-badge&logo=github)](https://github.com/reqstool/reqstool-python-decorators/actions/workflows/build.yml)
22
+ [![Documentation](https://img.shields.io/badge/Documentation-blue?style=for-the-badge&link=docs)](https://reqstool.github.io)
23
+
24
+ # Reqstool Python Decorators
25
+
26
+ Python decorators for [reqstool](https://github.com/reqstool/reqstool-client) requirements traceability. Provides `@Requirements` and `@SVCs` decorators for linking Python code to requirements and software verification cases.
27
+
28
+ ## Prerequisites
29
+
30
+ - Python >= 3.13
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install reqstool-python-decorators
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ from reqstool_python_decorators.decorators.decorators import Requirements, SVCs
42
+
43
+ @Requirements("REQ_111", "REQ_222")
44
+ def somefunction():
45
+ pass
46
+
47
+ @SVCs("SVC_111", "SVC_222")
48
+ def test_somefunction():
49
+ pass
50
+ ```
51
+
52
+ ### Processor
53
+
54
+ ```python
55
+ from reqstool_python_decorators.processors.decorator_processor import DecoratorProcessor
56
+
57
+ # Collect decorators and generate annotations.yml
58
+ process_decorated_data(path_to_python_files, output_file)
59
+ ```
60
+
61
+ Used together with the [Hatch Plugin](https://github.com/reqstool/reqstool-python-hatch-plugin) or [Poetry Plugin](https://github.com/reqstool/reqstool-python-poetry-plugin).
62
+
63
+ ## Documentation
64
+
65
+ Full documentation can be found [here](https://reqstool.github.io).
66
+
67
+ ## Contributing
68
+
69
+ See the organization-wide [CONTRIBUTING.md](https://github.com/reqstool/.github/blob/main/CONTRIBUTING.md).
70
+
71
+ ## License
72
+
73
+ MIT License.
@@ -0,0 +1,9 @@
1
+ reqstool_python_decorators/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ reqstool_python_decorators/decorators/__init__.py,sha256=9xL1ExocYj8K05rdGyEKT9CLX7bgWbOG3hsvDhWWnFc,19
3
+ reqstool_python_decorators/decorators/decorators.py,sha256=UtlQmqt2QdnCYHu8s4C54gMjvNrp5zlzZYWF6haTYe8,876
4
+ reqstool_python_decorators/processors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ reqstool_python_decorators/processors/decorator_processor.py,sha256=UlBMMGP6eE2x7BL9TBZGciL2b7q2gkB0u4qAXtyWeh4,9759
6
+ reqstool_python_decorators-0.2.0.dist-info/METADATA,sha256=6xb99W6dkLof0T9PagPugPQKTTUM1l3o-7gszJnFpYw,2805
7
+ reqstool_python_decorators-0.2.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
8
+ reqstool_python_decorators-0.2.0.dist-info/licenses/LICENSE,sha256=FVfPRmqjYUYTodYsh2C7Y70MWH64m0aWgTeIbqPj-P0,1060
9
+ reqstool_python_decorators-0.2.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.21.1
2
+ Generator: hatchling 1.29.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,93 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: reqstool-python-decorators
3
- Version: 0.1.dev10
4
- Summary: Reqstool Python Decorators
5
- Project-URL: Source, https://github.com/Luftfartsverket/reqstool-python-decorators.git
6
- Author-email: LFV SYSDEV <sysdev@lfv.com>
7
- License-File: LICENSE
8
- Classifier: Development Status :: 4 - Beta
9
- Classifier: License :: OSI Approved :: MIT License
10
- Classifier: Operating System :: OS Independent
11
- Classifier: Programming Language :: Python :: 3
12
- Requires-Python: >=3.10
13
- Requires-Dist: ruamel-yaml>=0.18.5
14
- Description-Content-Type: text/markdown
15
-
16
- # Reqstool Python Decorators
17
-
18
- ## Description
19
-
20
- This provides decorators and collecting of decorated code, formatting it and writing to yaml file.
21
-
22
- ## Installation
23
-
24
- The package name is `reqstool-decorators`.
25
-
26
- * Using pip install:
27
-
28
- ```
29
- $pip install reqstool-decorators
30
- ```
31
-
32
- ## Using
33
-
34
- ### pyproject.toml
35
-
36
- * Hatch
37
-
38
- ```
39
- dependencies = [
40
- "reqstool-decorators == <version>"
41
- ]
42
- ```
43
-
44
- * Poetry
45
-
46
- ```
47
- [tool.poetry.dependencies]
48
- reqstool-decorators = "<version>"
49
- ```
50
-
51
- ### Decorators
52
-
53
- Import decorators:
54
-
55
- ```
56
- from reqstool-decorators.decorators.decorators import Requirements, SVCs
57
- ```
58
-
59
- Example usage of the decorators:
60
-
61
- ```
62
- @Requirements(REQ_111, REQ_222)
63
- def somefunction():
64
- ```
65
-
66
- ```
67
- @SVCs(SVC_111, SVC_222)
68
- def test_somefunction():
69
- ```
70
-
71
- ### Processor
72
-
73
- Import processor:
74
-
75
- ```
76
- from reqstool.processors.decorator_processor import ProcessDecorator
77
- ```
78
-
79
- Main function to collect decorators data and generate yaml file:
80
-
81
- ```
82
- process_decorated_data(path_to_python_files)
83
- ```
84
-
85
- Here `path_to_python_files` is the directories to search through to find decorated code.
86
-
87
- *Note:*
88
-
89
- Yaml file is saved into the `/dist` folder, make sure the folder exists before running the `process_decorated_data` function.
90
-
91
- ## License
92
-
93
- This project is licensed under the MIT License - see the LICENSE.md file for details.
@@ -1,8 +0,0 @@
1
- reqstool_python_decorators/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- reqstool_python_decorators/decorators/decorators.py,sha256=7TnBcVour2VSH76rM4FtwmCDi9JY9gxqOvAL6o1kI_g,282
3
- reqstool_python_decorators/processors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- reqstool_python_decorators/processors/decorator_processor.py,sha256=DdfcNYMx0QbOqtU1nHGLYsNY_I1ru-11eVbovt5MiN0,7915
5
- reqstool_python_decorators-0.1.dev10.dist-info/METADATA,sha256=gBTLkT8lgXu7vCnLkOeNo-G-y8iF0x3AHOudxCeTb9k,1835
6
- reqstool_python_decorators-0.1.dev10.dist-info/WHEEL,sha256=TJPnKdtrSue7xZ_AVGkp9YXcvDrobsjBds1du3Nx6dc,87
7
- reqstool_python_decorators-0.1.dev10.dist-info/licenses/LICENSE,sha256=FVfPRmqjYUYTodYsh2C7Y70MWH64m0aWgTeIbqPj-P0,1060
8
- reqstool_python_decorators-0.1.dev10.dist-info/RECORD,,