3.7. Nesting Scripts: Calling Scripts from Scripts

To properly structure larger scripts it can be helpful to spread functionality over several scripts. The above mentioned scriptService provides simple helper methods to call scripts from within scripts. For this, consider the following script which does nothing but provide two methods

def caesarEncode(k, text) { 
    (text as int[]).collect { it==' ' ? ' ' : (((it & 0x1f) + k - 1).mod(26) + 1 | it & 0xe0) as char }.join()
}   
def caesarDecode(k, text) { caesarEncode(26 - k, text) }

Assume this is stored in a file called lib.groovy. For the interested reader, this is a simple implementation of the Caesar cipher found here: https://www.rosettacode.org/wiki/Caesar_cipher#Groovy (note this should not be used for actual encryption). Now, to load these helper methods we can use the following, which we store in a file called nestingTest.groovy

GLOBALS.exec('lib.groovy')

def plain = 'The quick brown fox jumps over the lazy dog'
def key = 6
def cipher = caesarEncode(key, plain)

tout.println plain
tout.println cipher
tout.println caesarDecode(key, cipher)

If you now run this script you should get the following output

reportserver$ exec nestingTest.groovy
The quick brown fox jumps over the lazy dog
Znk waoiq hxuct lud pasvy ubkx znk rgfe jum
The quick brown fox jumps over the lazy dog

The example above can be found here: https://github.com/infofabrik/reportserver-samples/tree/main/src/net/datenwerke/rs/samples/tools/nesting.

Note you can use relative paths for lib.groovy. For example:

GLOBALS.exec('../crypt/libs/lib.groovy')

or

GLOBALS.exec('libs/lib.groovy')

Besides the simple exec method that we have used above the GLOBALS object provides a second exec method that takes as second parameter an argument string that is passed to the script.