Gradle Zip任务:添加动态生成的文件

5

我有一个Gradle构建脚本,其中我使用“Zip”任务直接从源目录生成zip归档文件。

除了将源目录结构中的所有文件复制到zip归档文件中,我还想找到一种方法来包含一个动态生成的不在源目录中的文件。

你们知道我怎么做吗?

这是我想要做的伪代码:

task('archive', type: Zip) {
  ...
  from 'source'
  newFile('dynamically-generated.txt', 'dynamic file content')
}

以下是源结构和目标结构:

[i71178@bddev01-shell01 ~]$ tree source/
source/
├── file1.txt
├── file2.txt
└── file3.txt

0 directories, 3 files
[i71178@bddev01-shell01 ~]$ unzip -l destination.zip
Archive:  destination.zip
  Length      Date    Time    Name

---------  ---------- -----   ----
        0  02-26-2016 16:56   source/
        0  02-26-2016 16:56   source/file2.txt
        0  02-26-2016 16:56   source/dynamically-generated.txt
        0  02-26-2016 16:56   source/file1.txt
        0  02-26-2016 16:56   source/file3.txt
---------                     -------
        0                     5 files

包含一个动态生成的文件,该文件不在源目录中。那么它在哪里? - RaGe
该内容将在构建/复制时通过代码动态生成,我希望在目标zip归档中创建一个新文件,该文件具有提供的名称和内容。 - nemo
那它怎么和 from 'source' 有什么不同呢?只需添加另一个 from 行并指定新的目录即可。 - RaGe
所以,在源中不存在这个文件。当我将文件从“源”复制到“目标”时,我还想在“目标”中插入一个新文件,其中包含一些即时生成的内容。我会更新问题以澄清这一点。 - nemo
1
在不同的任务中创建文件。您可以使用 dependsOn 强制运行该任务以在压缩任务之前运行。 - RaGe
显示剩余4条评论
3个回答

1

结合我上面的评论和你的getTemporaryDir评论:

task generateThenZip()<<{
    def tempDir = getTemporaryDir()
    newFile("$tempDir/dynamically-generated.txt", 'dynamic file content')

    zip{
        from 'source'
        from tempDir
    }
}

这看起来很有趣:https://docs.gradle.org/current/javadoc/org/gradle/api/Task.html#getTemporaryDir()我可以在那里创建它,然后只需从'mytempfile'... - nemo

1
这是我最终做的事情:
subprojects {
  apply plugin: 'myPlugin'

  //The 'build' task is set up by the plugin
  build {
    //Customization to keep consistent with artifacts being currently generated.
    doFirst {
      new File(getTemporaryDir(), 'artifact-fullname.txt').text = "${project.name}-${project.version}\n"
    }
    archiveName = "${project.name}.${project.build.extension}"
    from getTemporaryDir()
  }
}

谢谢!


1

我在Gradle 6.6.1上已经相当轻松地实现了它,只需在from部分创建文件即可。

distributions {
  main {
    contents {
      into("/") {
        from {
          if (!buildDir.exists()) {
            buildDir.mkdir()
          }
          def f = new File("$buildDir/all")
          f.text = "project_version: ${project.version}\n"
          f
        }
      }
      ...
    }
  }
}

顺便说一下,我认为$buildDir/tmp更安全。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接