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

How do I check the current contents of a file in Gradle

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

以下是任务:

构建项目:

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

  commandLine command
}

远程部署

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}"
      }
    }
  }
}

获取当前版本

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

Gradle 构建具有 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
     }
  }
}