Replace token in file before building, but keep token in sources

后端 未结 5 1265
孤街浪徒
孤街浪徒 2021-02-12 03:33

I want to replace a @VERSION@ token in a java source file with a version before building (Gradle is my build system of choice).

In my current script a

5条回答
  •  时光取名叫无心
    2021-02-12 04:02

    WARNING: As indicated in comments by @Raffaele filtering source code may result in serious problems. This answer assumes that you know well what are you doing and are conscious about potential problems that may occur.

    The problem is in the fact that java source files are not copied - they're compiled only - in place. So you need to:

    1. Before compilation - copy the file that contains @VERSION@
    2. Filter the file.
    3. Compile
    4. Restore original file.

    Not sure about paths but the following piece of code should be helpful:

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

提交回复
热议问题