001package net.filebot.cli; 002 003import static net.filebot.util.FileUtilities.*; 004 005import java.io.File; 006import java.io.IOException; 007 008import javax.script.ScriptException; 009 010import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; 011 012import groovy.lang.Closure; 013import net.filebot.RenameAction; 014 015public class GroovyRenameAction implements RenameAction { 016 017 private final Closure<?> closure; 018 019 public GroovyRenameAction(String script) { 020 try { 021 this.closure = compile(script); 022 } catch (ScriptException e) { 023 throw new IllegalArgumentException(e); 024 } 025 } 026 027 public GroovyRenameAction(File script) { 028 try { 029 this.closure = compile(readTextFile(script)); 030 } catch (ScriptException | IOException e) { 031 throw new IllegalArgumentException(e); 032 } 033 } 034 035 public GroovyRenameAction(Closure<?> closure) { 036 this.closure = closure; 037 } 038 039 @Override 040 public File rename(File from, File to) throws Exception { 041 Object value = closure.call(from, to); 042 043 // must return File object, so we try the result of the closure, but if it's not a File we just return the original destination parameter 044 return value instanceof File ? (File) value : null; 045 } 046 047 @Override 048 public boolean canRevert() { 049 return false; 050 } 051 052 @Override 053 public String toString() { 054 return "CLOSURE"; 055 } 056 057 public static Closure<?> compile(String script) throws ScriptException { 058 return (Closure) DefaultTypeTransformation.castToType(ScriptShell.createScriptEngine().eval(script), Closure.class); 059 } 060 061}