代码之家  ›  专栏  ›  技术社区  ›  Werner Thumann

Gradle:考虑到添加的文件,对输出目录的增量生成支持

  •  1
  • Werner Thumann  · 技术社区  · 6 年前

    年级学生 documentation 告诉这个:

    请注意,如果任务指定了输出目录,则自上次执行任务以来添加到该目录的任何文件都将被忽略,并且不会导致该任务过期。这使得无关的任务可以共享一个输出目录,而不会相互干扰。如果出于某种原因这不是您想要的行为,请考虑使用taskoutputs.uptodatewhen(groovy.lang.closure)

    问题:uptodatewhen的解决方案看起来如何(以便考虑添加的文件)。主要问题是,必须访问生成缓存才能在上次运行任务时检索输出目录内容哈希。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Chriki    6 年前

    不确定我是否正确理解了这个问题,或者您为什么提到构建缓存。我假设您不知道添加的谓词 upToDateWhen() 被认为 此外 其他最新支票,如 TaskOutputs.dir() ?

    执行以下示例任务:

    task foo {
        def outDir = file('out')
        outputs.dir(outDir)
        outputs.upToDateWhen { outDir.listFiles().length == 1 }
        doLast {
           new File(outDir, 'foo.txt') << 'whatever'
        }
    }
    

    只要输出目录中只有一个文件(通过配置 upToDateWhen ) 任务生成的文件( out/foo.txt )如果任务运行后未更改,则该任务将是最新的。如果更改/删除由输出目录中的任务创建的文件,或者向输出目录中添加更多文件,则该任务将再次运行。


    根据评论中的更新问题更新答案:

    task foo {
        def outDir = file('out')
    
        /* sample task action: */
        doFirst {
            def numOutFiles = new Random().nextInt(5)
            for (int i = 1; i <= numOutFiles; i++) {
                new File(outDir, "foo${i}.txt") << 'whatever'
            }
        }
    
        /* up-to-date checking configuration: */
        def counterFile = new File(buildDir, 'counterFile.txt')
        outputs.dir(outDir)
        outputs.upToDateWhen {
            counterFile.isFile() \
              && counterFile.text as Integer == countFiles(outDir)
        }
        doLast {
            counterFile.text = countFiles(outDir)
        }
    }
    
    def countFiles(def dir) {
        def result = 0
        def files = dir.listFiles()
        if (files != null) {
            files.each {
                result++
                if (it.isDirectory()) {
                    result += countFiles(it)
                }
            }
        }
        result
    }
    
    推荐文章