如何在Gradle中检查文件的当前内容

时间:2018-02-22 02:27:01

标签: file gradle order-of-execution

首先和formost ......我是Gradle的新手。话虽如此,我它。不幸的是,我遇到了麻烦。我有一系列任务是部署过程的一部分。一个(buildProject)调用一个shell脚本,作为其过程的一部分,使用新的"版本"更新REVISION文件。之后,调用deployToRemote任务将最新版本部署到服务器。它调用getCurrentVersionREVISION文件中读取最新版本。所有这些任务概述如下。问题是,尽管有getLatestVersion个正确的语句,mustRunAfter似乎被称为 first ,因为它始终读入" PRE" buildProject文件中列出的REVISION版本。如何在 getLatestVersion运行后确保buildProject读取文件

以下是任务:

buildProject:

task buildProject(type:Exec) {
  def command = ['./make-release', '-f']
  if (deployEnvironment != 'stage') {
    command = ['./make-release', "-e ${deployEnvironment}"]
  }

  commandLine command
}

deployToRemote

task deployToRemote(dependsOn: 'getCurrentVersion') {
  doLast {
    def version = tasks.getCurrentVersion.hash()
    println "Using version ${version}"
    println "Using user ${webhostUser}"
    println "Using host ${webhostUrl}"
    ssh.run {
      session(remotes.webhost) {
        put from: "dist/project-${version}.tar.gz", into: '/srv/staging/'
        execute "cd /srv/staging; ./manual_install.sh ${version}"
      }
    }
  }
}

getCurrentVersion

task getCurrentVersion {
  def line
  new File("REVISION").withReader { line = it.readLine() }
  ext.hash = {
    line
  }
}

我的build.gradle文件最后有这个:

deployToRemote.mustRunAfter buildProject
getCurrentVersion.mustRunAfter buildProject

REVISION文件看起来像这样;

1196.dev10
919b642fd5ca5037a437dac28e2cfac0ea18ceed
dev

1 个答案:

答案 0 :(得分:1)

Gradle build three phases:初始化,配置和执行。

您遇到的问题是getCurrentVersion中的代码是在配置阶段执行的。在配置阶段,任务中的代码按其定义的顺序执行,并且不考虑依赖性。

考虑这个例子:

task second(dependsOn: 'first') {
    println 'second: this is executed during the configuration phase.'
    doLast {
      println 'second: This is executed during the execution phase.'
    }
}

task first {
    println 'first: this is executed during the configuration phase.'
    doLast {
      println 'first: This is executed during the execution phase.'
    }
}

second.mustRunAfter first

如果执行gradle -q second,您将获得:

second: this is executed during the configuration phase.
first: this is executed during the configuration phase.
first: This is executed during the execution phase.
second: This is executed during the execution phase.

要修复脚本,您需要将代码放入doLast,如下所示:

task getCurrentVersion {
  doLast {
     def line
     new File("REVISION").withReader { line = it.readLine() }
     ext.hash = {
       line
     }
  }
}