python-utility-scripts 1.0.4__tar.gz → 1.0.5__tar.gz

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.
Files changed (18) hide show
  1. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/PKG-INFO +1 -1
  2. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/jira_utils/jira_information.py +23 -24
  3. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/polarion/polarion_set_automated.py +7 -7
  4. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/polarion/polarion_utils.py +15 -14
  5. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/polarion/polarion_verify_tc_requirements.py +4 -3
  6. python_utility_scripts-1.0.5/apps/unused_code/unused_code.py +148 -0
  7. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/utils.py +4 -3
  8. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/pyproject.toml +3 -2
  9. python_utility_scripts-1.0.4/apps/unused_code/unused_code.py +0 -110
  10. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/LICENSE +0 -0
  11. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/README.md +0 -0
  12. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/__init__.py +0 -0
  13. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/jira_utils/README.md +0 -0
  14. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/jira_utils/__init__.py +0 -0
  15. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/polarion/README.md +0 -0
  16. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/polarion/__init__.py +0 -0
  17. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/unused_code/README.md +0 -0
  18. {python_utility_scripts-1.0.4 → python_utility_scripts-1.0.5}/apps/unused_code/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-utility-scripts
3
- Version: 1.0.4
3
+ Version: 1.0.5
4
4
  Summary: Python utility scripts
5
5
  Home-page: https://github.com/RedHatQE/python-utility-scripts
6
6
  License: Apache-2.0
@@ -1,20 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ import concurrent.futures
1
4
  import logging
5
+ import os
2
6
  import re
3
7
  import sys
4
- import os
5
- import concurrent.futures
6
8
  from functools import lru_cache
9
+ from typing import Any
7
10
 
8
11
  import click
9
- from jira import JIRA, JIRAError, Issue
10
-
12
+ from jira import JIRA, Issue, JIRAError
11
13
  from simple_logger.logger import get_logger
12
-
13
- from apps.utils import ListParamType
14
- from typing import Dict, List, Set, Tuple, Any
15
-
16
14
  from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed
17
- from apps.utils import all_python_files, get_util_config
15
+
16
+ from apps.utils import ListParamType, all_python_files, get_util_config
18
17
 
19
18
  LOGGER = get_logger(name=__name__)
20
19
 
@@ -29,7 +28,7 @@ def get_issue(
29
28
  return jira.issue(id=jira_id, fields="status, issuetype, fixVersions")
30
29
 
31
30
 
32
- def get_jira_ids_from_file_content(file_content: str, issue_pattern: str, jira_url: str) -> Set[str]:
31
+ def get_jira_ids_from_file_content(file_content: str, issue_pattern: str, jira_url: str) -> set[str]:
33
32
  """
34
33
  Try to find all Jira tickets in a given file content.
35
34
 
@@ -55,7 +54,7 @@ def get_jira_ids_from_file_content(file_content: str, issue_pattern: str, jira_u
55
54
  return set(_pytest_jira_marker_bugs + _jira_id_arguments + _jira_url_jiras)
56
55
 
57
56
 
58
- def get_jiras_from_python_files(issue_pattern: str, jira_url: str) -> Dict[str, Set[str]]:
57
+ def get_jiras_from_python_files(issue_pattern: str, jira_url: str) -> dict[str, set[str]]:
59
58
  """
60
59
  Get all python files from the current directory and get list of jira ids from each of them
61
60
 
@@ -68,7 +67,7 @@ def get_jiras_from_python_files(issue_pattern: str, jira_url: str) -> Dict[str,
68
67
 
69
68
  Note: any line containing <skip-jira_utils-check> would be not be checked for presence of a jira id
70
69
  """
71
- jira_found: Dict[str, Set[str]] = {}
70
+ jira_found: dict[str, set[str]] = {}
72
71
  for filename in all_python_files():
73
72
  file_content = []
74
73
  with open(filename) as fd:
@@ -91,12 +90,12 @@ def get_jiras_from_python_files(issue_pattern: str, jira_url: str) -> Dict[str,
91
90
  def get_jira_information(
92
91
  jira_object: JIRA,
93
92
  jira_id: str,
94
- skip_project_ids: List[str],
95
- resolved_status: List[str],
96
- jira_target_versions: List[str],
93
+ skip_project_ids: list[str],
94
+ resolved_status: list[str],
95
+ jira_target_versions: list[str],
97
96
  target_version_str: str,
98
97
  file_name: str,
99
- ) -> Tuple[str, str]:
98
+ ) -> tuple[str, str]:
100
99
  jira_error_string = ""
101
100
  try:
102
101
  # check resolved status:
@@ -133,11 +132,11 @@ def process_jira_command_line_config_file(
133
132
  url: str,
134
133
  token: str,
135
134
  issue_pattern: str,
136
- resolved_statuses: List[str],
135
+ resolved_statuses: list[str],
137
136
  version_string_not_targeted_jiras: str,
138
- target_versions: List[str],
139
- skip_projects: List[str],
140
- ) -> Dict[str, Any]:
137
+ target_versions: list[str],
138
+ skip_projects: list[str],
139
+ ) -> dict[str, Any]:
141
140
  # Process all the arguments passed from command line or config file or environment variable
142
141
  config_dict = get_util_config(util_name="pyutils-jira", config_file_path=config_file_path)
143
142
  url = url or config_dict.get("url", "")
@@ -201,11 +200,11 @@ def process_jira_command_line_config_file(
201
200
  @click.option("--verbose", default=False, is_flag=True)
202
201
  def get_jira_mismatch(
203
202
  config_file_path: str,
204
- target_versions: List[str],
203
+ target_versions: list[str],
205
204
  url: str,
206
205
  token: str,
207
- skip_projects: List[str],
208
- resolved_statuses: List[str],
206
+ skip_projects: list[str],
207
+ resolved_statuses: list[str],
209
208
  issue_pattern: str,
210
209
  version_string_not_targeted_jiras: str,
211
210
  verbose: bool,
@@ -228,7 +227,7 @@ def get_jira_mismatch(
228
227
  )
229
228
 
230
229
  jira_obj = JIRA(token_auth=jira_config_dict["token"], options={"server": jira_config_dict["url"]})
231
- jira_error: Dict[str, str] = {}
230
+ jira_error: dict[str, str] = {}
232
231
 
233
232
  if jira_id_dict := get_jiras_from_python_files(
234
233
  issue_pattern=jira_config_dict["issue_pattern"], jira_url=jira_config_dict["url"]
@@ -1,18 +1,18 @@
1
1
  from __future__ import annotations
2
+
2
3
  import logging
3
4
  import os
4
- from simple_logger.logger import get_logger
5
5
  import sys
6
- import click
7
6
 
8
- from apps.polarion.polarion_utils import get_polarion_project_id, find_polarion_ids, update_polarion_ids
9
- from typing import List, Dict, Optional
7
+ import click
8
+ from simple_logger.logger import get_logger
10
9
 
10
+ from apps.polarion.polarion_utils import find_polarion_ids, get_polarion_project_id, update_polarion_ids
11
11
 
12
12
  LOGGER = get_logger(name=__name__)
13
13
 
14
14
 
15
- def approve_tests(polarion_project_id: str, added_ids: List[str]) -> Dict[str, List[str]]:
15
+ def approve_tests(polarion_project_id: str, added_ids: list[str]) -> dict[str, list[str]]:
16
16
  LOGGER.debug(f"Following polarion ids were added: {added_ids}")
17
17
  return update_polarion_ids(
18
18
  polarion_ids=list(added_ids), project_id=polarion_project_id, is_automated=True, is_approved=True
@@ -20,8 +20,8 @@ def approve_tests(polarion_project_id: str, added_ids: List[str]) -> Dict[str, L
20
20
 
21
21
 
22
22
  def remove_approved_tests(
23
- polarion_project_id: str, branch: str, added_ids: Optional[List[str]] = None
24
- ) -> Dict[str, List[str]]:
23
+ polarion_project_id: str, branch: str, added_ids: list[str] | None = None
24
+ ) -> dict[str, list[str]]:
25
25
  removed_polarions = {}
26
26
  added_ids = added_ids or []
27
27
  if removed_ids := set(
@@ -1,12 +1,13 @@
1
1
  from __future__ import annotations
2
+
2
3
  import re
3
- import sys
4
- from simple_logger.logger import get_logger
5
4
  import shlex
6
5
  import subprocess
6
+ import sys
7
+
8
+ from simple_logger.logger import get_logger
7
9
 
8
10
  from apps.utils import get_util_config
9
- from typing import Dict, List
10
11
 
11
12
  LOGGER = get_logger(name=__name__)
12
13
  AUTOMATED = "automated"
@@ -19,8 +20,8 @@ def git_diff(branch: str) -> str:
19
20
  return data.decode()
20
21
 
21
22
 
22
- def git_diff_lines(branch: str) -> Dict[str, List[str]]:
23
- diff: Dict[str, List[str]] = {}
23
+ def git_diff_lines(branch: str) -> dict[str, list[str]]:
24
+ diff: dict[str, list[str]] = {}
24
25
  for line in git_diff(branch=branch).splitlines():
25
26
  LOGGER.debug(line)
26
27
  if line.startswith("+"):
@@ -31,13 +32,13 @@ def git_diff_lines(branch: str) -> Dict[str, List[str]]:
31
32
 
32
33
 
33
34
  def validate_polarion_requirements(
34
- polarion_test_ids: List[str],
35
+ polarion_test_ids: list[str],
35
36
  polarion_project_id: str,
36
- ) -> List[str]:
37
- tests_with_missing_requirements: List[str] = []
37
+ ) -> list[str]:
38
+ tests_with_missing_requirements: list[str] = []
38
39
  if polarion_test_ids:
39
- from pylero.work_item import TestCase, Requirement
40
40
  from pylero.exceptions import PyleroLibException
41
+ from pylero.work_item import Requirement, TestCase
41
42
 
42
43
  for _id in polarion_test_ids:
43
44
  has_req = False
@@ -57,7 +58,7 @@ def validate_polarion_requirements(
57
58
  return tests_with_missing_requirements
58
59
 
59
60
 
60
- def find_polarion_ids(polarion_project_id: str, string_to_match: str, branch: str) -> List[str]:
61
+ def find_polarion_ids(polarion_project_id: str, string_to_match: str, branch: str) -> list[str]:
61
62
  return re.findall(
62
63
  rf"pytest.mark.polarion.*({polarion_project_id}-[0-9]+)",
63
64
  "\n".join(git_diff_lines(branch=branch).get(string_to_match, [])),
@@ -74,14 +75,14 @@ def get_polarion_project_id(util_name: str, config_file_path: str) -> str:
74
75
 
75
76
 
76
77
  def update_polarion_ids(
77
- project_id: str, is_automated: bool, polarion_ids: List[str], is_approved: bool = False
78
- ) -> Dict[str, List[str]]:
79
- updated_ids: Dict[str, List[str]] = {}
78
+ project_id: str, is_automated: bool, polarion_ids: list[str], is_approved: bool = False
79
+ ) -> dict[str, list[str]]:
80
+ updated_ids: dict[str, list[str]] = {}
80
81
  if polarion_ids:
81
82
  automation_status = AUTOMATED if is_automated else NOT_AUTOMATED
82
83
 
83
- from pylero.work_item import TestCase
84
84
  from pylero.exceptions import PyleroLibException
85
+ from pylero.work_item import TestCase
85
86
 
86
87
  for id in polarion_ids:
87
88
  try:
@@ -1,10 +1,11 @@
1
1
  import logging
2
- from simple_logger.logger import get_logger
3
2
  import os
4
- import click
5
3
  import sys
6
4
 
7
- from apps.polarion.polarion_utils import validate_polarion_requirements, find_polarion_ids, get_polarion_project_id
5
+ import click
6
+ from simple_logger.logger import get_logger
7
+
8
+ from apps.polarion.polarion_utils import find_polarion_ids, get_polarion_project_id, validate_polarion_requirements
8
9
 
9
10
  LOGGER = get_logger(name="polarion-verify-tc-requirements")
10
11
 
@@ -0,0 +1,148 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import logging
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ from concurrent.futures import Future, ThreadPoolExecutor, as_completed
9
+ from typing import Any, Iterable
10
+
11
+ import click
12
+ from simple_logger.logger import get_logger
13
+
14
+ from apps.utils import ListParamType, all_python_files, get_util_config
15
+
16
+ LOGGER = get_logger(name=__name__)
17
+
18
+
19
+ def is_fixture_autouse(func: ast.FunctionDef) -> bool:
20
+ deco_list: list[Any] = func.decorator_list
21
+ for deco in deco_list or []:
22
+ if not hasattr(deco, "func"):
23
+ continue
24
+
25
+ if getattr(deco.func, "attr", None) and getattr(deco.func, "value", None):
26
+ if deco.func.attr == "fixture" and deco.func.value.id == "pytest":
27
+ for _key in deco.keywords:
28
+ if _key.arg == "autouse":
29
+ return True
30
+ return False
31
+
32
+
33
+ def _iter_functions(tree: ast.Module) -> Iterable[ast.FunctionDef]:
34
+ """
35
+ Get all function from python file
36
+ """
37
+ for elm in tree.body:
38
+ if isinstance(elm, ast.FunctionDef):
39
+ if elm.name.startswith("test_"):
40
+ continue
41
+
42
+ yield elm
43
+
44
+
45
+ def is_ignore_function_list(ignore_prefix_list: list[str], function: ast.FunctionDef) -> bool:
46
+ ignore_function_lists = [
47
+ function.name for ignore_prefix in ignore_prefix_list if function.name.startswith(ignore_prefix)
48
+ ]
49
+ if ignore_function_lists:
50
+ return True
51
+
52
+ return False
53
+
54
+
55
+ def process_file(py_file: str, func_ignore_prefix: list[str], file_ignore_list: list[str]) -> str:
56
+ if os.path.basename(py_file) in file_ignore_list:
57
+ LOGGER.debug(f"Skipping file: {py_file}")
58
+ return ""
59
+
60
+ with open(py_file) as fd:
61
+ tree = ast.parse(source=fd.read())
62
+
63
+ for func in _iter_functions(tree=tree):
64
+ if func_ignore_prefix and is_ignore_function_list(ignore_prefix_list=func_ignore_prefix, function=func):
65
+ LOGGER.debug(f"Skipping function: {func.name}")
66
+ continue
67
+
68
+ if is_fixture_autouse(func=func):
69
+ LOGGER.debug(f"Skipping `autouse` fixture function: {func.name}")
70
+ continue
71
+
72
+ used = False
73
+ _func_grep_found = subprocess.check_output(["git", "grep", "-w", func.name], shell=False)
74
+
75
+ for entry in _func_grep_found.decode().splitlines():
76
+ _, _line = entry.split(":", 1)
77
+
78
+ if f"def {func.name}" in _line:
79
+ continue
80
+
81
+ if _line.strip().startswith("#"):
82
+ continue
83
+
84
+ if func.name in _line:
85
+ used = True
86
+ break
87
+
88
+ if not used:
89
+ return f"{os.path.relpath(py_file)}:{func.name}:{func.lineno}:{func.col_offset} Is not used anywhere in the code."
90
+
91
+ return ""
92
+
93
+
94
+ @click.command()
95
+ @click.option(
96
+ "--config-file-path",
97
+ help="Provide absolute path to the config file. Any CLI option(s) would override YAML file",
98
+ type=click.Path(),
99
+ default=os.path.expanduser("~/.config/python-utility-scripts/config.yaml"),
100
+ )
101
+ @click.option(
102
+ "--exclude-files",
103
+ help="Provide a comma-separated string or list of files to exclude",
104
+ type=ListParamType(),
105
+ )
106
+ @click.option(
107
+ "--exclude-function-prefixes",
108
+ help="Provide a comma-separated string or list of function prefixes to exclude",
109
+ type=ListParamType(),
110
+ )
111
+ @click.option("--verbose", "-v", default=False, is_flag=True)
112
+ def get_unused_functions(
113
+ config_file_path: str, exclude_files: list[str], exclude_function_prefixes: list[str], verbose: bool
114
+ ) -> None:
115
+ LOGGER.setLevel(logging.DEBUG if verbose else logging.INFO)
116
+
117
+ unused_functions: list[str] = []
118
+ unused_code_config = get_util_config(util_name="pyutils-unusedcode", config_file_path=config_file_path)
119
+ func_ignore_prefix = exclude_function_prefixes or unused_code_config.get("exclude_function_prefix", [])
120
+ file_ignore_list = exclude_files or unused_code_config.get("exclude_files", [])
121
+
122
+ jobs: list[Future] = []
123
+ if not os.path.exists(".git"):
124
+ LOGGER.error("Must be run from a git repository")
125
+ sys.exit(1)
126
+
127
+ with ThreadPoolExecutor() as executor:
128
+ for py_file in all_python_files():
129
+ jobs.append(
130
+ executor.submit(
131
+ process_file,
132
+ py_file=py_file,
133
+ func_ignore_prefix=func_ignore_prefix,
134
+ file_ignore_list=file_ignore_list,
135
+ )
136
+ )
137
+
138
+ for result in as_completed(jobs):
139
+ if unused_func := result.result():
140
+ unused_functions.append(unused_func)
141
+
142
+ if unused_functions:
143
+ click.echo("\n".join(unused_functions))
144
+ sys.exit(1)
145
+
146
+
147
+ if __name__ == "__main__":
148
+ get_unused_functions()
@@ -1,11 +1,12 @@
1
1
  from __future__ import annotations
2
+
3
+ import json
2
4
  import os
5
+ from typing import Any, Dict, Iterable, Optional
3
6
 
7
+ import click
4
8
  import yaml
5
9
  from simple_logger.logger import get_logger
6
- import json
7
- import click
8
- from typing import Any, Dict, Iterable, Optional
9
10
 
10
11
  LOGGER = get_logger(name=__name__)
11
12
 
@@ -13,7 +13,7 @@ show_contexts = true
13
13
  show_error_codes = true
14
14
  warn_unused_ignores = true
15
15
  check_untyped_defs = true
16
- disallow_any_generics = true
16
+ disallow_any_generics = false
17
17
  disallow_incomplete_defs = true
18
18
  disallow_untyped_defs = true
19
19
  no_implicit_optional = true
@@ -23,13 +23,14 @@ preview = true
23
23
  line-length = 120
24
24
  fix = true
25
25
  output-format = "grouped"
26
+ lint.extend-select = ["I"]
26
27
 
27
28
  [tool.ruff.format]
28
29
  exclude = [".git", ".venv", ".mypy_cache", ".tox", "__pycache__"]
29
30
 
30
31
  [tool.poetry]
31
32
  name = "python-utility-scripts"
32
- version = "1.0.4"
33
+ version = "1.0.5"
33
34
  description = "Python utility scripts"
34
35
  authors = ["dbasunag <dbasunag@redhat.com>"]
35
36
  license = "Apache License 2.0"
@@ -1,110 +0,0 @@
1
- import ast
2
- import logging
3
- import os
4
- import subprocess
5
- import sys
6
-
7
- import click
8
- from simple_logger.logger import get_logger
9
-
10
- from apps.utils import all_python_files, ListParamType, get_util_config
11
- from typing import Any, Iterable, List
12
-
13
- LOGGER = get_logger(name=__name__)
14
-
15
-
16
- def is_fixture_autouse(func: ast.FunctionDef) -> bool:
17
- deco_list: List[Any] = func.decorator_list
18
- for deco in deco_list or []:
19
- if not hasattr(deco, "func"):
20
- continue
21
-
22
- if getattr(deco.func, "attr", None) and getattr(deco.func, "value", None):
23
- if deco.func.attr == "fixture" and deco.func.value.id == "pytest":
24
- for _key in deco.keywords:
25
- if _key.arg == "autouse":
26
- return True
27
- return False
28
-
29
-
30
- def _iter_functions(tree: ast.Module) -> Iterable[ast.FunctionDef]:
31
- """
32
- Get all function from python file
33
- """
34
- for elm in tree.body:
35
- if isinstance(elm, ast.FunctionDef):
36
- if elm.name.startswith("test_"):
37
- continue
38
-
39
- yield elm
40
-
41
-
42
- def is_ignore_function_list(ignore_prefix_list: List[str], function: ast.FunctionDef) -> bool:
43
- ignore_function_lists = [
44
- function.name for ignore_prefix in ignore_prefix_list if function.name.startswith(ignore_prefix)
45
- ]
46
- if ignore_function_lists:
47
- LOGGER.debug(f"Following functions are getting skipped: {ignore_function_lists}")
48
- return True
49
-
50
- return False
51
-
52
-
53
- @click.command()
54
- @click.option(
55
- "--config-file-path",
56
- help="Provide absolute path to the config file. Any CLI option(s) would override YAML file",
57
- type=click.Path(),
58
- default=os.path.expanduser("~/.config/python-utility-scripts/config.yaml"),
59
- )
60
- @click.option(
61
- "--exclude-files",
62
- help="Provide a comma-separated string or list of files to exclude",
63
- type=ListParamType(),
64
- )
65
- @click.option(
66
- "--exclude-function-prefixes",
67
- help="Provide a comma-separated string or list of function prefixes to exclude",
68
- type=ListParamType(),
69
- )
70
- @click.option("--verbose", default=False, is_flag=True)
71
- def get_unused_functions(
72
- config_file_path: Any, exclude_files: Any, exclude_function_prefixes: Any, verbose: bool
73
- ) -> Any:
74
- LOGGER.setLevel(logging.DEBUG if verbose else logging.INFO)
75
-
76
- _unused_functions = []
77
- unused_code_config = get_util_config(util_name="pyutils-unusedcode", config_file_path=config_file_path)
78
- func_ignore_prefix = exclude_function_prefixes or unused_code_config.get("exclude_function_prefix", [])
79
- file_ignore_list = exclude_files or unused_code_config.get("exclude_files", [])
80
-
81
- for py_file in all_python_files():
82
- if os.path.basename(py_file) in file_ignore_list:
83
- continue
84
- with open(py_file) as fd:
85
- tree = ast.parse(source=fd.read())
86
-
87
- for func in _iter_functions(tree=tree):
88
- if func_ignore_prefix and is_ignore_function_list(ignore_prefix_list=func_ignore_prefix, function=func):
89
- continue
90
-
91
- if is_fixture_autouse(func=func):
92
- continue
93
-
94
- _used = subprocess.check_output(
95
- f"git grep -w '{func.name}' | wc -l",
96
- shell=True,
97
- )
98
- used = int(_used.strip())
99
- if used < 2:
100
- _unused_functions.append(
101
- f"{os.path.relpath(py_file)}:{func.name}:{func.lineno}:{func.col_offset} Is"
102
- " not used anywhere in the code.",
103
- )
104
- if _unused_functions:
105
- click.echo("\n".join(_unused_functions))
106
- sys.exit(1)
107
-
108
-
109
- if __name__ == "__main__":
110
- get_unused_functions()