1

试图从 Gradle 调用 Saga Javascript 代码覆盖率。在玩了很久之后,我终于可以让它工作了。但是,我是 gradle 新手,不知道我的做法是否最有意义!似乎有很多方法可以做到这一点,所以我想我会在这里发布我所做的事情,希望我可以了解这种方式是否可行或是否有更好的方法。

从 maven Central 下载 saga-core 后,发现没有 Java“main”。所以我认为我不能轻易使用 JavaExec。在我看来,我需要创建一个 Java 对象、设置一些参数并调用提供的“运行”方法。

这是我最终得到的最终 build.gradle:

apply plugin: 'groovy'

buildscript {    
    repositories {
        mavenCentral()
    }

    dependencies {
        // add the jar file withe the code you want to execute to gradle's classpath
        classpath 'com.github.timurstrekalov:saga-core:1.1.2'
    }
}

configurations {
    compile
    codeCoverageTask
}

dependencies {
    groovy localGroovy()
    codeCoverageTask 'com.github.timurstrekalov:saga-core:1.1.2'
}

// I thought this was simple and made sense to be co-located here rather than
// another file...
// getting the imports to compile requires adding the "buildscript" section above
import java.io.File
import com.github.timurstrekalov.saga.core.CoverageGenerator

class SagaCoverageTask extends DefaultTask {
    def outputDirectory
    def baseDirectory
    def includes = 'my_includesPattern_here'
    def excludes = 'my_excludesPattern_here'
    def noInstrumentPatterns = [ 'my_noIntrumentPatterns_here' ]

    @TaskAction
    def runCoverage() {
        // check these were set correctly!
        println outputDirectory
        println 'baseDir' + baseDirectory

        // create an instance of the object
        CoverageGenerator generator = new CoverageGenerator(baseDirectory, includes, excludes, outputDirectory)   
        generator.noInstrumentPatterns = noInstrumentPatterns
        // there are params, but they would be handled in the same way if needed
        generator.run()   // invoke the arbitrary method
    }
}

task genCodeCoverage(type: SagaCoverageTask)  {
    // needed the values of task properties, so these are set here
    outputDirectory = new File('' + reportsDir + '/coverage')
    baseDirectory = new File('' + projectDir + '/src')   
}
4

1 回答 1

2

看起来是一个不错的开始。通常应该使用该project.file()方法创建文件对象,因为它比处理相对路径更好new File()(尽管在这种特殊情况下这不是问题)。例如:file("$reportsDir/coverage")

如果任务类变得更大或者您想在项目/构建中重用它,您应该将它移到其他地方(例如移入buildSrc)并添加一些测试覆盖率。

通过使用@InputDirectory、@OutputDirectory 等注释任务类属性,您可以使其仅在某些输入已更改或先前生成的输出不再可用时才运行。这可以加快构建速度。

于 2012-08-22T12:22:49.807 回答