我想@VERSION@在构建之前用版本替换java源文件中的标记(Gradle是我选择的构建系统).
在我当前的脚本中,ant.replace(file: 'src/main/java/randers/notenoughvocab/main/Reference.java', token: '@VERSION@', value: version)它取代了@VERSION@实际源文件中出现的内容,因此在构建之后,所有出现的模式都被版本替换,如果我更改了gradle构建文件的版本,它将不再在那里找到任何模式并且版本不会更新.
我在这里也看到了一个任务,但是我没有得到需要为我的特定项目应用的值.
如果需要,我的项目的项目布局:

我的gradle构建文件:在github上查看
Raf*_*ele 18
@VERSION@在向公众发布软件之前,您只需要替换令牌.在这里,我定义了一个compileForRelease完成它的任务:
import org.apache.tools.ant.filters.ReplaceTokens
task sourcesForRelease(type: Copy) {
from 'src/main/java'
into 'build/adjustedSrc'
filter(ReplaceTokens, tokens: [VERSION: '2.3.1'])
}
task compileForRelease(type: JavaCompile, dependsOn: sourcesForRelease) {
source = sourcesForRelease.destinationDir
classpath = sourceSets.main.compileClasspath
destinationDir = file('build/adjustedClasses')
}
Run Code Online (Sandbox Code Playgroud)
我不建议搞乱Java插件定义的标准任务,因为这会给每个构建添加不必要的开销.
警告:如@Raffaele的评论中所示,过滤源代码可能会导致严重问题.这个答案假定您很清楚自己在做什么,并且意识到可能发生的潜在问题.
问题在于java源文件没有被复制 - 它们只是编译 - 就位.所以你需要:
@VERSION@不确定路径,但下面的代码应该是有用的:
apply plugin: 'java'
version = '0.0.1'
group = 'randers.notenoughvocab'
archivesBaseName = 'NotEnoughVocab'
def versionFile = 'src/main/java/randers/notenoughvocab/main/Reference.java'
def tempDir = 'build/tmp/sourcesCache'
def versionFileName = 'Reference.java'
compileJava.doFirst {
copy {
from(versionFile)
into(tempDir)
}
ant.replace(file: versionFile, token: '@VERSION@', value: version)
}
compileJava.doLast {
copy {
from(tempDir + '/' + versionFileName)
into(project.file(versionFile).parent)
}
}
Run Code Online (Sandbox Code Playgroud)
我发现现有的答案有些不令人满意,所以这是我的解决方案:
import org.apache.tools.ant.filters.ReplaceTokens
task processSource(type: Sync) {
from sourceSets.main.java
inputs.property 'version', version
filter(ReplaceTokens, tokens: [VERSION: version])
into "$buildDir/src"
}
compileJava {
source = processSource.outputs
}
Run Code Online (Sandbox Code Playgroud)
这解决了以下各种问题:
$buildDir/src根据processSource任务进行修改,这反映了标准processResources.sourceSets.main.java.srcDirs仍然是默认值,并且在指定(尚)不存在的位置时没有任何技巧filter包含/排除模式的范围。src,$buildDir处理过的源文件所在的目录。inputs.property.Sync而不是Copy从源中删除的文件也从过滤的源中删除(谢谢,@Earthcomputer)。| 归档时间: |
|
| 查看次数: |
12564 次 |
| 最近记录: |