Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Changelog

## 0.6.0

- Analyze `importlib.import_module`, `importlib.__import__`, and built-in `__import__` using the same layer, slice, public API, and app/UI rules as ordinary imports.
- Resolve imported/assigned loader aliases, literal names, constant bindings, concatenation, f-strings, joins, relative packages, and `__import__` fromlists without executing project code.
- Inspect literal `exec`/`eval` code and literal `compile` inputs, including nested dynamic imports. Report violations at the original call site.
- Fail with `dynamic-imports` when a recognized loader target, package, fromlist, executed code, or escaped loader cannot be inspected. Unknown values never count as proof that a recognized dynamic import is valid.
- Respect function/lambda parameter shadowing, class/method lookup, comprehensions and conditional bindings; preserve possible loader provenance across branches.
- Bound recursive code expansion and diagnostics to prevent generated code from making inspection unbounded.
- Add dynamic import, namespace, scope, no-execution, subprocess and installed-wheel regression controls. Custom import hooks and arbitrary runtime behavior are not executed by the checker.

## 0.5.0

- Replace runtime import checks with static AST analysis. Forbidden layer and sibling-slice imports now fail both under pytest and in standalone Python, without importing project code or requiring pytest-archon.
Expand Down
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,23 @@ See the [rule documentation](src/pytest_fsd/rules/) for examples and details.

## Scope and limitations

- Import rules statically inspect Python syntax, including relative imports, package initializers, function-local imports and `if TYPE_CHECKING:` branches. They do not execute project code. Dynamically computed imports (`importlib`, `__import__`, `exec`) and custom import hooks are not resolved.
- Import rules statically inspect Python syntax, including relative imports, package initializers, function-local imports and `if TYPE_CHECKING:` branches. They do not execute project code. Programmatic imports through `importlib.import_module`, `importlib.__import__`, and built-in `__import__` are analyzed too. Loader aliases, literal names, constant bindings, concatenation, f-strings, joins, relative packages and fromlists are supported. Literal `exec`/`eval` strings and literal `compile` inputs are inspected recursively, with bounded expansion. Unresolved recognized loader calls or executed code fail with `[dynamic-imports]`; they do not silently pass. Arbitrary user-defined import hooks and runtime code are not executed.
- `no-public-api-sidestep` supports static `__all__` lists/tuples, concatenation, annotations, `+=`, `append` and `extend`. Unresolved dynamic exports are reported as unknown.
- Steiger's `inconsistent-naming` and `import-locality` have no direct equivalent here. Consider Ruff's `N` and `TID` rules for Python naming and relative imports; their behavior is not identical to Steiger's rules.
- Steiger's `insignificant-slice` needs an import graph and is not implemented. The deprecated `processes` layer is not created by this package; omit it from `layers`.
- This package checks Python files and filesystem structure. It does not implement every Steiger rule or every JavaScript-specific convention.

For example, this computed sibling import is rejected:

```python
import importlib

layer = "features"
importlib.import_module(f"src.{layer}.other_slice")
```

If the target comes from runtime input (`importlib.import_module(requested_module)`), validation fails with `[dynamic-imports]` because the target cannot be proven valid. Replace it with an explicit dispatch between statically known imports. The checker is an architecture linter; it does not emulate arbitrary Python execution or serve as an execution sandbox.

See the [upstream FSD plugin changelog](https://github.com/feature-sliced/steiger/blob/master/packages/steiger-plugin-fsd/CHANGELOG.md) for Steiger's release history.

## License
Expand Down
4 changes: 3 additions & 1 deletion README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ extra_rules = [

## Ограничения

- Правила импортов статически разбирают Python, включая относительные импорты, `__init__.py`, импорты внутри функций и ветки `if TYPE_CHECKING:`. Код проекта не исполняется. Динамические импорты (`importlib`, `__import__`, `exec`) и нестандартные загрузчики не разрешаются.
- Правила импортов статически разбирают Python, включая относительные импорты, `__init__.py`, импорты внутри функций и ветки `if TYPE_CHECKING:`. Код проекта не исполняется. Программные импорты через `importlib.import_module`, `importlib.__import__` и встроенный `__import__` тоже проверяются. Поддерживаются алиасы загрузчиков, литералы, переменные с константными значениями, конкатенация, f-строки, `join`, относительные пакеты и `fromlist`. Строки `exec`/`eval` и константные входы `compile` разбираются рекурсивно с ограничением объёма анализа. Неразрешённые вызовы известных загрузчиков и строки исполняемого кода завершаются ошибкой `[dynamic-imports]`, а не пропускаются. Произвольные пользовательские загрузчики и код проекта не исполняются.
- `no-public-api-sidestep` анализирует синтаксис Python и явные списки `__all__`. Динамически собранные экспорты могут давать ложные срабатывания.
- Прямых аналогов Steiger `inconsistent-naming` и `import-locality` здесь нет. Для именования Python и относительных импортов можно использовать правила Ruff `N` и `TID`; их поведение не совпадает полностью с правилами Steiger.
- `insignificant-slice` требует анализа графа импортов и не реализовано. Устаревший слой `processes` пакет не создаёт — не указывайте его в `layers`.
Expand All @@ -94,3 +94,5 @@ extra_rules = [
## Лицензия

MIT. См. [LICENSE](LICENSE).

Вызов `importlib.import_module(f"src.{layer}.tables")` проверяется, если значение `layer` известно. Если имя приходит только во время исполнения, проверка выдаёт `[dynamic-imports]`: замените такой вызов явным выбором между известными импортами. Чекер проверяет архитектуру и не является интерпретатором произвольного Python-кода или средством изоляции исполнения.
2 changes: 1 addition & 1 deletion instructions/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ The `pytest-fsd` library enforces the Feature-Sliced Design (FSD) methodology. I

## Inner Workings

The library acts as a facade over static AST and filesystem checks. Import rules inspect absolute and relative imports, public packages, initializers, local-function imports and `TYPE_CHECKING` branches without executing project code. They raise `AssertionError` under pytest and standalone Python. Dynamic imports and unresolved dynamic exports are outside static resolution; invalid source/configuration fails explicitly.
The library acts as a facade over static AST and filesystem checks. Import rules inspect absolute and relative imports, public packages, initializers, local-function imports and `TYPE_CHECKING` branches without executing project code. They raise `AssertionError` under pytest and standalone Python. Programmatic imports through importlib and __import__, loader aliases, constant expressions, and literal exec/eval/compile code feed the same rules. Unresolved recognized loader calls, executed code, or escaped loaders fail with dynamic-imports. Recursive expansion is bounded. Unresolved dynamic exports, invalid source and invalid configuration fail explicitly. The checker never executes project code or custom import hooks.

Configuration is centralized in `pyproject.toml` under the section `[tool.pytest_fsd]`.

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "pytest-fsd"
version = "0.5.0"
version = "0.6.0"
description = "Validate Feature-Sliced Design architecture in Python projects with pytest"
keywords = ["feature-sliced-design", "fsd", "architecture", "pytest", "python", "steiger"]
readme = "README.md"
Expand Down
Loading
Loading