groovy集成ant
CRC最近在我的文章《 从Groovy执行蚂蚁构建文件目标》的评论部分中询问:“我使用了您的脚本,它似乎可以正常工作,但在控制台上看不到任何输出(我正在调用echo任务。在build.xml中),为什么?” 这是一个很好的问题,我认为在帖子中比在评论中更好地回答。
在developerWorks文章“以编程方式调用Apache Ant”中 , Nell Gawor解释了在命令行中执行的构建中访问Ant的echo任务时,要看到通常在控制台上看到的输出,需要做些什么:命令行,输出自动进入控制台。 但是[使用Project.executeTarget(String)时 ]必须明确。 您需要添加一个BuildLogger并将其添加为侦听器,以便它将接收到在构建过程中发生的事件的通知。”
Gawor在她的文章的“记录器”部分中提到的BuildLogger是Ant对侦听器和记录器的支持的一部分。 在她的文章(以及我的文章)中,使用DefaultLogger是因为它很简单。 DefaultLogger实现BuildLogger并提供方法setOutputPrintStream(PrintStream)和setErrorPrintStream(PrintStream) 。 正是这两个“设置”方法使一个方法可以将标准输出和标准错误分别与Ant Project实例相关联。
下面的代码清单显示了经过修改的Groovy脚本,该脚本将运行提供的Ant目标,并将被调用的Ant目标(例如那些采用echo任务的目标)的输出打印到标准输出。
#!/usr/bin/env groovy
/**
* applyBuildFileInGroovy2.groovy
*
* This is an example of executing an Ant build file from Groovy code using
* Ant's Project and ProjectHelper classes. The only difference between this and
* applyBuildFileInGroovy.groovy is that this version will write to standard
* output and standard error for invoked Ant targets as appropriate.
*
* Usage: applyBuildFileInGroovy.groovy _buildFilePathName_ [target1] [target2] ... [targetn]
*
* where _buildFilePathName_ is the path and file name of the build file to be
* used by this script and zero or more targets in that build file can be
* specified (default target used if no targets specified).
*/
import org.apache.tools.ant.DefaultLogger
import org.apache.tools.ant.Project
import org.apache.tools.ant.ProjectHelper
if (args.length < 1)
{
println "You must provide an Ant build file as the first parameter."
System.exit(-1)
}
def antBuildFilePathAndName = args[0]
def antFile = new File(antBuildFilePathAndName)
def project = new Project()
def consoleLogger = new DefaultLogger()
consoleLogger.errorPrintStream = System.err
consoleLogger.outputPrintStream = System.out
consoleLogger.messageOutputLevel = Project.MSG_INFO
project.addBuildListener(consoleLogger);
project.init()
ProjectHelper.projectHelper.parse(project, antFile)
if (args.length > 1)
{
def antTargets = args - antBuildFilePathAndName
antTargets.each
{
project.executeTarget(it)
}
}
else
{
// use default target because no targets were specified on the command line
project.executeTarget(project.defaultTarget);
}
在上面的代码清单中,添加的与该帖子相关的行是第17行(导入DefaultLogger)和第31-34行(设置DefaultLogger的标准输出流,标准错误流和消息输出级别)。 可用的消息输出级别在Project类中定义为常量整数MSG_DEBUG,MSG_ERR,MSG_INFO,MSG_VERBOSE和MSG_WARN。 这些在相应的Javadoc注释中进行了描述,在echo任务文档中也进行了描述。
现在运行增强的脚本不仅将执行所调用的Ant目标的逻辑行为,而且还将这些任务的输出定向到标准输出和标准错误。 感谢CRC提出了一个有趣的问题,并感谢Nell Gawor的明确解释。
翻译自: https://www.javacodegeeks.com/2013/12/listening-and-logging-ant-output-in-groovy.html
groovy集成ant