概述

该组件提供了一些实用程序来解释/执行各种实现的一些脚本:groovy 或 beanshell。

依赖声明

    <dependency>
      <groupId>org.apache.maven.shared</groupId>
      <artifactId>maven-script-interpreter</artifactId>
      <version>1.1</version>
    </dependency>

解释 beanshell 脚本

    ScriptInterpreter interpreter = new BeanShellScriptInterpreter();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    interpreter.evaluateScript( script content, extra classPath entries,
                              Map<String, ? extends Object> globalVariables, new PrintStream( out ) );
    out.toString() returns script output

解释一个 groovy 脚本

    ScriptInterpreter interpreter = new GroovyScriptInterpreter();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    interpreter.evaluateScript( script content, extra classPath entries,
                              Map<String, ? extends Object> globalVariables, new PrintStream( out ) );
    out.toString() returns script output

使用 ScriptRunner

ScriptRunner 类将根据支持的扩展名(.bsh、.groovy)检测要运行的脚本文件。

此类将在提供的目录中搜索具有提供的文件名和支持的扩展名的脚本。

有关运行方法,请参见javadoc

    SystemStreamLog systemStreamLog = new SystemStreamLog();

    ScriptRunner scriptRunner = new ScriptRunner( systemStreamLog );
    scriptRunner.run( "test", new File( "src/test/resources/bsh-test" ), "verify", buildContext(),
                      new FileLogger( logFile ), "foo", true );

全局变量

默认情况下,您的脚本将具有两个全局变量:

  • basedir:脚本的基本目录
  • context:构建上下文(见下文)

您可以添加更多全局变量。

    SystemStreamLog systemStreamLog = new SystemStreamLog();

    ScriptRunner scriptRunner = new ScriptRunner( systemStreamLog );
    scriptRunner.setGlobalVariable( name, value );

构建上下文

您可以使用类型为Map<String, ? 扩展对象>上下文

    Map<String, Object> context = new HashMap<String, Object>();
    context.put( "foo", "bar" );
    return context;

    // in your bsh script
    String value = context.get( "foo" );
    value will be "bar"

    // in your groovy script
    context.get("foo")

额外的类路径条目

您可以为脚本执行添加一些额外的类路径条目

    SystemStreamLog systemStreamLog = new SystemStreamLog();

    List<String> classpathEntries = list of jar paths
    ScriptRunner scriptRunner = new ScriptRunner( systemStreamLog );
    scriptRunner.setClassPath( classpathEntries );
    scriptRunner.run( "test", new File( "src/test/resources/bsh-test" ), "verify", buildContext(),
                      new FileLogger( logFile ), "foo", true );