fyr
fyr

Reputation: 20859

Maven: Extract parts of a text file to variables

Is there a way with Maven to parse an external text file and to extract variables using regex ? The Use-Case is that i have an external-file which cannot be changed. This file is not a proerties file but a C-Header file.

What I would like to do is that maven extracts portions which are in the header file to a variable, like version and to use this variables during the build.

The process might look like this:

  1. Maven reads the header-file
  2. Maven extracts the Major version using regex on the files contents
  3. Maven extracts the Minor version using regex on the files contents
  4. Maven uses extracted Major and Minor version during build.

I did search the net but didnt find a solution to this and currently stuck.

Upvotes: 1

Views: 1458

Answers (2)

fyr
fyr

Reputation: 20859

Found a solution which is convenient for me using groovy maven plugin.

<plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>groovy-maven-plugin</artifactId>
    <version>2.0</version>
    <executions>
        <execution>
            <phase>process-classes</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <defaults>
                    <name>Xenu</name>
                </defaults>
                <source>
                    String fileContents = new File("${project.basedir}/../include/version.h").getText('UTF-8')
                    matcher = (fileContents =~ /(?s).*MAJOR ([0-9]+).*?/)
                    String major_version = matcher.getAt(0).getAt(1)
                    matcher = (fileContents =~ /(?s).*MINOR ([0-9]+).*?/)
                    String minor_version = matcher.getAt(0).getAt(1)
                    matcher = (fileContents =~ /(?s).*PATCH ([0-9]+).*?/)
                    String patch_version = matcher.getAt(0).getAt(1)
                    String version = String.format('%s.%s.%s', major_version, minor_version, patch_version)
                    // Set version to be used in pom.properties
                    project.version = version
                    // Set version to be set as jar name
                    project.build.finalName = project.artifactId + "-" + version
                </source>
            </configuration>
        </execution>
    </executions>
</plugin>

Upvotes: 1

Gerold Broser
Gerold Broser

Reputation: 14762

  1. Use the Exec Maven Plugin to read the header file and to create a properties file from its content.
  2. Use the Properties Maven Plugin to use the properties file.

Upvotes: 1

Related Questions