0

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

以下是任务:

构建项目:

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
4

1 回答 1

1

Gradle 构建分为三个阶段:初始化、配置和执行。

您面临的问题是代码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
     }
  }
}
于 2018-02-22T10:50:02.890 回答