Files
cherrypick/cherrypick_generator/lib/module_generator.dart

94 lines
4.9 KiB
Dart
Raw Normal View History

2025-05-18 15:43:02 +03:00
//
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2025-08-08 23:24:05 +03:00
// https://www.apache.org/licenses/LICENSE-2.0
2025-05-18 15:43:02 +03:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
2025-05-17 00:34:56 +03:00
import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
2025-05-21 15:50:24 +03:00
import 'src/generated_class.dart';
2025-05-22 16:05:09 +03:00
/// ---------------------------------------------------------------------------
/// ModuleGenerator for code generation of dependency-injected modules.
2025-05-17 22:29:37 +03:00
///
2025-05-22 16:05:09 +03:00
/// ENGLISH
/// This generator scans for Dart classes annotated with `@module()` and
/// automatically generates boilerplate code for dependency injection
/// (DI) based on the public methods in those classes. Each method can be
/// annotated to describe how an object should be provided to the DI container.
/// The generated code registers those methods as bindings. This automates the
/// creation of factories, singletons, and named instances, reducing repetitive
/// manual code.
2025-05-20 19:50:13 +03:00
///
2025-05-22 16:05:09 +03:00
/// RUSSIAN
/// Генератор зависимостей для DI-контейнера на основе аннотаций.
2025-05-20 19:50:13 +03:00
/// Данный генератор автоматически создаёт код для внедрения зависимостей (DI)
/// на основе аннотаций в вашем исходном коде. Когда вы отмечаете класс
/// аннотацией `@module()`, этот генератор обработает все его публичные методы
/// и автоматически сгенерирует класс с биндингами (регистрациями зависимостей)
/// для DI-контейнера. Это избавляет от написания однообразного шаблонного кода.
2025-05-22 16:05:09 +03:00
/// ---------------------------------------------------------------------------
2025-05-17 00:34:56 +03:00
class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
2025-05-22 16:05:09 +03:00
/// -------------------------------------------------------------------------
/// ENGLISH
/// Generates the Dart source for a class marked with the `@module()` annotation.
/// - [element]: the original Dart class element.
/// - [annotation]: the annotation parameters (not usually used here).
/// - [buildStep]: the current build step info.
2025-05-20 19:50:13 +03:00
///
2025-05-22 16:05:09 +03:00
/// RUSSIAN
/// Генерирует исходный код для класса-модуля с аннотацией `@module()`.
2025-05-20 19:50:13 +03:00
/// [element] — исходный класс, помеченный аннотацией.
/// [annotation] — значения параметров аннотации.
/// [buildStep] — информация о текущем шаге генерации.
2025-05-22 16:05:09 +03:00
/// -------------------------------------------------------------------------
2025-05-17 00:34:56 +03:00
@override
String generateForAnnotatedElement(
Element element,
ConstantReader annotation,
BuildStep buildStep,
) {
2025-05-22 16:05:09 +03:00
// Only classes are supported for @module() annotation
// Обрабатываются только классы (другие элементы — ошибка)
2025-05-17 00:34:56 +03:00
if (element is! ClassElement) {
throw InvalidGenerationSourceError(
2025-05-22 16:05:09 +03:00
'@module() can only be applied to classes. / @module() может быть применён только к классам.',
2025-05-17 00:34:56 +03:00
element: element,
);
}
2025-05-17 22:29:37 +03:00
2025-05-17 00:34:56 +03:00
final classElement = element;
2025-05-17 22:29:37 +03:00
2025-05-22 16:05:09 +03:00
// Build a representation of the generated bindings based on class methods /
2025-05-20 19:50:13 +03:00
// Создаёт объект, описывающий, какие биндинги нужно сгенерировать на основании методов класса
2025-05-21 15:50:24 +03:00
final generatedClass = GeneratedClass.fromClassElement(classElement);
2025-05-20 19:50:13 +03:00
2025-05-22 16:05:09 +03:00
// Generate the resulting Dart code / Генерирует итоговый Dart-код
2025-05-20 19:50:13 +03:00
return generatedClass.generate();
}
}
2025-05-22 16:05:09 +03:00
/// ---------------------------------------------------------------------------
/// ENGLISH
/// Entry point for build_runner. Returns a Builder used to generate code for
/// every file with a @module() annotation.
2025-05-20 19:50:13 +03:00
///
2025-05-22 16:05:09 +03:00
/// RUSSIAN
2025-05-20 19:50:13 +03:00
/// Точка входа для генератора build_runner.
/// Возвращает Builder, используемый build_runner для генерации кода для всех
/// файлов, где встречается @module().
2025-05-22 16:05:09 +03:00
/// ---------------------------------------------------------------------------
2025-05-17 00:34:56 +03:00
Builder moduleBuilder(BuilderOptions options) =>
2025-05-23 12:21:23 +03:00
PartBuilder([ModuleGenerator()], '.module.cherrypick.g.dart');