pipbreak 0.2.2__tar.gz → 0.2.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pipbreak
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: Find the installed packages a dependency update breaks - the calls pip's version ranges let through.
5
5
  Author: Youssef Elaasri
6
6
  License-Expression: MIT
@@ -1,4 +1,4 @@
1
1
  from .checker import Finding, check_paths, check_source
2
2
 
3
3
  __all__ = ["Finding", "check_paths", "check_source"]
4
- __version__ = "0.2.2"
4
+ __version__ = "0.2.4"
@@ -836,11 +836,52 @@ def guarded_nodes(tree: ast.Module) -> set[ast.AST]:
836
836
  if not probed or (isinstance(n, (ast.Attribute, ast.Call)) and uses_any(n, probed)):
837
837
  guarded.update(ast.walk(n))
838
838
  break
839
+ # `with suppress(Exception): from x import New; return New` then `from x import old`: what
840
+ # follows a try that returns is the fallback for versions where the try failed.
841
+ for node in ast.walk(tree):
842
+ for field in ("body", "orelse", "finalbody"):
843
+ stmts = getattr(node, field, None)
844
+ if isinstance(stmts, list):
845
+ for i, stmt in enumerate(stmts):
846
+ if is_returning_try(stmt):
847
+ for rest in stmts[i + 1:]:
848
+ guarded.update(ast.walk(rest))
849
+ break
839
850
  for func in import_hints(tree):
840
851
  guarded.update(ast.walk(func))
852
+ # With `from __future__ import annotations` no annotation is ever evaluated: weblate's
853
+ # `objhash: hashlib._Hash` names a class that only exists in typeshed.
854
+ if any(isinstance(n, ast.ImportFrom) and n.module == "__future__" and any(a.name == "annotations" for a in n.names)
855
+ for n in tree.body):
856
+ for node in ast.walk(tree):
857
+ for ann in annotations_of(node):
858
+ guarded.update(ast.walk(ann))
841
859
  return guarded
842
860
 
843
861
 
862
+ def annotations_of(node: ast.AST) -> list[ast.expr]:
863
+ if isinstance(node, ast.arg) and node.annotation:
864
+ return [node.annotation]
865
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.returns:
866
+ return [node.returns]
867
+ if isinstance(node, ast.AnnAssign):
868
+ return [node.annotation]
869
+ return []
870
+
871
+
872
+ def is_returning_try(stmt: ast.AST) -> bool:
873
+ """A `try` or `with suppress(...)` whose body returns, and whose failure falls through."""
874
+ if not isinstance(stmt, (ast.With, ast.Try)) or not isinstance(stmt.body[-1], ast.Return):
875
+ return False
876
+ if isinstance(stmt, ast.With):
877
+ return any(isinstance(item.context_expr, ast.Call)
878
+ and decorator_name(item.context_expr.func).endswith("suppress") for item in stmt.items)
879
+ if isinstance(stmt, ast.Try):
880
+ return bool(stmt.handlers) and all(
881
+ not any(isinstance(n, (ast.Return, ast.Raise)) for n in h.body) for h in stmt.handlers)
882
+ return False
883
+
884
+
844
885
  def probed_objects(test: ast.AST) -> set[str]:
845
886
  """The objects a condition's hasattr/getattr calls look at: `hasattr(Shard, "x")` -> {"Shard"}."""
846
887
  return {ast.unparse(n.args[0]) for n in ast.walk(test)
@@ -893,6 +934,10 @@ def store_counts(tree: ast.AST) -> Counter:
893
934
  return counts
894
935
 
895
936
 
937
+ def is_mangled(name: str) -> bool:
938
+ return name.startswith("__") and not name.endswith("__")
939
+
940
+
896
941
  def walk_scope(body: list[ast.AST]):
897
942
  """ast.walk over one scope's statements (parents first), not descending into nested scopes."""
898
943
  stack = list(reversed(body))
@@ -926,6 +971,7 @@ class FileChecker(ast.NodeVisitor):
926
971
  self.local_classes: dict[str, LocalClass] = {}
927
972
  self.scopes: list[dict] = []
928
973
  self.class_stack: list[LocalClass | None] = []
974
+ self.class_names: list[str] = [] # lexically enclosing classes, for name mangling
929
975
  self.findings: list[Finding] = []
930
976
  self.guarded = guarded_nodes(self.tree)
931
977
  self.stores = store_counts(self.tree)
@@ -984,6 +1030,11 @@ class FileChecker(ast.NodeVisitor):
984
1030
  module = owner_module(owner)
985
1031
  if re.search(r"(^|\.)six\.moves\b", module): # its contents depend on the platform (winreg)
986
1032
  return
1033
+ if inspect.ismodule(owner) and getattr(owner, "__file__", None) is None and hasattr(owner, "__path__"):
1034
+ # `from google.cloud import storage`: a namespace package has no contents of its own,
1035
+ # so the name is a distribution that isn't installed (google-cloud-storage).
1036
+ self.report(node, "error", "API001", f"package '{owner.__name__}.{name}' is not installed in this environment")
1037
+ return
987
1038
  where = self.env.label(module)
988
1039
  if type(value) is Removed:
989
1040
  self.report(node, "error", "API002", f"'{what}.{name}' is not available in {where}: {value.reason}",
@@ -1252,6 +1303,9 @@ class FileChecker(ast.NodeVisitor):
1252
1303
  value = self.lookup_name(expr.id)
1253
1304
  elif isinstance(expr, ast.Call):
1254
1305
  value = self.call_result(expr)
1306
+ elif isinstance(expr, ast.Attribute) and self.class_names and is_mangled(expr.attr):
1307
+ # `Socket.__handle` in a class body is really `Socket._Admin__handle`, set elsewhere.
1308
+ value = None
1255
1309
  elif isinstance(expr, ast.Attribute):
1256
1310
  base = self.resolve(expr.value)
1257
1311
  value = None if base is None else self.resolve_member(expr, base)
@@ -1400,8 +1454,10 @@ class FileChecker(ast.NodeVisitor):
1400
1454
  self.visit(child)
1401
1455
  local = self.local_classes.get(node.name)
1402
1456
  self.class_stack.append(local if local is not None and local.node is node else None)
1457
+ self.class_names.append(node.name)
1403
1458
  for stmt in node.body:
1404
1459
  self.visit(stmt)
1460
+ self.class_names.pop()
1405
1461
  self.class_stack.pop()
1406
1462
 
1407
1463
  def visit_FunctionDef(self, node: ast.FunctionDef):
@@ -1515,6 +1571,11 @@ class FileChecker(ast.NodeVisitor):
1515
1571
  has_star = any(isinstance(a, ast.Starred) for a in node.args)
1516
1572
  if inspect.Parameter.VAR_POSITIONAL not in kinds and not has_star:
1517
1573
  max_positional = sum(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in params)
1574
+ if (inspect.isbuiltin(func) and module.split(".")[0] not in sys.stdlib_module_names | {"builtins"}):
1575
+ # A third-party C function's hand-written text signature can be stricter than its
1576
+ # parser: numpy 2.5 says `arange(start, /, stop, step, *, dtype)` but takes dtype
1577
+ # positionally. (The stdlib's come from Argument Clinic and are exact.)
1578
+ max_positional = sum(p.kind is not p.VAR_KEYWORD for p in params)
1518
1579
  if len(node.args) > max_positional:
1519
1580
  self.report(node, "error", "API004",
1520
1581
  f"{name}() takes at most {max_positional} positional argument(s) "
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pipbreak
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: Find the installed packages a dependency update breaks - the calls pip's version ranges let through.
5
5
  Author: Youssef Elaasri
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pipbreak"
7
- version = "0.2.2"
7
+ version = "0.2.4"
8
8
  description = "Find the installed packages a dependency update breaks - the calls pip's version ranges let through."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -338,6 +338,66 @@ class NoFalsePositives(unittest.TestCase):
338
338
  def test_rebound_name_is_not_tracked(self):
339
339
  self.assertEqual(codes("import json\njson = make_thing()\njson.parse\n"), [])
340
340
 
341
+ def test_private_names_in_a_class_are_mangled(self):
342
+ # python-socketio: `Socket.__handle` inside class InstrumentedServer is `Socket._InstrumentedServer__handle`.
343
+ source = """
344
+ import os
345
+ class Instrumented:
346
+ def install(self):
347
+ os.handle = os.__handle
348
+ """
349
+ self.assertEqual(codes(source), [])
350
+
351
+ def test_private_names_outside_a_class_are_checked(self):
352
+ self.assertEqual(codes("import os\nos.__made_up\n"), ["API002"])
353
+
354
+ def test_fallback_after_a_suppressed_return(self):
355
+ # django-dbbackup: the old Django API is only reached when the new one failed to import.
356
+ source = """
357
+ import contextlib
358
+ def storage():
359
+ with contextlib.suppress(Exception):
360
+ from os import path
361
+ return path
362
+ from os import made_up_old
363
+ return made_up_old
364
+ def other():
365
+ try:
366
+ from os import path
367
+ return path
368
+ except ImportError:
369
+ pass
370
+ import os
371
+ return os.made_up_old()
372
+ """
373
+ self.assertEqual(codes(source), [])
374
+
375
+ def test_code_after_a_try_that_does_not_return_is_checked(self):
376
+ source = """
377
+ import os
378
+ def f():
379
+ try:
380
+ x = 1
381
+ except Exception:
382
+ pass
383
+ os.made_up()
384
+ """
385
+ self.assertEqual(codes(source), ["API002"])
386
+
387
+ def test_lazy_annotations_are_not_evaluated(self):
388
+ # weblate: `objhash: hashlib._Hash` names a class that only exists in typeshed.
389
+ source = """
390
+ from __future__ import annotations
391
+ import os
392
+ def f(x: os.MadeUp) -> os.AlsoMadeUp:
393
+ y: os.Nope = 1
394
+ """
395
+ self.assertEqual(codes(source), [])
396
+ self.assertEqual(codes("import os\ndef f(x: os.MadeUp): pass\n"), ["API002"])
397
+
398
+ def test_stdlib_builtin_positional_limits_are_kept(self):
399
+ self.assertEqual(codes("sorted([1], None, False)\n"), ["API004"])
400
+
341
401
  def test_ignore_comment(self):
342
402
  self.assertEqual(codes("import json\njson.parse('{}') # pipbreak: ignore\n"), [])
343
403
 
@@ -979,6 +1039,13 @@ class InstalledPackages(unittest.TestCase):
979
1039
  findings = check_installed({"nsp.one"})[0]
980
1040
  self.assertEqual([f.path for f in findings], ["nsp/two/__init__.py"])
981
1041
 
1042
+ def test_missing_piece_of_a_namespace_is_not_installed(self):
1043
+ # `from google.cloud import storage` without google-cloud-storage installed.
1044
+ [f] = check_source("from nsp import absent\n")
1045
+ self.assertEqual((f.code, f.message), ("API001", "package 'nsp.absent' is not installed in this environment"))
1046
+ [f] = check_source("import nsp.one\nnsp.absent\n")
1047
+ self.assertEqual(f.code, "API001")
1048
+
982
1049
  def test_shared_top_level_owner_does_not_depend_on_install_order(self):
983
1050
  self.assertEqual(distribution_of({"top": ["zed", "core"]}, "top.sub"), "core")
984
1051
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes