3

I have some library scripts: lib1.groovy:

def a(){
}

lib2.groovy:

def b(){
}

lib3.groovy:

def c(){
}

and want to use them in another scripts : conf.groovy:

a()
b()
c()

conf.groovy is configured by user and he is not aware of my background lib scripts! he is only aware of provided methods/task : a(), b(), c(). actually i created lib scripts for user simplicity.

Is there any way to include all scripts in a lib directory (scripts lib1, lib2m ,lib3) into conf.groovy script(s)? Or, is there any alternative mechanism to to that? I am trying to run conf.groovy in a runner script/java class (using groovy shell, loader o script engine).

main.groovy:

File currentDir = new File(".")
String[] roots = {currentDir.getAbsolutePath()}
GroovyScriptEngine gse = new GroovyScriptEngine(roots)
gse.run('confg.groovy', binding)
Sam
  • 55
  • 1
  • 7
  • Possible duplicate of [Load script from groovy script](https://stackoverflow.com/questions/9004303/load-script-from-groovy-script) – Szymon Stepniak Jul 08 '17 at 07:29
  • Thanks Szymon! but I do not want to insert def script = new GroovyScriptEngine( '.' ).with { loadScriptByName( 'lib1.groovy' ) } this.metaClass.mixin script in my conf.groovy file!. conf.groovy is a script which i am giving to user to config his tasks and i do not want user get involved with this. Actually I have another script(main.groovy) that runs confg.groovy (using GroovyShell, Loader or ScriptEngine). i edited the question to be more clear. – Sam Jul 08 '17 at 07:46
  • you have c() in lib2 and in lib3. Which one should be called ? – daggett Jul 09 '17 at 21:03
  • name corrected! it a() , b() and c()! – Sam Jul 11 '17 at 09:48

1 Answers1

3

v1

use import static and static methods declaration:

Lib1.groovy

static def f3(){
    println 'f3'
}
static def f4(){
    println 'f4'
}

Conf.groovy

import static Lib1.* /*Lib1 must be in classpath*/

f3()
f4()

v2

or another idea (but not sure you need this complexity): use GroovyShell to parse all lib scripts. from each lib script class get all non-standard declared methods, convert them into MethodClosure and pass them as binding into conf.groovy script. And a lot of questions here like: what to do if method declared in several Libs...

import org.codehaus.groovy.runtime.MethodClosure
def shell = new GroovyShell()
def binding=[:]
//cycle here through all lib scripts and add methods into binding
def script = shell.parse( new File("/11/tmp/bbb/Lib1.groovy") )
binding << script.getClass().getDeclaredMethods().findAll{!it.name.matches('^\\$.*|main|run$')}.collectEntries{[it.name,new MethodClosure(script,it.name)]}

//run conf script
def confScript = shell.parse( new File("/11/tmp/bbb/Conf.groovy") )
confScript.setBinding(new Binding(binding))
confScript.run()

Lib1.groovy

def f3(){
    println 'f3'
}
def f4(){
    println 'f4'
}

Conf.groovy

f3()
f4()
daggett
  • 26,404
  • 3
  • 40
  • 56