Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

breaking_changes_detection.py 9.4 KB

You have to be logged in to leave a comment. Sign In
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
  1. import ast
  2. from abc import ABC
  3. from pathlib import Path
  4. from typing import List, Dict, Union
  5. from termcolor import colored
  6. from dataclasses import dataclass, field, asdict
  7. from .code_parser import parse_functions_signatures, parse_imports
  8. MODULE_PATH_COLOR = "yellow"
  9. SOURCE_CODE_COLOR = "blue"
  10. BREAKING_OBJECT_COLOR = "red"
  11. @dataclass
  12. class AbstractBreakingChange(ABC):
  13. line_num: int
  14. @property
  15. def description(self) -> str:
  16. raise NotImplementedError()
  17. @property
  18. def breaking_type_name(self) -> str:
  19. raise NotImplementedError()
  20. @dataclass
  21. class ClassRemoved(AbstractBreakingChange):
  22. class_name: str
  23. line_num: int
  24. @property
  25. def description(self) -> str:
  26. return f"{colored(self.class_name, SOURCE_CODE_COLOR)} -> {colored('X', BREAKING_OBJECT_COLOR)}"
  27. @property
  28. def breaking_type_name(self) -> str:
  29. return "CLASS REMOVED"
  30. @dataclass
  31. class ImportRemoved(AbstractBreakingChange):
  32. import_name: str
  33. line_num: int
  34. @property
  35. def description(self) -> str:
  36. return f"{colored(self.import_name, SOURCE_CODE_COLOR)} -> {colored('X', BREAKING_OBJECT_COLOR)}"
  37. @property
  38. def breaking_type_name(self) -> str:
  39. return "IMPORT REMOVED"
  40. @dataclass
  41. class FunctionRemoved(AbstractBreakingChange):
  42. function_name: str
  43. line_num: int
  44. @property
  45. def description(self) -> str:
  46. return f"{colored(self.function_name, SOURCE_CODE_COLOR)} -> {colored('X', BREAKING_OBJECT_COLOR)}"
  47. @property
  48. def breaking_type_name(self) -> str:
  49. return "FUNCTION REMOVED"
  50. @dataclass
  51. class ParameterRemoved(AbstractBreakingChange):
  52. parameter_name: str
  53. function_name: str
  54. line_num: int
  55. @property
  56. def description(self) -> str:
  57. source_fn_colored = colored(self.function_name, SOURCE_CODE_COLOR)
  58. current_fn_colored = colored(self.function_name, "yellow")
  59. param_colored = colored(self.parameter_name, BREAKING_OBJECT_COLOR)
  60. return f"{source_fn_colored}(..., {param_colored}) -> {current_fn_colored}(...)"
  61. @property
  62. def breaking_type_name(self) -> str:
  63. return "FUNCTION PARAMETER REMOVED"
  64. @dataclass
  65. class RequiredParameterAdded(AbstractBreakingChange):
  66. parameter_name: str
  67. function_name: str
  68. line_num: int
  69. @property
  70. def description(self) -> str:
  71. source_fn_colored = colored(self.function_name, SOURCE_CODE_COLOR)
  72. current_fn_colored = colored(self.function_name, "yellow")
  73. param_colored = colored(self.parameter_name, BREAKING_OBJECT_COLOR)
  74. return f"{source_fn_colored}(...) -> {current_fn_colored}(..., {param_colored})"
  75. @property
  76. def breaking_type_name(self) -> str:
  77. return "FUNCTION PARAMETER ADDED"
  78. @dataclass
  79. class BreakingChanges:
  80. module_path: str
  81. classes_removed: List[ClassRemoved] = field(default_factory=list)
  82. imports_removed: List[ImportRemoved] = field(default_factory=list)
  83. functions_removed: List[FunctionRemoved] = field(default_factory=list)
  84. params_removed: List[ParameterRemoved] = field(default_factory=list)
  85. required_params_added: List[RequiredParameterAdded] = field(default_factory=list)
  86. def __str__(self) -> str:
  87. summary = ""
  88. module_path_colored = colored(self.module_path, MODULE_PATH_COLOR)
  89. breaking_changes: List[AbstractBreakingChange] = (
  90. self.classes_removed + self.imports_removed + self.functions_removed + self.params_removed + self.required_params_added
  91. )
  92. for breaking_change in breaking_changes:
  93. summary += "{:<70} {:<8} {:<30} {}\n".format(
  94. module_path_colored, breaking_change.line_num, breaking_change.breaking_type_name, breaking_change.description
  95. )
  96. return summary
  97. def json(self) -> Dict[str, List[str]]:
  98. return asdict(self)
  99. @property
  100. def is_empty(self) -> bool:
  101. return len(self.classes_removed + self.imports_removed + self.functions_removed + self.params_removed + self.required_params_added) == 0
  102. def extract_code_breaking_changes(module_path: str, source_code: str, current_code: str) -> BreakingChanges:
  103. """Compares two versions of code to identify breaking changes.
  104. :param module_path: The path to the module being compared.
  105. :param source_code: The source version of the code.
  106. :param current_code: The modified version of the code.
  107. :return: A BreakingChanges object detailing the differences.
  108. """
  109. breaking_changes = BreakingChanges(module_path=module_path)
  110. source_classes = {node.name: node for node in ast.walk(ast.parse(source_code)) if isinstance(node, ast.ClassDef)}
  111. current_classes = {node.name: node for node in ast.walk(ast.parse(current_code)) if isinstance(node, ast.ClassDef)}
  112. # ClassRemoved
  113. for class_name, source_class in source_classes.items():
  114. if class_name not in current_classes:
  115. breaking_changes.classes_removed.append(
  116. ClassRemoved(
  117. class_name=class_name,
  118. line_num=source_class.lineno,
  119. )
  120. )
  121. # IMPORTS - Check import ONLY if __init__ file and ignores non-SG imports.
  122. current_imports = parse_imports(code=current_code)
  123. if module_path.endswith("__init__.py"):
  124. source_imports = parse_imports(code=source_code)
  125. breaking_changes.imports_removed = [
  126. ImportRemoved(import_name=source_import, line_num=0)
  127. for source_import in source_imports
  128. if (source_import not in current_imports) and ("super_gradients" in source_import)
  129. ]
  130. # FUNCTION SIGNATURES
  131. source_functions_signatures = parse_functions_signatures(source_code)
  132. current_functions_signatures = parse_functions_signatures(current_code)
  133. for function_name, source_function_signature in source_functions_signatures.items():
  134. if function_name in current_functions_signatures:
  135. current_function_signature = current_functions_signatures[function_name]
  136. # ParameterRemoved
  137. for source_param in source_function_signature.params.all:
  138. if source_param not in current_function_signature.params.all:
  139. breaking_changes.params_removed.append(
  140. ParameterRemoved(
  141. function_name=function_name,
  142. parameter_name=source_param,
  143. line_num=current_function_signature.line_num,
  144. )
  145. )
  146. # RequiredParameterAdded
  147. for current_param in current_function_signature.params.required:
  148. if current_param not in source_function_signature.params.required:
  149. breaking_changes.required_params_added.append(
  150. RequiredParameterAdded(
  151. function_name=function_name,
  152. parameter_name=current_param,
  153. line_num=current_function_signature.line_num,
  154. )
  155. )
  156. else:
  157. # Count a function as removed only if it was removed AND it was not added in the imports!
  158. imported_function_names = current_imports.values()
  159. if function_name not in imported_function_names:
  160. breaking_changes.functions_removed.append(
  161. FunctionRemoved(
  162. function_name=function_name,
  163. line_num=source_function_signature.line_num,
  164. )
  165. )
  166. return breaking_changes
  167. def analyze_breaking_changes(verbose: bool = 1, source_branch: str = "master") -> List[Dict[str, Union[str, List]]]:
  168. """Analyze changes between the current branch (HEAD) and the master branch.
  169. :param verbose: If True, print the summary of breaking changes in a nicely formatted way
  170. :param source_branch: The branch source branch, to which we will compare the HEAD.
  171. :return: List of changes, where each change is a dictionary listing each type of change for each module.
  172. """
  173. print("\n" + "=" * 50)
  174. print(f"Analyzing breaking changes, comparing `HEAD` to `{source_branch}`...")
  175. # GitHelper requires `git` library which should NOT be required for the other functions
  176. from .git_utils import GitHelper
  177. root_dir = str(Path(__file__).resolve().parents[2])
  178. git_explorer = GitHelper(git_path=root_dir)
  179. changed_sg_modules = [
  180. module_path
  181. for module_path in git_explorer.diff_files(source_branch=source_branch, current_branch="HEAD")
  182. if module_path.startswith("src/super_gradients/") and not module_path.startswith("src/super_gradients/examples/")
  183. ]
  184. summary = ""
  185. breaking_changes_list = []
  186. for module_path in changed_sg_modules:
  187. master_code = git_explorer.load_branch_file(branch=source_branch, file_path=module_path)
  188. head_code = git_explorer.load_branch_file(branch="HEAD", file_path=module_path)
  189. breaking_changes = extract_code_breaking_changes(module_path=module_path, source_code=master_code, current_code=head_code)
  190. if not breaking_changes.is_empty:
  191. breaking_changes_list.append(breaking_changes.json())
  192. summary += str(breaking_changes)
  193. if verbose:
  194. if summary:
  195. print("{:<60} {:<8} {:<30} {}\n".format("MODULE", "LINE NO", "BREAKING TYPE", "DESCRIPTION (Master -> HEAD)"))
  196. print("-" * 175 + "\n")
  197. print(summary)
  198. else:
  199. print(colored("NO BREAKING CHANGE DETECTED!", "green"))
  200. return breaking_changes_list
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...