Debian Codegraph @

packages/griffelib/src/griffe/_internal/diff.py

raw symbols SCIP
1 # This module exports "breaking changes" related utilities.
2 # The logic here is to iterate on objects and their members recursively,
3 # to yield found breaking changes.
4 #
5 # The breakage class definitions might sound a bit verbose,
6 # but declaring them this way helps with (de)serialization,
7 # which we don't use yet, but could use in the future.
8
9 from __future__ import annotations
10
11 import contextlib
12 from pathlib import Path
13 from typing import TYPE_CHECKING, Any
14
15 from griffe._internal.enumerations import BreakageKind, ExplanationStyle, ParameterKind
16 from griffe._internal.exceptions import AliasResolutionError
17 from griffe._internal.git import _WORKTREE_PREFIX
18 from griffe._internal.logger import logger
19
20 if TYPE_CHECKING:
21 from collections.abc import Iterable, Iterator
22
23 from griffe._internal.models import Alias, Attribute, Class, Function, Object
24
25 _POSITIONAL = frozenset((ParameterKind.positional_only, ParameterKind.positional_or_keyword))
26 _KEYWORD = frozenset((ParameterKind.keyword_only, ParameterKind.positional_or_keyword))
27 _POSITIONAL_KEYWORD_ONLY = frozenset((ParameterKind.positional_only, ParameterKind.keyword_only))
28 _VARIADIC = frozenset((ParameterKind.var_positional, ParameterKind.var_keyword))
29
30
31 # Colors for terminal output.
32 class _ANSI:
33 FG_BLACK = "\033[30m"
34 FG_RED = "\033[31m"
35 FG_GREEN = "\033[32m"
36 FG_YELLOW = "\033[33m"
37 FG_BLUE = "\033[34m"
38 FG_MAGENTA = "\033[35m"
39 FG_CYAN = "\033[36m"
40 FG_WHITE = "\033[37m"
41 FG_RESET = "\033[39m"
42 FG_LIGHTBLACK_EX = "\033[90m"
43 FG_LIGHTRED_EX = "\033[91m"
44 FG_LIGHTGREEN_EX = "\033[92m"
45 FG_LIGHTYELLOW_EX = "\033[93m"
46 FG_LIGHTBLUE_EX = "\033[94m"
47 FG_LIGHTMAGENTA_EX = "\033[95m"
48 FG_LIGHTCYAN_EX = "\033[96m"
49 FG_LIGHTWHITE_EX = "\033[97m"
50 BG_BLACK = "\033[40m"
51 BG_RED = "\033[41m"
52 BG_GREEN = "\033[42m"
53 BG_YELLOW = "\033[43m"
54 BG_BLUE = "\033[44m"
55 BG_MAGENTA = "\033[45m"
56 BG_CYAN = "\033[46m"
57 BG_WHITE = "\033[47m"
58 BG_RESET = "\033[49m"
59 BG_LIGHTBLACK_EX = "\033[100m"
60 BG_LIGHTRED_EX = "\033[101m"
61 BG_LIGHTGREEN_EX = "\033[102m"
62 BG_LIGHTYELLOW_EX = "\033[103m"
63 BG_LIGHTBLUE_EX = "\033[104m"
64 BG_LIGHTMAGENTA_EX = "\033[105m"
65 BG_LIGHTCYAN_EX = "\033[106m"
66 BG_LIGHTWHITE_EX = "\033[107m"
67 BRIGHT = "\033[1m"
68 DIM = "\033[2m"
69 NORMAL = "\033[22m"
70 RESET_ALL = "\033[0m"
71
72
73 class Breakage:
74 """Breakages can explain what broke from a version to another."""
75
76 kind: BreakageKind
77 """The kind of breakage."""
78
79 def __init__(self, obj: Object, old_value: Any, new_value: Any, details: str = "") -> None:
80 """Initialize the breakage.
81
82 Parameters:
83 obj: The object related to the breakage.
84 old_value: The old value.
85 new_value: The new, incompatible value.
86 details: Some details about the breakage.
87 """
88 self.obj = obj
89 """The object related to the breakage."""
90 self.old_value = old_value
91 """The old value."""
92 self.new_value = new_value
93 """The new, incompatible value."""
94 self.details = details
95 """Some details about the breakage."""
96
97 def __str__(self) -> str:
98 return self.kind.value
99
100 def __repr__(self) -> str:
101 return self.kind.name
102
103 def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]: # noqa: ARG002
104 """Return this object's data as a dictionary.
105
106 Parameters:
107 full: Whether to return full info, or just base info.
108 **kwargs: Additional serialization options.
109
110 Returns:
111 A dictionary.
112 """
113 return {
114 "kind": self.kind,
115 "object_path": self.obj.path,
116 "old_value": self.old_value,
117 "new_value": self.new_value,
118 }
119
120 def explain(self, style: ExplanationStyle = ExplanationStyle.ONE_LINE) -> str:
121 """Explain the breakage by showing old and new value.
122
123 Parameters:
124 style: The explanation style to use.
125
126 Returns:
127 An explanation.
128 """
129 return getattr(self, f"_explain_{style.value}")()
130
131 @property
132 def _filepath(self) -> Path:
133 if self.obj.is_alias:
134 return self.obj.parent.filepath # ty:ignore[invalid-return-type, unresolved-attribute]
135 return self.obj.filepath # ty:ignore[invalid-return-type]
136
137 @property
138 def _relative_filepath(self) -> Path:
139 if self.obj.is_alias:
140 return self.obj.parent.relative_filepath # ty:ignore[unresolved-attribute]
141 return self.obj.relative_filepath
142
143 @property
144 def _relative_package_filepath(self) -> Path:
145 if self.obj.is_alias:
146 return self.obj.parent.relative_package_filepath # ty:ignore[unresolved-attribute]
147 return self.obj.relative_package_filepath
148
149 @property
150 def _location(self) -> Path:
151 # Absolute file path probably means temporary worktree.
152 # We use our worktree prefix to remove some components
153 # of the path on the left (`/tmp/griffe-worktree-*/griffe_*/repo`).
154 if self._relative_filepath.is_absolute():
155 parts = self._relative_filepath.parts
156 for index, part in enumerate(parts):
157 if part.startswith(_WORKTREE_PREFIX):
158 return Path(*parts[index + 2 :])
159 return self._relative_filepath
160
161 @property
162 def _canonical_path(self) -> str:
163 if self.obj.is_alias:
164 return self.obj.path
165 return self.obj.canonical_path
166
167 @property
168 def _module_path(self) -> str:
169 if self.obj.is_alias:
170 return self.obj.parent.module.path # ty:ignore[unresolved-attribute]
171 return self.obj.module.path
172
173 @property
174 def _relative_path(self) -> str:
175 return self._canonical_path[len(self._module_path) + 1 :] or "<module>"
176
177 @property
178 def _lineno(self) -> int:
179 # If the object was removed, and we are able to get the location (file path)
180 # as a relative path, then we use 0 instead of the original line number
181 # (it helps when checking current sources, and avoids pointing to now missing contents).
182 if self.kind is BreakageKind.OBJECT_REMOVED and self._relative_filepath != self._location:
183 return 0
184 if self.obj.is_alias:
185 return self.obj.alias_lineno or 0 # ty:ignore[unresolved-attribute]
186 return self.obj.lineno or 0
187
188 def _format_location(self, *, colors: bool = True) -> str:
189 bright = _ANSI.BRIGHT if colors else ""
190 reset = _ANSI.RESET_ALL if colors else ""
191 return f"{bright}{self._location}{reset}:{self._lineno}"
192
193 def _format_title(self, *, colors: bool = True) -> str: # noqa: ARG002
194 return self._relative_path
195
196 def _format_kind(self, *, colors: bool = True) -> str:
197 yellow = _ANSI.FG_YELLOW if colors else ""
198 reset = _ANSI.FG_RESET if colors else ""
199 return f"{yellow}{self.kind.value}{reset}"
200
201 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
202 return str(self.old_value)
203
204 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
205 return str(self.new_value)
206
207 def _explain_oneline(self) -> str:
208 explanation = f"{self._format_location()}: {self._format_title()}: {self._format_kind()}"
209 old = self._format_old_value()
210 new = self._format_new_value()
211 if old and new:
212 change = f"{old} -> {new}"
213 elif old:
214 change = old
215 elif new:
216 change = new
217 else:
218 change = ""
219 if change:
220 return f"{explanation}: {change}"
221 return explanation
222
223 def _explain_verbose(self) -> str:
224 lines = [f"{self._format_location()}: {self._format_title()}:"]
225 kind = self._format_kind()
226 old = self._format_old_value()
227 new = self._format_new_value()
228 if old or new:
229 lines.append(f"{kind}:")
230 else:
231 lines.append(kind)
232 if old:
233 lines.append(f" Old: {old}")
234 if new:
235 lines.append(f" New: {new}")
236 if self.details:
237 lines.append(f" Details: {self.details}")
238 lines.append("")
239 return "\n".join(lines)
240
241 def _explain_markdown(self) -> str:
242 explanation = f"- `{self._relative_path}`: *{self.kind.value}*"
243 old = self._format_old_value(colors=False)
244 if old and old != "unset":
245 old = f"`{old}`"
246 new = self._format_new_value(colors=False)
247 if new and new != "unset":
248 new = f"`{new}`"
249 if old and new:
250 change = f"{old} -> {new}"
251 elif old:
252 change = old
253 elif new:
254 change = new
255 else:
256 change = ""
257 if change:
258 return f"{explanation}: {change}"
259 return explanation
260
261 def _explain_github(self) -> str:
262 location = f"file={self._location},line={self._lineno}"
263 title = f"title={self._format_title(colors=False)}"
264 explanation = f"::warning {location},{title}::{self.kind.value}"
265 old = self._format_old_value(colors=False)
266 if old and old != "unset":
267 old = f"`{old}`"
268 new = self._format_new_value(colors=False)
269 if new and new != "unset":
270 new = f"`{new}`"
271 if old and new:
272 change = f"{old} -> {new}"
273 elif old:
274 change = old
275 elif new:
276 change = new
277 else:
278 change = ""
279 if change:
280 return f"{explanation}: {change}"
281 return explanation
282
283 def _explain_azdo(self) -> str:
284 location = f"sourcepath={self._location},linenumber={self._lineno}"
285 title = f"title={self._format_title(colors=False)}"
286 explanation = f"###vso[task.logissue type=warning;{location},{title}]{self.kind.value}"
287 old = self._format_old_value(colors=False)
288 if old and old != "unset":
289 old = f"`{old}`"
290 new = self._format_new_value(colors=False)
291 if new and new != "unset":
292 new = f"`{new}`"
293 if old and new:
294 change = f"{old} -> {new}"
295 elif old:
296 change = old
297 elif new:
298 change = new
299 else:
300 change = ""
301 if change:
302 return f"{explanation}: {change}"
303 return explanation
304
305
306 class ParameterMovedBreakage(Breakage):
307 """Specific breakage class for moved parameters."""
308
309 kind: BreakageKind = BreakageKind.PARAMETER_MOVED
310
311 @property
312 def _relative_path(self) -> str:
313 return f"{super()._relative_path}({self.old_value.name})"
314
315 def _format_title(self, *, colors: bool = True) -> str:
316 blue = _ANSI.FG_BLUE if colors else ""
317 reset = _ANSI.FG_RESET if colors else ""
318 return f"{super()._relative_path}({blue}{self.old_value.name}{reset})"
319
320 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
321 return ""
322
323 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
324 return ""
325
326
327 class ParameterRemovedBreakage(Breakage):
328 """Specific breakage class for removed parameters."""
329
330 kind: BreakageKind = BreakageKind.PARAMETER_REMOVED
331
332 @property
333 def _relative_path(self) -> str:
334 return f"{super()._relative_path}({self.old_value.name})"
335
336 def _format_title(self, *, colors: bool = True) -> str:
337 blue = _ANSI.FG_BLUE if colors else ""
338 reset = _ANSI.FG_RESET if colors else ""
339 return f"{super()._relative_path}({blue}{self.old_value.name}{reset})"
340
341 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
342 return ""
343
344 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
345 return ""
346
347
348 class ParameterChangedKindBreakage(Breakage):
349 """Specific breakage class for parameters whose kind changed."""
350
351 kind: BreakageKind = BreakageKind.PARAMETER_CHANGED_KIND
352
353 @property
354 def _relative_path(self) -> str:
355 return f"{super()._relative_path}({self.old_value.name})"
356
357 def _format_title(self, *, colors: bool = True) -> str:
358 blue = _ANSI.FG_BLUE if colors else ""
359 reset = _ANSI.FG_RESET if colors else ""
360 return f"{super()._relative_path}({blue}{self.old_value.name}{reset})"
361
362 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
363 return str(self.old_value.kind.value)
364
365 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
366 return str(self.new_value.kind.value)
367
368
369 class ParameterChangedDefaultBreakage(Breakage):
370 """Specific breakage class for parameters whose default value changed."""
371
372 kind: BreakageKind = BreakageKind.PARAMETER_CHANGED_DEFAULT
373
374 @property
375 def _relative_path(self) -> str:
376 return f"{super()._relative_path}({self.old_value.name})"
377
378 def _format_title(self, *, colors: bool = True) -> str:
379 blue = _ANSI.FG_BLUE if colors else ""
380 reset = _ANSI.FG_RESET if colors else ""
381 return f"{super()._relative_path}({blue}{self.old_value.name}{reset})"
382
383 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
384 return str(self.old_value.default)
385
386 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
387 return str(self.new_value.default)
388
389
390 class ParameterChangedRequiredBreakage(Breakage):
391 """Specific breakage class for parameters which became required."""
392
393 kind: BreakageKind = BreakageKind.PARAMETER_CHANGED_REQUIRED
394
395 @property
396 def _relative_path(self) -> str:
397 return f"{super()._relative_path}({self.old_value.name})"
398
399 def _format_title(self, *, colors: bool = True) -> str:
400 blue = _ANSI.FG_BLUE if colors else ""
401 reset = _ANSI.FG_RESET if colors else ""
402 return f"{super()._relative_path}({blue}{self.old_value.name}{reset})"
403
404 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
405 return ""
406
407 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
408 return ""
409
410
411 class ParameterAddedRequiredBreakage(Breakage):
412 """Specific breakage class for new parameters added as required."""
413
414 kind: BreakageKind = BreakageKind.PARAMETER_ADDED_REQUIRED
415
416 @property
417 def _relative_path(self) -> str:
418 return f"{super()._relative_path}({self.new_value.name})"
419
420 def _format_title(self, *, colors: bool = True) -> str:
421 blue = _ANSI.FG_BLUE if colors else ""
422 reset = _ANSI.FG_RESET if colors else ""
423 return f"{super()._relative_path}({blue}{self.new_value.name}{reset})"
424
425 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
426 return ""
427
428 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
429 return ""
430
431
432 class ReturnChangedTypeBreakage(Breakage):
433 """Specific breakage class for return values which changed type."""
434
435 kind: BreakageKind = BreakageKind.RETURN_CHANGED_TYPE
436
437
438 class ObjectRemovedBreakage(Breakage):
439 """Specific breakage class for removed objects."""
440
441 kind: BreakageKind = BreakageKind.OBJECT_REMOVED
442
443 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
444 return ""
445
446 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
447 return ""
448
449
450 class ObjectChangedKindBreakage(Breakage):
451 """Specific breakage class for objects whose kind changed."""
452
453 kind: BreakageKind = BreakageKind.OBJECT_CHANGED_KIND
454
455 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
456 return self.old_value.value
457
458 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
459 return self.new_value.value
460
461
462 class AttributeChangedTypeBreakage(Breakage):
463 """Specific breakage class for attributes whose type changed."""
464
465 kind: BreakageKind = BreakageKind.ATTRIBUTE_CHANGED_TYPE
466
467
468 class AttributeChangedValueBreakage(Breakage):
469 """Specific breakage class for attributes whose value changed."""
470
471 kind: BreakageKind = BreakageKind.ATTRIBUTE_CHANGED_VALUE
472
473
474 class ClassRemovedBaseBreakage(Breakage):
475 """Specific breakage class for removed base classes."""
476
477 kind: BreakageKind = BreakageKind.CLASS_REMOVED_BASE
478
479 def _format_old_value(self, *, colors: bool = True) -> str: # noqa: ARG002
480 return "[" + ", ".join(base.canonical_path for base in self.old_value) + "]"
481
482 def _format_new_value(self, *, colors: bool = True) -> str: # noqa: ARG002
483 return "[" + ", ".join(base.canonical_path for base in self.new_value) + "]"
484
485
486 # TODO: Check decorators? Maybe resolved by extensions and/or dynamic analysis.
487 def _class_incompatibilities(
488 old_class: Class,
489 new_class: Class,
490 *,
491 seen_paths: set[str],
492 ) -> Iterable[Breakage]:
493 yield from ()
494 if new_class.bases != old_class.bases and len(new_class.bases) < len(old_class.bases):
495 yield ClassRemovedBaseBreakage(new_class, old_class.bases, new_class.bases)
496 yield from _member_incompatibilities(old_class, new_class, seen_paths=seen_paths)
497
498
499 # TODO: Check decorators? Maybe resolved by extensions and/or dynamic analysis.
500 def _function_incompatibilities(old_function: Function, new_function: Function) -> Iterator[Breakage]:
501 new_param_names = [param.name for param in new_function.parameters]
502 param_kinds = {param.kind for param in new_function.parameters}
503 has_variadic_args = ParameterKind.var_positional in param_kinds
504 has_variadic_kwargs = ParameterKind.var_keyword in param_kinds
505
506 for old_index, old_param in enumerate(old_function.parameters):
507 # Check if the parameter was removed.
508 if old_param.name not in new_function.parameters:
509 swallowed = (
510 (old_param.kind is ParameterKind.keyword_only and has_variadic_kwargs)
511 or (old_param.kind is ParameterKind.positional_only and has_variadic_args)
512 or (old_param.kind is ParameterKind.positional_or_keyword and has_variadic_args and has_variadic_kwargs)
513 )
514 if not swallowed:
515 yield ParameterRemovedBreakage(new_function, old_param, None)
516 continue
517
518 # Check if the parameter became required.
519 new_param = new_function.parameters[old_param.name]
520 if new_param.required and not old_param.required:
521 yield ParameterChangedRequiredBreakage(new_function, old_param, new_param)
522
523 # Check if the parameter was moved.
524 if old_param.kind in _POSITIONAL and new_param.kind in _POSITIONAL:
525 new_index = new_param_names.index(old_param.name)
526 if new_index != old_index:
527 details = f"position: from {old_index} to {new_index} ({new_index - old_index:+})"
528 yield ParameterMovedBreakage(new_function, old_param, new_param, details=details)
529
530 # Check if the parameter changed kind.
531 if old_param.kind is not new_param.kind:
532 incompatible_kind = any(
533 (
534 # Positional-only to keyword-only.
535 old_param.kind is ParameterKind.positional_only and new_param.kind is ParameterKind.keyword_only,
536 # Keyword-only to positional-only.
537 old_param.kind is ParameterKind.keyword_only and new_param.kind is ParameterKind.positional_only,
538 # Positional or keyword to positional-only/keyword-only.
539 old_param.kind is ParameterKind.positional_or_keyword
540 and new_param.kind in _POSITIONAL_KEYWORD_ONLY,
541 # Not keyword-only to variadic keyword, without variadic positional.
542 new_param.kind is ParameterKind.var_keyword
543 and old_param.kind is not ParameterKind.keyword_only
544 and not has_variadic_args,
545 # Not positional-only to variadic positional, without variadic keyword.
546 new_param.kind is ParameterKind.var_positional
547 and old_param.kind is not ParameterKind.positional_only
548 and not has_variadic_kwargs,
549 ),
550 )
551 if incompatible_kind:
552 yield ParameterChangedKindBreakage(new_function, old_param, new_param)
553
554 # Check if the parameter changed default.
555 breakage = ParameterChangedDefaultBreakage(new_function, old_param, new_param)
556 non_required = not old_param.required and not new_param.required
557 non_variadic = old_param.kind not in _VARIADIC and new_param.kind not in _VARIADIC
558 if non_required and non_variadic:
559 try:
560 if old_param.default != new_param.default:
561 yield breakage
562 except Exception: # noqa: BLE001 (equality checks sometimes fail, e.g. numpy arrays)
563 # NOTE: Emitting breakage on a failed comparison could be a preference.
564 yield breakage
565
566 # Check if required parameters were added.
567 for new_param in new_function.parameters:
568 if new_param.name not in old_function.parameters and new_param.required:
569 yield ParameterAddedRequiredBreakage(new_function, None, new_param)
570
571 if not _returns_are_compatible(old_function, new_function):
572 yield ReturnChangedTypeBreakage(new_function, old_function.returns, new_function.returns)
573
574
575 def _attribute_incompatibilities(old_attribute: Attribute, new_attribute: Attribute) -> Iterable[Breakage]:
576 # TODO: Support annotation breaking changes.
577 if old_attribute.value != new_attribute.value:
578 if new_attribute.value is None:
579 yield AttributeChangedValueBreakage(new_attribute, old_attribute.value, "unset")
580 else:
581 yield AttributeChangedValueBreakage(new_attribute, old_attribute.value, new_attribute.value)
582
583
584 def _alias_incompatibilities(
585 old_obj: Object | Alias,
586 new_obj: Object | Alias,
587 *,
588 seen_paths: set[str],
589 ) -> Iterable[Breakage]:
590 try:
591 old_member = old_obj.target if old_obj.is_alias else old_obj # ty:ignore[unresolved-attribute]
592 new_member = new_obj.target if new_obj.is_alias else new_obj # ty:ignore[unresolved-attribute]
593 except AliasResolutionError:
594 logger.debug("API check: %s | %s: skip alias with unknown target", old_obj.path, new_obj.path)
595 return
596
597 yield from _type_based_yield(old_member, new_member, seen_paths=seen_paths)
598
599
600 def _member_incompatibilities(
601 old_obj: Object | Alias,
602 new_obj: Object | Alias,
603 *,
604 seen_paths: set[str] | None = None,
605 ) -> Iterator[Breakage]:
606 seen_paths = set() if seen_paths is None else seen_paths
607 for name, old_member in old_obj.all_members.items():
608 if not old_member.is_public:
609 logger.debug("API check: %s.%s: skip non-public object", old_obj.path, name)
610 continue
611 logger.debug("API check: %s.%s", old_obj.path, name)
612 try:
613 new_member = new_obj.all_members[name]
614 except KeyError:
615 if (not old_member.is_alias and old_member.is_module) or old_member.is_public:
616 yield ObjectRemovedBreakage(old_member, old_member, None) # ty:ignore[invalid-argument-type]
617 else:
618 yield from _type_based_yield(old_member, new_member, seen_paths=seen_paths)
619
620
621 def _type_based_yield(
622 old_member: Object | Alias,
623 new_member: Object | Alias,
624 *,
625 seen_paths: set[str],
626 ) -> Iterator[Breakage]:
627 if old_member.path in seen_paths:
628 return
629 seen_paths.add(old_member.path)
630 if old_member.is_alias or new_member.is_alias:
631 # Should be first, since there can be the case where there is an alias and another kind of object,
632 # which may not be a breaking change.
633 yield from _alias_incompatibilities(
634 old_member,
635 new_member,
636 seen_paths=seen_paths,
637 )
638 elif new_member.kind != old_member.kind:
639 yield ObjectChangedKindBreakage(new_member, old_member.kind, new_member.kind) # ty:ignore[invalid-argument-type]
640 elif old_member.is_module:
641 yield from _member_incompatibilities(
642 old_member,
643 new_member,
644 seen_paths=seen_paths,
645 )
646 elif old_member.is_class:
647 yield from _class_incompatibilities(
648 old_member, # ty:ignore[invalid-argument-type]
649 new_member, # ty:ignore[invalid-argument-type]
650 seen_paths=seen_paths,
651 )
652 elif old_member.is_function:
653 yield from _function_incompatibilities(old_member, new_member) # ty:ignore[invalid-argument-type]
654 elif old_member.is_attribute:
655 yield from _attribute_incompatibilities(old_member, new_member) # ty:ignore[invalid-argument-type]
656
657
658 def _returns_are_compatible(old_function: Function, new_function: Function) -> bool:
659 # We consider that a return value of `None` only is not a strong contract,
660 # it just means that the function returns nothing. We don't expect users
661 # to be asserting that the return value is `None`.
662 # Therefore we don't consider it a breakage if the return changes from `None`
663 # to something else: the function just gained a return value.
664 if old_function.returns is None:
665 return True
666
667 if new_function.returns is None:
668 # NOTE: Should it be configurable to allow/disallow removing a return type?
669 return False
670
671 with contextlib.suppress(AttributeError):
672 if new_function.returns == old_function.returns:
673 return True
674
675 # TODO: Support annotation breaking changes.
676 return True
677
678
679 _sentinel = object()
680
681
682 def find_breaking_changes(
683 old_obj: Object | Alias,
684 new_obj: Object | Alias,
685 ) -> Iterator[Breakage]:
686 """Find breaking changes between two versions of the same API.
687
688 The function will iterate recursively on all objects
689 and yield breaking changes with detailed information.
690
691 Parameters:
692 old_obj: The old version of an object.
693 new_obj: The new version of an object.
694
695 Yields:
696 Breaking changes.
697
698 Examples:
699 >>> import sys, griffe
700 >>> new = griffe.load("pkg")
701 >>> old = griffe.load_git("pkg", "1.2.3")
702 >>> for breakage in griffe.find_breaking_changes(old, new)
703 ... print(breakage.explain(style=style), file=sys.stderr)
704 """
705 yield from _member_incompatibilities(old_obj, new_obj)