Skip to content

Make it possible to know if the current target class/enum/function is from the current file #21

Description

@mtnbnz

Trying to implement my own version of copyWith from the freezed package, I have found the need to know if the current target provided in the apply method is from the target file or not and I can't seem to find a way to do so.

To elaborate, suppose I have the following:

person.dart:

@dataClass
class Person {
  @override
  final String name;
  @override
  final Pet pet;

  const Person({ required this.name, required this.pet });
}

pet.dart:

@dataClass
class Pet {
  @override
  final String name;
  @override
  final Animal type;

  const Pet({ required this.name, required this.type });
}

I want to generate a copyWith on both classes. But I also want to support deep copying like freezed does it:

const p1 = Person(name: 'Bob', pet: Pet(name: 'Max', type: .dog));
final p2 = p1.copyWith.pet(name: 'Kitty', type: .cat);

I would need to use CodeGen(discoveryMode: .recursiveImports) (the default) in order to know that my generated $PersonCopyWith class should also include a pet field to make deep copies since Pet is also annotated with my dataClass annotation.

When my DataClass annotation is processing the person.dart file, its apply method is called twice, once with the Person class and a second time with the Pet class as the target parameter. All good, this is needed to be able to generate the deep copy functionality for the Person class.

However, when it gets called the second time with the Pet class as the target, I have no way of knowing if that class is from the current file or not, so I end up doing code generation for its mixin code twice and I now have a person.g.dart containing generated code for the Pet class which I don't want since that code also ends up in pet.g.dart once code generation is performed for that file.

It doesn't seem like that big of a deal at first, I can just add a output.ignoreForFile.add('unused_element') in my code generation and ignore the duplicated code.
But if the Pet class has a field that comes from an import my person.dart file now also needs that import as well since person.g.dart contains references to that type.

Is there maybe a way to solve this problem already that I have missed?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions