openrewrite / rewrite

Automated mass refactoring of source code.
https://docs.openrewrite.org
Apache License 2.0
2.3k stars 342 forks source link

[Feature Request] Being able to inspect dependency jars and .class files #2311

Closed peterphan closed 1 year ago

peterphan commented 2 years ago

Use Case

We use an internal experimentation platform for A/B testing that often has code like

if (experimentIsOn("my_experiment_key")) {
  doTreatmentFlow();
} else {
  doControlFlow();
}

We want to create a recipe to automatically clean up stale experiments, so being able to refactor the code such that it becomes

doTreatmentFlow();

Problem

In order to do this, we need to be able to detect that the treatment/experiment key being passed in is exactly my_experiment_key. This could be a string literal, which is easy to handle, however, if it's a constant that is defined in an external dependency through the classpath. E.g.

// Class processed from the classpath
class Constants {
  public static final String EXPERIMENT_KEY = "my_experiment_key";
}

// Class we want to modify, but we cannot resolve Constants.EXPERIMENT_KEY
if (experimentIsOn(Constants.EXPERIMENT_KEY)) {
  doTreatmentFlow();
} else {
  doControlFlow();
}

then we currently have no means to resolve this value.

sambsnyd commented 2 years ago

Note that doing bytecode analysis of the classpath represents a substantial engineering effort, unlikely to come to fruition anytime soon. But it would be neat, I agree.

kunalkandekar commented 2 years ago

Cross-posting from internal discussion: Another option would be to use reflection where possible. For the example above, if we cannot resolve the constant in any of the current source files, we could load the classpath into a ClassLoader and use reflection to find the appropriate class and its constants e.g. like this.

This approach is very specific to the example use-case, and may not scale to broader use-cases so might not belong in OpenRewrite itself, but it may be a useful workaround for users.

tkvangorder commented 1 year ago

This may be a feature we can explore much further down the road when the SaaS supports multi-repository recipes. It is unlikely that work will be done on this in the near term.