generateHeader<T extends Object?> method

void generateHeader<T extends Object?>(
  1. StringBuffer buffer,
  2. Iterable<ClassModel> models
)

Generate a header for the data classes file.

Implementation

void generateHeader<T extends Object?>(
  final StringBuffer buffer,
  final Iterable<ClassModel> models,
) {
  buffer
    ..writeDoc(
      (<String>['sort_constructors_first']..sort()).join(' '),
      prefix: '// ignore_for_file: ',
      separator: ', ',
    )
    ..writeDoc('')
    ..writeDoc('This file is used for `Data Class` generation.')
    ..writeDoc('')
    ..writeDoc('Modify this file at your own risk!')
    ..writeDoc('')
    ..writeDoc(
      'See: https://pub.dev/packages/generators_lite#data-class-generator',
    )
    ..writeDoc('')
    ..writeImports(<String>[
      ...imports,
      'package:meta/meta.dart',
      if (models.any((final _) => _.toJson)) 'dart:convert',
      if (models.any(
        (final _) => _.fields.any((final _) => _.type.name.startsWith(r'$$')),
      ))
        'package:collection/collection.dart',
    ]);

  if (_isDirectoryExport) {
    /// Handle model relationships with relative imports.
    final Map<String, int> relativeImports = <String, int>{};
    for (final ClassModel model in models) {
      if (model.reference.isEmpty) {
        continue;
      }
      for (final FieldModel field in model.fields) {
        if ((field.reference.isEmpty) ||
            (field.type != FieldType.$object &&
                field.type != FieldType.$$object)) {
          continue;
        }

        Iterable<String> nameParts = model.reference.split('.')..removeLast();
        Iterable<String> parts = field.reference.split('.')..removeLast();
        if (parts.isNotEmpty &&
            !const IterableEquality<String>().equals(parts, nameParts)) {
          while (nameParts.length > 1 &&
              parts.length > 1 &&
              nameParts.first == parts.first) {
            nameParts = nameParts.skip(1);
            parts = parts.skip(1);
          }

          final String path = <String>[
            for (int index = 1; index < nameParts.length; index++) '..',
            ...parts.take(parts.length - 1),
            '${parts.last}$_suffix'
          ].join('/');
          relativeImports["import '$path';"] = nameParts.length;
        }
      }
    }
    if (relativeImports.isNotEmpty) {
      buffer.writeln();
    }
    relativeImports.keys.toList(growable: false)
      ..sort(
        (final String key1, final String key2) {
          final num value1 = relativeImports[key1]!;
          final num value2 = relativeImports[key2]!;
          final int value = (value2 <= 1 ? double.negativeInfinity : value2)
              .compareTo(value1 <= 1 ? double.negativeInfinity : value1);
          return value != 0 ? value : key1.compareTo(key2);
        },
      )
      ..forEach(buffer.writeln);
  }
}