Skip to content

Commit

Permalink
Remove String feature flags for LaunchDarkly (#33)
Browse files Browse the repository at this point in the history
* Remove String feature flags for LaunchDarkly

* Apply suggestions from code review

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
  • Loading branch information
timtebeek and github-actions[bot] authored Sep 12, 2024
1 parent 8033bcc commit 2c9a406
Show file tree
Hide file tree
Showing 6 changed files with 321 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
doAfterVisit(new SimplifyConstantIfBranchExecution().getVisitor());
doAfterVisit(new RemoveUnusedLocalVariables(null).getVisitor());
doAfterVisit(new RemoveUnusedPrivateFields().getVisitor());
return new J.Literal(Tree.randomId(), Space.SINGLE_SPACE, Markers.EMPTY, replacementValue, String.valueOf(replacementValue), null, JavaType.Primitive.Boolean);
J.Literal literal = new J.Literal(Tree.randomId(), Space.SINGLE_SPACE, Markers.EMPTY, replacementValue, String.valueOf(replacementValue), null, JavaType.Primitive.Boolean);
return literal.withPrefix(mi.getPrefix());
}
return mi;
}
Expand Down
90 changes: 90 additions & 0 deletions src/main/java/org/openrewrite/featureflags/RemoveStringFlag.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
package org.openrewrite.featureflags;

import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.analysis.constantfold.ConstantFold;
import org.openrewrite.analysis.util.CursorUtil;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Space;
import org.openrewrite.marker.Markers;
import org.openrewrite.staticanalysis.RemoveUnusedLocalVariables;
import org.openrewrite.staticanalysis.RemoveUnusedPrivateFields;
import org.openrewrite.staticanalysis.SimplifyConstantIfBranchExecution;

@Value
@EqualsAndHashCode(callSuper = false)
public class RemoveStringFlag extends Recipe {

@Override
public String getDisplayName() {
return "Remove a boolean feature flag for feature key";
}

@Override
public String getDescription() {
return "Replace method invocations for feature key with value, and simplify constant if branch execution.";
}

@Option(displayName = "Method pattern",
description = "A method pattern to match against. The first argument must be the feature key as `String`.",
example = "dev.openfeature.sdk.Client getBooleanValue(String, Boolean)")
String methodPattern;

@Option(displayName = "Feature flag key",
description = "The key of the feature flag to remove.",
example = "flag-key-123abc")
String featureKey;

@Option(displayName = "Replacement value",
description = "The value to replace the feature flag check with.",
example = "topic-456")
String replacementValue;

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
final MethodMatcher methodMatcher = new MethodMatcher(methodPattern, true);
JavaVisitor<ExecutionContext> visitor = new JavaVisitor<ExecutionContext>() {
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
if (methodMatcher.matches(mi) && isFeatureKey(mi.getArguments().get(0))) {
doAfterVisit(new SimplifyConstantIfBranchExecution().getVisitor());
doAfterVisit(new RemoveUnusedLocalVariables(null).getVisitor());
doAfterVisit(new RemoveUnusedPrivateFields().getVisitor());
J.Literal literal = new J.Literal(Tree.randomId(), Space.SINGLE_SPACE, Markers.EMPTY, replacementValue, '"' + replacementValue + '"', null, JavaType.Primitive.String);
return literal.withPrefix(mi.getPrefix());
}
return mi;
}

private boolean isFeatureKey(Expression firstArgument) {
return CursorUtil.findCursorForTree(getCursor(), firstArgument)
.bind(c -> ConstantFold.findConstantLiteralValue(c, String.class))
.map(featureKey::equals)
.orSome(false);
}
};
return Preconditions.check(new UsesMethod<>(methodMatcher), visitor);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
package org.openrewrite.featureflags.launchdarkly;

import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.Option;
import org.openrewrite.Recipe;
import org.openrewrite.featureflags.RemoveBooleanFlag;
import org.openrewrite.featureflags.RemoveStringFlag;

import java.util.Collections;
import java.util.List;

@Value
@EqualsAndHashCode(callSuper = false)
public class RemoveStringVariation extends Recipe {

@Override
public String getDisplayName() {
return "Remove LaunchDarkly's `boolVariation` for feature key";
}

@Override
public String getDescription() {
return "Replace `boolVariation` invocations for feature key with value, and simplify constant if branch execution.";
}

@Option(displayName = "Feature flag key",
description = "The key of the feature flag to remove.",
example = "flag-key-123abc")
String featureKey;

@Option(displayName = "Replacement value",
description = "The value to replace the feature flag check with.",
example = "topic-456")
String replacementValue;

@Override
public List<Recipe> getRecipeList() {
return Collections.singletonList(new RemoveStringFlag(
"com.launchdarkly.sdk.server.LDClient stringVariation(String, com.launchdarkly.sdk.*, String)",
featureKey, replacementValue));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package org.openrewrite.featureflags;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.Issue;
import org.openrewrite.test.RewriteTest;
import org.openrewrite.test.SourceSpec;
Expand All @@ -25,6 +26,7 @@
class RemoveBooleanFlagTest implements RewriteTest {

@Test
@DocumentExample
void customMethodPatternForWrapper() {
rewriteRun(
spec -> spec.recipe(new RemoveBooleanFlag("com.acme.bank.CustomLaunchDarklyWrapper featureFlagEnabled(String, boolean)", "flag-key-123abc", true)),
Expand Down
104 changes: 104 additions & 0 deletions src/test/java/org/openrewrite/featureflags/RemoveStringFlagTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
package org.openrewrite.featureflags;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;

class RemoveStringFlagTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new RemoveStringFlag("com.acme.bank.InHouseFF getStringFeatureFlagValue(String, String)", "flag-key-123abc", "topic-456"))
// language=java
.parser(JavaParser.fromJavaVersion().dependsOn(
"""
package com.acme.bank;
public class InHouseFF {
public String getStringFeatureFlagValue(String key, String fallback) {
return fallback;
}
}
"""
));
}

@DocumentExample
@Test
void removeStringFeatureFlag() {
rewriteRun(
spec -> spec.recipe(new RemoveStringFlag("com.acme.bank.InHouseFF getStringFeatureFlagValue(String, String)", "flag-key-123abc", "topic-456")),
// language=java
java(
"""
import com.acme.bank.InHouseFF;
class Foo {
private InHouseFF inHouseFF = new InHouseFF();
void bar() {
String topic = inHouseFF.getStringFeatureFlagValue("flag-key-123abc", "topic-123");
System.out.println("Publishing to topic: " + topic);
}
}
""",
"""
class Foo {
void bar() {
String topic = "topic-456";
System.out.println("Publishing to topic: " + topic);
}
}
"""
)
);
}

@Disabled("This test is disabled because it is not yet implemented.")
@Test
void removeEqualsComparison() {
rewriteRun(
spec -> spec.recipe(new RemoveStringFlag("com.acme.bank.InHouseFF getStringFeatureFlagValue(String, String)", "flag-key-123abc", "topic-456")),
// language=java
java(
"""
import com.acme.bank.InHouseFF;
class Foo {
private InHouseFF inHouseFF = new InHouseFF();
void bar() {
if ("topic-456".equals(inHouseFF.getStringFeatureFlagValue("flag-key-123abc", "topic-123"))) {
// Application code to show the feature
System.out.println("Feature is on");
}
}
}
""",
"""
class Foo {
void bar() {
// Application code to show the feature
System.out.println("Feature is on");
}
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
package org.openrewrite.featureflags.launchdarkly;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;

class RemoveStringVariationTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new RemoveStringVariation("flag-key-123abc", "topic-456"))
.parser(JavaParser.fromJavaVersion()
.classpathFromResources(new InMemoryExecutionContext(), "launchdarkly-java-server-sdk-6"));
}

@Test
@DocumentExample
void replaceStringVariation() {
rewriteRun(
// language=java
java(
"""
import com.launchdarkly.sdk.LDContext;
import com.launchdarkly.sdk.server.LDClient;
class Foo {
private LDClient client = new LDClient("sdk-key-123abc");
void bar() {
LDContext context = null;
String topic = client.stringVariation("flag-key-123abc", context, "topic-123");
System.out.println("Publishing to topic: " + topic);
}
}
""",
"""
class Foo {
void bar() {
String topic = "topic-456";
System.out.println("Publishing to topic: " + topic);
}
}
"""
)
);
}
}

0 comments on commit 2c9a406

Please sign in to comment.