Skip to content

how to get Maven to build a properties file with the git commit version, branch, and build timestamp

Eric Jahn edited this page Feb 12, 2018 · 9 revisions

Maven part: [in the maven part, if you set to true, it won't build if there are uncommitted files]

<build> <finalName>HSLynk</finalName> <resources> <resource> <directory>src/main/resources/</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <compilerArgument>-Xlint:unchecked</compilerArgument> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.1.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>3.0.1</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>buildnumber-maven-plugin</artifactId> <version>1.4</version> <executions> <execution> <phase>validate</phase> <goals> <goal>create</goal> </goals> </execution> </executions> <configuration> <doCheck>false</doCheck> <doUpdate>false</doUpdate> <shortRevisionLength>8</shortRevisionLength> <properties> <scmBranch>${scmBranch}</scmBranch> </properties> </configuration> </plugin> </plugins> </build>

and this is version.properties which lives in src/main/resources:

version=${project.version} name=${project.name} revision=${buildNumber} timestamp=${timestamp} branch=${scmBranch}

And some logging:

` public static void logVersion() { Properties properties = new Properties(); InputStream in = null; try { in = LoadPropertiesUtility.class.getClassLoader().getResourceAsStream("version.properties");

        if(in == null){
            LOGGER.log(Level.FINE, "Unknown Code Revision");
        }

        properties.load(in);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String timestamp = properties.getProperty("timestamp");
        String buildTimestamp = sdf.format(new Date(Long.parseLong(timestamp)));
        String version = properties.getProperty("name") + "-" + properties.getProperty("version");
        String revision = properties.getProperty("revision");
        String scmBranch = properties.getProperty("branch");

        LOGGER.log(Level.FINE, "{0} commit version {1}, built on {2} from branch {3}",
                   new Object[] { version, revision, buildTimestamp, scmBranch });
    } catch (IOException ex) {
        LOGGER.log(Level.FINE, ex.getMessage());
    } finally{
        if(in != null){
            try {
                in.close();
            } catch (IOException e) {
                LOGGER.log(Level.FINE, e.getMessage());
            }
        }
    }

`

Clone this wiki locally