|
| 1 | +/* |
| 2 | + * Copyright 2025 the original author or authors. |
| 3 | + * <p> |
| 4 | + * Licensed under the Moderne Source Available License (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * <p> |
| 8 | + * https://docs.moderne.io/licensing/moderne-source-available-license |
| 9 | + * <p> |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +import {createDraft, finishDraft} from "immer"; |
| 17 | +import {emptyMarkers, ExecutionContext, Option, randomId, Recipe, TreeVisitor} from "@openrewrite/rewrite"; |
| 18 | +import {JavaScriptVisitor} from "@openrewrite/rewrite/javascript"; |
| 19 | +import {J, singleSpace, Type} from "@openrewrite/rewrite/java"; |
| 20 | + |
| 21 | +export class ReplaceAssignment extends Recipe { |
| 22 | + name = "org.openrewrite.example.javascript.replace-assignment" |
| 23 | + displayName = "Replace assignment with env var value"; |
| 24 | + description = "Replaces the assignment of a variable with the value of an environment variable."; |
| 25 | + |
| 26 | + @Option({ |
| 27 | + displayName: "Environment Variable Name", |
| 28 | + description: "The name of the environment variable whose value will replace the variable assignment.", |
| 29 | + }) |
| 30 | + variable!: string; |
| 31 | + |
| 32 | + constructor(options: { variable: string }) { |
| 33 | + super(options); |
| 34 | + } |
| 35 | + |
| 36 | + async editor(): Promise<TreeVisitor<any, ExecutionContext>> { |
| 37 | + const envVar = this.variable; |
| 38 | + const envVarValue = "'" + process.env[envVar] + "'"; |
| 39 | + return new class extends JavaScriptVisitor<ExecutionContext> { |
| 40 | + protected async visitVariable(variable: J.VariableDeclarations.NamedVariable, c: ExecutionContext): Promise<J | undefined> { |
| 41 | + if ((variable.initializer!.element as J.Literal).valueSource === envVarValue) { |
| 42 | + return super.visitVariable(variable, c); |
| 43 | + } |
| 44 | + let draft = createDraft(variable); |
| 45 | + draft.initializer = { |
| 46 | + kind: J.Kind.LeftPadded, |
| 47 | + markers: emptyMarkers, |
| 48 | + element: { |
| 49 | + kind: J.Kind.Literal, |
| 50 | + id: randomId(), |
| 51 | + prefix: singleSpace, |
| 52 | + markers: emptyMarkers, |
| 53 | + valueSource: envVarValue, |
| 54 | + type: Type.Primitive.String, |
| 55 | + }, |
| 56 | + before: singleSpace, |
| 57 | + }; |
| 58 | + return finishDraft(draft); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments