specfact-cli 0.55.5__py3-none-any.whl → 0.55.20__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.
specfact_cli/__init__.py CHANGED
@@ -76,6 +76,6 @@ def _install_progressive_disclosure() -> None:
76
76
  # keeps missing-command and missing-parameter UX consistent outside the root CLI too.
77
77
  _install_progressive_disclosure()
78
78
 
79
- __version__ = "0.55.5"
79
+ __version__ = "0.55.20"
80
80
 
81
81
  __all__ = ["__version__"]
@@ -11,7 +11,7 @@ import sys
11
11
  import tokenize
12
12
  from collections.abc import Iterator, Sequence
13
13
  from dataclasses import asdict, dataclass
14
- from itertools import pairwise
14
+ from itertools import groupby, pairwise
15
15
  from pathlib import Path
16
16
 
17
17
 
@@ -266,6 +266,7 @@ def _scope_findings(
266
266
  scope: ast.AsyncFunctionDef,
267
267
  aliases: dict[str, str],
268
268
  coroutines: set[str],
269
+ bindings: Sequence[_CallableBinding],
269
270
  ) -> Iterator[tuple[str, ast.stmt | ast.expr | ast.ExceptHandler]]:
270
271
  nodes: list[ast.AST] = [scope]
271
272
  for statement in scope.body:
@@ -273,9 +274,9 @@ def _scope_findings(
273
274
  nodes.extend((statement, *_scoped_nodes(statement)))
274
275
  imports = {**aliases, **import_aliases(nodes)}
275
276
  parents = {child: node for node in nodes for child in ast.iter_child_nodes(node)}
277
+ for call, bound_coroutines in _calls_with_coroutines(nodes, parents, coroutines, bindings):
278
+ yield from ((rule, call) for rule in _async_call_rules(call, parents, imports, bound_coroutines))
276
279
  for node in nodes:
277
- if isinstance(node, ast.Call):
278
- yield from ((rule, node) for rule in _async_call_rules(node, parents, imports, coroutines))
279
280
  yield from _async_statement_rules(node, imports)
280
281
  yield from (("task-result-not-checked", call) for call in _unobserved_tasks(nodes, imports))
281
282
  if not _has_cancellation_handler(nodes, imports):
@@ -293,6 +294,16 @@ _LexicalScope = (
293
294
  | ast.DictComp
294
295
  | ast.GeneratorExp
295
296
  )
297
+ _Loop = ast.For | ast.AsyncFor | ast.While
298
+
299
+
300
+ @dataclass(frozen=True)
301
+ class _CallableBinding:
302
+ position: tuple[int, int]
303
+ name: str
304
+ value: bool | tuple[str, ...] | None
305
+ may_skip: bool
306
+ node: ast.AST
296
307
 
297
308
 
298
309
  def _enclosing_scope(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> _LexicalScope | None:
@@ -303,24 +314,302 @@ def _enclosing_scope(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> _Lexical
303
314
  return None
304
315
 
305
316
 
306
- def _scope_functions(tree: ast.Module, parents: dict[ast.AST, ast.AST]) -> dict[_LexicalScope, dict[str, bool]]:
307
- definitions: dict[_LexicalScope, dict[str, bool]] = {}
308
- bindings = (
309
- node
310
- for node in ast.walk(tree)
311
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
312
- or (isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store))
317
+ def _store_position(node: ast.Name, parents: dict[ast.AST, ast.AST]) -> tuple[int, int]:
318
+ target: ast.AST = node
319
+ while isinstance(parent := parents.get(target), (ast.List, ast.Tuple, ast.Starred)):
320
+ target = parent
321
+ if isinstance(parent, (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.NamedExpr)):
322
+ # Assignment evaluates its value before replacing the target binding.
323
+ return parent.end_lineno or parent.lineno, parent.end_col_offset or parent.col_offset
324
+ return node.lineno, node.col_offset
325
+
326
+
327
+ def _binding_may_be_skipped(node: ast.AST, parents: dict[ast.AST, ast.AST], boundary: _Loop | None = None) -> bool:
328
+ conditional = (
329
+ ast.If,
330
+ ast.IfExp,
331
+ ast.BoolOp,
332
+ ast.For,
333
+ ast.AsyncFor,
334
+ ast.While,
335
+ ast.Try,
336
+ ast.TryStar,
337
+ ast.Match,
338
+ ast.With,
339
+ ast.AsyncWith,
313
340
  )
314
- for node in sorted(bindings, key=lambda item: (item.lineno, item.col_offset)):
341
+ while (parent := parents.get(node)) is not None:
342
+ if parent is boundary or isinstance(parent, _LexicalScope):
343
+ break
344
+ if isinstance(parent, conditional):
345
+ return True
346
+ node = parent
347
+ return False
348
+
349
+
350
+ def _enclosing_loops(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> Iterator[_Loop]:
351
+ while (parent := parents.get(node)) is not None and not isinstance(parent, _LexicalScope):
352
+ if isinstance(parent, _Loop) and (
353
+ node in parent.body or (isinstance(parent, ast.While) and node is parent.test)
354
+ ):
355
+ yield parent
356
+ node = parent
357
+
358
+
359
+ def _assignment_rhs(target: ast.expr, parents: dict[ast.AST, ast.AST]) -> ast.expr | None:
360
+ container = parents.get(target)
361
+ if isinstance(container, (ast.Assign, ast.AnnAssign, ast.NamedExpr)):
362
+ return container.value
363
+ if not isinstance(container, (ast.List, ast.Tuple)):
364
+ return None
365
+ values = _assignment_rhs(container, parents)
366
+ if not isinstance(values, (ast.List, ast.Tuple)) or len(container.elts) != len(values.elts):
367
+ return None
368
+ if any(isinstance(item, ast.Starred) for item in (*container.elts, *values.elts)):
369
+ return None
370
+ return values.elts[container.elts.index(target)]
371
+
372
+
373
+ def _callable_aliases(value: ast.expr) -> Iterator[str]:
374
+ if isinstance(value, ast.IfExp):
375
+ if isinstance(value.test, ast.Constant):
376
+ yield from _callable_aliases(value.body if value.test.value else value.orelse)
377
+ else:
378
+ yield from _callable_aliases(value.body)
379
+ yield from _callable_aliases(value.orelse)
380
+ return
381
+ if name := qualified_name(value, {}):
382
+ yield name
383
+
384
+
385
+ def _assigned_callable(node: ast.Name, parents: dict[ast.AST, ast.AST]) -> bool | tuple[str, ...] | None:
386
+ assignment = parents.get(node)
387
+ if isinstance(assignment, ast.AnnAssign) and assignment.value is None:
388
+ # A bare annotation declares a local name and leaves its current value alone.
389
+ return None
390
+ value = _assignment_rhs(node, parents)
391
+ return False if value is None else tuple(_callable_aliases(value)) or False
392
+
393
+
394
+ def _scope_callable_bindings(
395
+ nodes: Sequence[ast.AST], parents: dict[ast.AST, ast.AST]
396
+ ) -> dict[_LexicalScope, list[_CallableBinding]]:
397
+ definitions: dict[_LexicalScope, list[_CallableBinding]] = {}
398
+ for node in nodes:
399
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
400
+ position = (node.lineno, node.col_offset)
401
+ name, value = node.name, isinstance(node, ast.AsyncFunctionDef)
402
+ elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
403
+ position = _store_position(node, parents)
404
+ name, value = node.id, _assigned_callable(node, parents)
405
+ else:
406
+ continue
315
407
  owner = _enclosing_scope(node, parents)
316
408
  if owner is not None:
317
- name = node.id if isinstance(node, ast.Name) else node.name
318
- definitions.setdefault(owner, {})[name] = isinstance(node, ast.AsyncFunctionDef)
409
+ binding = _CallableBinding(position, name, value, _binding_may_be_skipped(node, parents), node)
410
+ definitions.setdefault(owner, []).append(binding)
411
+ for bindings in definitions.values():
412
+ bindings.sort(key=lambda binding: binding.position)
319
413
  return definitions
320
414
 
321
415
 
416
+ def _binds_coroutine(binding: _CallableBinding, coroutines: set[str]) -> bool:
417
+ return binding.value is True or (
418
+ isinstance(binding.value, tuple) and any(name in coroutines for name in binding.value)
419
+ )
420
+
421
+
422
+ def _binding_groups(bindings: Sequence[_CallableBinding]) -> Iterator[tuple[_CallableBinding, ...]]:
423
+ return (tuple(group) for _, group in groupby(bindings, key=lambda binding: binding.position))
424
+
425
+
426
+ def _resolved_bindings(group: Sequence[_CallableBinding], coroutines: set[str]) -> list[tuple[_CallableBinding, bool]]:
427
+ # Unpacking reads every right-hand value before storing any of the targets.
428
+ return [(binding, _binds_coroutine(binding, coroutines)) for binding in group]
429
+
430
+
431
+ def _apply_callable_binding(binding: _CallableBinding, coroutines: set[str], is_coroutine: bool) -> None:
432
+ if is_coroutine:
433
+ coroutines.add(binding.name)
434
+ elif binding.value is not None and not binding.may_skip:
435
+ coroutines.discard(binding.name)
436
+
437
+
438
+ def _synchronous_loop_targets(nodes: Sequence[ast.AST]) -> dict[_Loop, dict[str, bool]]:
439
+ # Only infer a synchronous target when every iterable item is a literal lambda.
440
+ return {
441
+ node: {node.target.id: False}
442
+ for node in nodes
443
+ if isinstance(node, ast.For)
444
+ and isinstance(node.target, ast.Name)
445
+ and isinstance(node.iter, (ast.List, ast.Tuple))
446
+ and all(isinstance(item, ast.Lambda) for item in node.iter.elts)
447
+ }
448
+
449
+
450
+ def _iteration_coroutines(
451
+ coroutines: set[str],
452
+ loops: Sequence[_Loop],
453
+ overrides: dict[_Loop, dict[str, bool]],
454
+ carried: dict[_Loop, set[str]],
455
+ ) -> set[str]:
456
+ if not loops:
457
+ return coroutines
458
+ visible = coroutines.copy()
459
+ for loop in reversed(loops):
460
+ # A loop target resets its own iteration. Inner loops then contribute their bindings.
461
+ visible.update(carried.get(loop, ()))
462
+ for name, is_coroutine in overrides.get(loop, {}).items():
463
+ if is_coroutine:
464
+ visible.add(name)
465
+ else:
466
+ visible.discard(name)
467
+ return visible
468
+
469
+
470
+ def _update_iteration_bindings(
471
+ binding: _CallableBinding,
472
+ loops: Sequence[_Loop],
473
+ overrides: dict[_Loop, dict[str, bool]],
474
+ parents: dict[ast.AST, ast.AST],
475
+ is_coroutine: bool,
476
+ ) -> None:
477
+ if binding.value is None:
478
+ return
479
+ for loop in loops:
480
+ if is_coroutine or not _binding_may_be_skipped(binding.node, parents, loop):
481
+ overrides.setdefault(loop, {})[binding.name] = is_coroutine
482
+
483
+
484
+ def _apply_iteration_bindings(
485
+ group: tuple[_CallableBinding, ...],
486
+ coroutines: set[str],
487
+ overrides: dict[_Loop, dict[str, bool]],
488
+ parents: dict[ast.AST, ast.AST],
489
+ carried: dict[_Loop, set[str]],
490
+ ) -> None:
491
+ loops = tuple(_enclosing_loops(group[0].node, parents))
492
+ visible = _iteration_coroutines(coroutines, loops, overrides, carried)
493
+ for binding, is_coroutine in _resolved_bindings(group, visible):
494
+ _apply_callable_binding(binding, coroutines, is_coroutine)
495
+ _update_iteration_bindings(binding, loops, overrides, parents, is_coroutine)
496
+
497
+
498
+ def _body_exit(statements: Sequence[ast.stmt]) -> ast.stmt | None:
499
+ for statement in statements:
500
+ if isinstance(statement, (ast.Break, ast.Continue, ast.Raise, ast.Return)):
501
+ return statement
502
+ if isinstance(statement, ast.If) and _body_exit(statement.body) and _body_exit(statement.orelse):
503
+ return statement
504
+ return None
505
+
506
+
507
+ def _can_repeat(loop: _Loop) -> bool:
508
+ if isinstance(loop, ast.For) and isinstance(loop.iter, (ast.List, ast.Tuple)):
509
+ items = loop.iter.elts
510
+ return len(items) > 1 or any(isinstance(item, ast.Starred) for item in items)
511
+ return True
512
+
513
+
514
+ def _loop_carry_events(
515
+ groups: Sequence[tuple[_CallableBinding, ...]],
516
+ nodes: Sequence[ast.AST],
517
+ parents: dict[ast.AST, ast.AST],
518
+ exits: dict[_Loop, ast.stmt | None],
519
+ ) -> list[tuple[_CallableBinding, ...] | _Loop]:
520
+ events: list[tuple[tuple[int, int], tuple[_CallableBinding, ...] | _Loop]] = [
521
+ (group[0].position, group) for group in groups
522
+ ]
523
+ for node in nodes:
524
+ if not isinstance(node, ast.Continue):
525
+ continue
526
+ loop = next(_enclosing_loops(node, parents), None)
527
+ if loop is None or loop not in exits:
528
+ continue
529
+ end = exits[loop]
530
+ if end is None or node.lineno <= (end.end_lineno or end.lineno):
531
+ events.append(((node.lineno, node.col_offset), loop))
532
+ return [event for _, event in sorted(events, key=lambda entry: entry[0])]
533
+
534
+
535
+ def _carry_live_bindings(carried: dict[_Loop, set[str]], loop: _Loop, bindings: dict[str, bool]) -> None:
536
+ carried.setdefault(loop, set()).update(name for name, is_coroutine in bindings.items() if is_coroutine)
537
+
538
+
539
+ def _loop_binding_names(
540
+ groups: Sequence[tuple[_CallableBinding, ...]],
541
+ nodes: Sequence[ast.AST],
542
+ coroutines: set[str],
543
+ targets: dict[_Loop, dict[str, bool]],
544
+ parents: dict[ast.AST, ast.AST],
545
+ ) -> dict[_Loop, set[str]]:
546
+ carried: dict[_Loop, set[str]] = {}
547
+ exits = {node: _body_exit(node.body) for node in nodes if isinstance(node, _Loop) and _can_repeat(node)}
548
+ events = _loop_carry_events(groups, nodes, parents, exits)
549
+ # Only names that may reach a backedge carry. Chained aliases can take
550
+ # multiple passes, and each continuing pass adds a name to a finite set.
551
+ while True:
552
+ prior_count = sum(map(len, carried.values()))
553
+ visible = coroutines.copy()
554
+ overrides = {loop: bindings.copy() for loop, bindings in targets.items()}
555
+ for event in events:
556
+ if isinstance(event, tuple):
557
+ _apply_iteration_bindings(event, visible, overrides, parents, carried)
558
+ else:
559
+ _carry_live_bindings(carried, event, overrides.get(event, {}))
560
+ for loop, end in exits.items():
561
+ if end is None:
562
+ _carry_live_bindings(carried, loop, overrides.get(loop, {}))
563
+ if sum(map(len, carried.values())) == prior_count:
564
+ return carried
565
+
566
+
567
+ def _calls_with_coroutines(
568
+ nodes: Sequence[ast.AST],
569
+ parents: dict[ast.AST, ast.AST],
570
+ coroutines: set[str],
571
+ bindings: Sequence[_CallableBinding],
572
+ ) -> Iterator[tuple[ast.Call, set[str]]]:
573
+ groups = tuple(_binding_groups(bindings))
574
+ targets = _synchronous_loop_targets(nodes)
575
+ carried = (
576
+ _loop_binding_names(groups, nodes, coroutines, targets, parents)
577
+ if any(isinstance(node, _Loop) for node in nodes)
578
+ else {}
579
+ )
580
+ events = iter(groups)
581
+ event = next(events, None)
582
+ calls = sorted(
583
+ (node for node in nodes if isinstance(node, ast.Call)), key=lambda node: (node.lineno, node.col_offset)
584
+ )
585
+ for call in calls:
586
+ position = (call.lineno, call.col_offset)
587
+ while event is not None and event[0].position <= position:
588
+ _apply_iteration_bindings(event, coroutines, targets, parents, carried)
589
+ event = next(events, None)
590
+ loops = tuple(_enclosing_loops(call, parents))
591
+ yield call, _iteration_coroutines(coroutines, loops, targets, carried)
592
+
593
+
594
+ def _binding_flags(
595
+ bindings: Sequence[_CallableBinding],
596
+ definition_position: tuple[int, int] | None = None,
597
+ inherited: set[str] | None = None,
598
+ ) -> dict[str, bool]:
599
+ coroutines = set(inherited or ())
600
+ for group in _binding_groups(bindings):
601
+ resolved = _resolved_bindings(group, coroutines)
602
+ if definition_position is None or group[0].position < definition_position:
603
+ for binding, is_coroutine in resolved:
604
+ _apply_callable_binding(binding, coroutines, is_coroutine)
605
+ else:
606
+ # An enclosing scope can rebind the name after the function runs.
607
+ coroutines.update(binding.name for binding, is_coroutine in resolved if is_coroutine)
608
+ return {binding.name: binding.name in coroutines for binding in bindings}
609
+
610
+
322
611
  def _method_coroutines(
323
- scope: ast.AsyncFunctionDef, owner: _LexicalScope | None, definitions: dict[_LexicalScope, dict[str, bool]]
612
+ scope: ast.AsyncFunctionDef, owner: _LexicalScope | None, definitions: dict[_LexicalScope, list[_CallableBinding]]
324
613
  ) -> set[str]:
325
614
  arguments = scope.args.posonlyargs + scope.args.args
326
615
  if not isinstance(owner, ast.ClassDef) or not arguments:
@@ -328,24 +617,78 @@ def _method_coroutines(
328
617
  if any(qualified_name(node, {}).rsplit(".", 1)[-1] == "staticmethod" for node in scope.decorator_list):
329
618
  return set()
330
619
  receiver = arguments[0].arg
331
- return {f"{receiver}.{name}" for name, is_async in definitions.get(owner, {}).items() if is_async}
620
+ return {f"{receiver}.{name}" for name, is_async in _binding_flags(definitions.get(owner, ())).items() if is_async}
621
+
622
+
623
+ def _enclosing_scopes(scope: _LexicalScope, parents: dict[ast.AST, ast.AST]) -> Iterator[_LexicalScope]:
624
+ owner = _enclosing_scope(scope, parents)
625
+ while owner is not None:
626
+ yield owner
627
+ owner = _enclosing_scope(owner, parents)
628
+
629
+
630
+ def _outer_declarations(scope: _LexicalScope) -> tuple[set[str], set[str]]:
631
+ global_names: set[str] = set()
632
+ nonlocal_names: set[str] = set()
633
+ for node in _scoped_nodes(scope):
634
+ if isinstance(node, ast.Global):
635
+ global_names.update(node.names)
636
+ elif isinstance(node, ast.Nonlocal):
637
+ nonlocal_names.update(node.names)
638
+ return global_names, global_names | nonlocal_names
639
+
640
+
641
+ def _apply_enclosing_bindings(
642
+ scope: _LexicalScope,
643
+ bindings: Sequence[_CallableBinding],
644
+ position: tuple[int, int],
645
+ visible: dict[str, bool],
646
+ module_flags: dict[str, bool],
647
+ ) -> None:
648
+ global_names, redirected = _outer_declarations(scope)
649
+ local_names = {binding.name for binding in bindings} - redirected
650
+ inherited = {name for name, is_async in visible.items() if is_async} - local_names - global_names
651
+ inherited.update(name for name in global_names if module_flags.get(name))
652
+ flags = _binding_flags(bindings, position, inherited)
653
+ module_flags.update({name: flags[name] for name in global_names & flags.keys()})
654
+ visible.update(flags)
655
+ visible.update({name: module_flags.get(name, False) for name in global_names})
656
+
657
+
658
+ def _enclosing_callable_flags(
659
+ scope: ast.AsyncFunctionDef,
660
+ parents: dict[ast.AST, ast.AST],
661
+ definitions: dict[_LexicalScope, list[_CallableBinding]],
662
+ global_names: set[str],
663
+ ) -> dict[str, bool]:
664
+ visible: dict[str, bool] = {}
665
+ module_flags: dict[str, bool] = {}
666
+ position = scope.lineno, scope.col_offset
667
+ for owner in reversed(tuple(_enclosing_scopes(scope, parents))):
668
+ bindings = definitions.get(owner, ())
669
+ if isinstance(owner, ast.Module):
670
+ module_flags = _binding_flags(bindings, position)
671
+ visible.update(module_flags)
672
+ elif not isinstance(owner, ast.ClassDef):
673
+ _apply_enclosing_bindings(owner, bindings, position, visible, module_flags)
674
+ visible.update({name: module_flags.get(name, False) for name in global_names})
675
+ return visible
332
676
 
333
677
 
334
678
  def _visible_coroutines(
335
- scope: ast.AsyncFunctionDef, parents: dict[ast.AST, ast.AST], definitions: dict[_LexicalScope, dict[str, bool]]
679
+ scope: ast.AsyncFunctionDef,
680
+ parents: dict[ast.AST, ast.AST],
681
+ definitions: dict[_LexicalScope, list[_CallableBinding]],
336
682
  ) -> set[str]:
337
683
  owner = _enclosing_scope(scope, parents)
338
- visible = dict(definitions.get(scope, {}))
339
- visible.update(
340
- dict.fromkeys((arg.arg for arg in scope.args.posonlyargs + scope.args.args + scope.args.kwonlyargs), False)
341
- )
684
+ # A locally declared name shadows the outer name throughout the function.
685
+ # Its callable type then changes at each statement that binds it.
686
+ global_names, outer_names = _outer_declarations(scope)
687
+ visible = {binding.name for binding in definitions.get(scope, ())} - outer_names
688
+ visible.update(arg.arg for arg in scope.args.posonlyargs + scope.args.args + scope.args.kwonlyargs)
342
689
  result = _method_coroutines(scope, owner, definitions)
343
- while owner is not None:
344
- if not isinstance(owner, ast.ClassDef):
345
- for name, is_async in definitions.get(owner, {}).items():
346
- visible.setdefault(name, is_async)
347
- owner = _enclosing_scope(owner, parents)
348
- return result | {name for name, is_async in visible.items() if is_async}
690
+ inherited = _enclosing_callable_flags(scope, parents, definitions, global_names)
691
+ return result | {name for name, is_async in inherited.items() if is_async and name not in visible}
349
692
 
350
693
 
351
694
  def async_findings(tree: ast.Module, filename: str) -> list[AsyncFinding]:
@@ -353,11 +696,11 @@ def async_findings(tree: ast.Module, filename: str) -> list[AsyncFinding]:
353
696
  aliases = import_aliases(tree.body)
354
697
  nodes = list(ast.walk(tree))
355
698
  parents = {child: node for node in nodes for child in ast.iter_child_nodes(node)}
356
- definitions = _scope_functions(tree, parents)
699
+ definitions = _scope_callable_bindings(nodes, parents)
357
700
  findings: set[AsyncFinding] = set()
358
701
  for scope in (node for node in nodes if isinstance(node, ast.AsyncFunctionDef)):
359
702
  coroutines = _visible_coroutines(scope, parents, definitions)
360
- for rule, node in _scope_findings(scope, aliases, coroutines):
703
+ for rule, node in _scope_findings(scope, aliases, coroutines, definitions.get(scope, ())):
361
704
  severity, message = RULES[rule]
362
705
  findings.add(AsyncFinding(filename, node.lineno, node.col_offset + 1, rule, severity, message))
363
706
  return sorted(findings)
@@ -456,7 +456,8 @@ class CodeAnalyzer:
456
456
  - Tests validate code, they don't define what code should do
457
457
  - Test files should only be used for linking to production features and extracting examples
458
458
  """
459
- file_str = str(file_path)
459
+ relative_path = file_path.relative_to(self.repo_path) if file_path.is_absolute() else file_path
460
+ directory_parts = relative_path.parts[:-1]
460
461
  file_name = file_path.name
461
462
 
462
463
  # Skip common non-source directories
@@ -473,13 +474,12 @@ class CodeAnalyzer:
473
474
  ".eggs",
474
475
  ]
475
476
 
476
- if any(pattern in file_str for pattern in skip_patterns):
477
+ if any(part in skip_patterns for part in directory_parts):
477
478
  return True
478
479
 
479
480
  # Skip test directories (both "test/" and "tests/")
480
481
  # Check if any path component is a test directory
481
- path_parts = file_path.parts
482
- if any(part in ("test", "tests") for part in path_parts):
482
+ if any(part in ("test", "tests") for part in directory_parts):
483
483
  return True
484
484
 
485
485
  # Skip test files by naming pattern (test_*.py, *_test.py)
@@ -273,15 +273,34 @@ def _is_string_literal(node: ast.expr | None) -> bool:
273
273
  return isinstance(node, ast.JoinedStr) or (isinstance(node, ast.Constant) and isinstance(node.value, str))
274
274
 
275
275
 
276
- def _preceding_string_bindings(loop: ast.For | ast.AsyncFor, parent: ast.AST) -> set[str]:
277
- statements = next((items for _, items in ast.iter_fields(parent) if isinstance(items, list) and loop in items), [])
278
- strings: set[str] = set()
279
- for item in statements:
280
- if item is loop:
276
+ def _earlier_block_statements(node: ast.AST, parent: ast.AST) -> list[ast.stmt]:
277
+ for _, children in ast.iter_fields(parent):
278
+ if not isinstance(children, list):
279
+ continue
280
+ nodes = [item for item in children if isinstance(item, ast.AST)]
281
+ if node in nodes:
282
+ return [item for item in nodes[: nodes.index(node)] if isinstance(item, ast.stmt)]
283
+ return []
284
+
285
+
286
+ def _enclosing_statements_before(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> Iterator[ast.stmt]:
287
+ blocks: list[list[ast.stmt]] = []
288
+ while (parent := parents.get(node)) is not None:
289
+ blocks.append(_earlier_block_statements(node, parent))
290
+ if isinstance(parent, (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
281
291
  break
282
- if not isinstance(item, ast.Assign):
292
+ node = parent
293
+ for block in reversed(blocks):
294
+ yield from block
295
+
296
+
297
+ def _preceding_string_bindings(loop: ast.For | ast.AsyncFor, parents: dict[ast.AST, ast.AST]) -> set[str]:
298
+ strings: set[str] = set()
299
+ for item in _enclosing_statements_before(loop, parents):
300
+ if not isinstance(item, (ast.Assign, ast.AnnAssign)) or item.value is None:
283
301
  continue
284
- targets = {target.id for target in item.targets if isinstance(target, ast.Name)}
302
+ assigned = item.targets if isinstance(item, ast.Assign) else [item.target]
303
+ targets = {target.id for target in assigned if isinstance(target, ast.Name)}
285
304
  strings.difference_update(targets)
286
305
  if _is_string_literal(item.value):
287
306
  strings.update(targets)
@@ -329,7 +348,7 @@ def _statement_evidence(
329
348
  if isinstance(node, ast.Subscript) and qualified_name(node.value, aliases) == "os.environ":
330
349
  yield PatternMatch("env-variable-access", node)
331
350
  if isinstance(node, (ast.For, ast.AsyncFor)):
332
- for statement in _repeated_additions(node, _preceding_string_bindings(node, parents[node])):
351
+ for statement in _repeated_additions(node, _preceding_string_bindings(node, parents)):
333
352
  yield PatternMatch("string-concatenation-loop", statement, "Review repeated concatenation in a loop")
334
353
 
335
354
 
specfact_cli/cli.py CHANGED
@@ -954,11 +954,10 @@ def _get_group_from_info_wrapper(
954
954
  _typer_get_group_from_info_original: Callable[..., click.Group] | None = None
955
955
  _typer_get_command_original: Callable[[typer.Typer], click.Command] | None = None
956
956
  _typer_get_params_original: Callable[..., Any] | None = None
957
- _typer_get_params_convertors_original: Callable[..., Any] | None = None
958
957
 
959
958
 
960
959
  def _specfact_get_params_from_function(func: Callable[..., Any]) -> Any:
961
- """Map thin Typer entrypoints to their option-rich implementations for Click param generation."""
960
+ """Resolve thin entry points and normalize Click contexts before Typer builds commands."""
962
961
  orig = _typer_get_params_original
963
962
  if orig is None:
964
963
  import typer.utils as typer_utils
@@ -976,7 +975,11 @@ def _specfact_get_params_from_function(func: Callable[..., Any]) -> Any:
976
975
  merge_install = getattr(module, "_specfact_merge_install_param_specs", None)
977
976
  if merge_install is not None:
978
977
  return merge_install(orig)
979
- return orig(func)
978
+ params = orig(func)
979
+ for param in params.values():
980
+ if _is_context_annotation(param.annotation):
981
+ param.annotation = typer.Context
982
+ return params
980
983
 
981
984
 
982
985
  def _is_context_annotation(annotation: object) -> bool:
@@ -985,49 +988,6 @@ def _is_context_annotation(annotation: object) -> bool:
985
988
  return getattr(annotation, "__name__", "") == "Context" and "click" in getattr(annotation, "__module__", "")
986
989
 
987
990
 
988
- def _specfact_get_params_convertors_ctx_param_name_from_function(callback: Callable[..., Any] | None) -> Any:
989
- """Treat both Click context classes as Typer context parameters across Typer releases."""
990
- assert _typer_get_params_convertors_original is not None
991
- original_error: RuntimeError | None = None
992
- try:
993
- return _typer_get_params_convertors_original(callback)
994
- except RuntimeError as exc:
995
- if callback is None or "click.core.Context" not in str(exc):
996
- raise
997
- original_error = exc
998
- import typer.utils as typer_utils
999
-
1000
- params = _specfact_get_params_from_function(callback)
1001
- ctx_param_name: str | None = None
1002
- filtered_params: dict[str, Any] = {}
1003
- for name, param in params.items():
1004
- if ctx_param_name is None and _is_context_annotation(getattr(param, "annotation", None)):
1005
- ctx_param_name = name
1006
- continue
1007
- filtered_params[name] = param
1008
-
1009
- if ctx_param_name is None:
1010
- raise RuntimeError("Unable to identify Click context parameter") from original_error
1011
-
1012
- typer_main = cast(Any, importlib.import_module("typer.main"))
1013
- previous_main_get_params = typer_main.get_params_from_function
1014
- previous_utils_get_params = typer_utils.get_params_from_function
1015
-
1016
- def _filtered_get_params(func: Callable[..., Any]) -> Any:
1017
- if func is callback:
1018
- return filtered_params
1019
- return previous_main_get_params(func)
1020
-
1021
- try:
1022
- typer_main.get_params_from_function = _filtered_get_params
1023
- typer_utils.get_params_from_function = _filtered_get_params
1024
- click_params, convertors, _ignored_ctx = _typer_get_params_convertors_original(callback)
1025
- finally:
1026
- typer_main.get_params_from_function = previous_main_get_params
1027
- typer_utils.get_params_from_function = previous_utils_get_params
1028
- return click_params, convertors, ctx_param_name
1029
-
1030
-
1031
991
  # Patch so root app build uses our delegate group for lazy typers (built via get_group_from_info).
1032
992
  def _patch_typer_build() -> None:
1033
993
  import typer.utils as typer_utils
@@ -1035,7 +995,6 @@ def _patch_typer_build() -> None:
1035
995
  typer_main = cast(Any, importlib.import_module("typer.main"))
1036
996
 
1037
997
  global _typer_get_group_from_info_original, _typer_get_command_original, _typer_get_params_original
1038
- global _typer_get_params_convertors_original
1039
998
  # Save originals only on first patch; avoid overwriting with our wrapper when cli is re-imported (e.g. by plan module).
1040
999
  if _typer_get_group_from_info_original is None:
1041
1000
  _typer_get_group_from_info_original = typer_main.get_group_from_info
@@ -1043,14 +1002,9 @@ def _patch_typer_build() -> None:
1043
1002
  _typer_get_command_original = typer_main.get_command
1044
1003
  if _typer_get_params_original is None:
1045
1004
  _typer_get_params_original = typer_utils.get_params_from_function
1046
- if _typer_get_params_convertors_original is None:
1047
- _typer_get_params_convertors_original = typer_main.get_params_convertors_ctx_param_name_from_function
1048
1005
  typer_utils.get_params_from_function = _specfact_get_params_from_function
1049
1006
  # typer.main may have bound get_params_from_function at import time; keep in sync.
1050
1007
  typer_main.get_params_from_function = _specfact_get_params_from_function
1051
- typer_main.get_params_convertors_ctx_param_name_from_function = (
1052
- _specfact_get_params_convertors_ctx_param_name_from_function
1053
- )
1054
1008
  typer_main.get_command = _get_command
1055
1009
  typer_main.get_group_from_info = _get_group_from_info_wrapper
1056
1010