rharter / auto-value-gson

AutoValue Extension to add Gson De/Serializer support
Apache License 2.0
607 stars 103 forks source link

Non-deterministic generation of TypeAdapterFactory #257

Closed prempalsingh closed 3 years ago

prempalsingh commented 3 years ago

auto-value-gson version - 1.3.1 kotlin version - 1.4.21

When the project has two AutoValue classes with the same name but in different packages, the generated TypeAdapterFactory is not deterministic which creates a cache miss in Gradle because of different file contents.

Following are the two different generated TypeAdapterFactory with the same source -

import com.example.subs.TrayData;

final class AutoValueGson_HSTypeAdapterFactory extends HSTypeAdapterFactory {
  @Override
  @SuppressWarnings("unchecked")
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<?> rawType = type.getRawType();
    if (TrayData.class.isAssignableFrom(rawType)) {
      return (TypeAdapter<T>) TrayData.typeAdapter(gson);
    } else if (com.example.models.TrayData.class.isAssignableFrom(rawType)) {
      return (TypeAdapter<T>) com.example.models.TrayData.typeAdapter(gson);
    } else {
      return null;
    }  
  }
}
import com.example.models.TrayData;

final class AutoValueGson_HSTypeAdapterFactory extends HSTypeAdapterFactory {
  @Override
  @SuppressWarnings("unchecked")
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<?> rawType = type.getRawType();
    if (TrayData.class.isAssignableFrom(rawType)) {
      return (TypeAdapter<T>) TrayData.typeAdapter(gson);
    } else if (com.example.subs.TrayData.class.isAssignableFrom(rawType)) {
      return (TypeAdapter<T>) com.example.subs.TrayData.typeAdapter(gson);
    } else {
      return null;
    }  
  }
}
prempalsingh commented 3 years ago

My hunch is that in AutoValueGsonAdapterFactoryProcessor when sorting the elements, we are not considering the package name so in case of same class name, the final order will depend on the order in which those elements were initially present which wouldn't always be the same(?) https://github.com/rharter/auto-value-gson/blob/063c8289367e08e1b1fda6d2be912fada60108c6/auto-value-gson-factory/src/main/java/com/ryanharter/auto/value/gson/factory/AutoValueGsonAdapterFactoryProcessor.java#L95

ZacSweers commented 3 years ago

Good find. Apologies for the delay, we'd be open to a PR for this if you're interested