|
| 1 | +/* |
| 2 | + * Copyright 2021 DiffPlug |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (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 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 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 | +package com.diffplug.spotless.generic; |
| 17 | + |
| 18 | +import java.io.Serializable; |
| 19 | +import java.util.Objects; |
| 20 | + |
| 21 | +import javax.script.ScriptEngine; |
| 22 | +import javax.script.ScriptEngineManager; |
| 23 | + |
| 24 | +import com.diffplug.spotless.FormatterFunc; |
| 25 | +import com.diffplug.spotless.FormatterStep; |
| 26 | +import com.diffplug.spotless.JarState; |
| 27 | +import com.diffplug.spotless.Provisioner; |
| 28 | + |
| 29 | +public final class Jsr223Step { |
| 30 | + // prevent direct instantiation |
| 31 | + private Jsr223Step() {} |
| 32 | + |
| 33 | + public static FormatterStep create(String name, String dependency, CharSequence engine, CharSequence script, Provisioner provisioner) { |
| 34 | + Objects.requireNonNull(name, "name"); |
| 35 | + Objects.requireNonNull(engine, "engine"); |
| 36 | + Objects.requireNonNull(script, "script"); |
| 37 | + return FormatterStep.createLazy(name, |
| 38 | + () -> new State(dependency == null ? null : JarState.from(dependency, provisioner), engine, script), |
| 39 | + State::toFormatter); |
| 40 | + } |
| 41 | + |
| 42 | + private static final class State implements Serializable { |
| 43 | + private static final long serialVersionUID = 1L; |
| 44 | + |
| 45 | + private final JarState jarState; |
| 46 | + private final String engine; |
| 47 | + private final String script; |
| 48 | + |
| 49 | + State(JarState jarState, CharSequence engine, CharSequence script) { |
| 50 | + this.jarState = jarState; |
| 51 | + this.engine = engine.toString(); |
| 52 | + this.script = script.toString(); |
| 53 | + } |
| 54 | + |
| 55 | + FormatterFunc toFormatter() { |
| 56 | + ScriptEngineManager scriptEngineManager; |
| 57 | + if (jarState == null) { |
| 58 | + scriptEngineManager = new ScriptEngineManager(); |
| 59 | + } else { |
| 60 | + scriptEngineManager = new ScriptEngineManager(jarState.getClassLoader()); |
| 61 | + } |
| 62 | + ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(engine); |
| 63 | + |
| 64 | + // evaluate JavaScript code |
| 65 | + return raw -> { |
| 66 | + scriptEngine.put("source", raw); |
| 67 | + return (String) scriptEngine.eval(script); |
| 68 | + }; |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments