【问题标题】:How do I check the current contents of a file in Gradle如何在 Gradle 中检查文件的当前内容
【发布时间】:2018-08-01 18:52:54
【问题描述】:

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

【问题讨论】:

    标签: file gradle order-of-execution


    【解决方案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
         }
      }
    }
    

    【讨论】:

    • 当然!如此明显,如此简单和如此完美。谢谢@roman-konaval!
    猜你喜欢
    • 2012-01-19
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多