Skip to content

Commit

Permalink
Support for export of info properties
Browse files Browse the repository at this point in the history
If 'jgitver.export-properties-path=FILE` is specified then a
properties file, FILE, will be generated with the jgitver info
properties.

Fixes #163
  • Loading branch information
lbruun authored and McFoggy committed Sep 28, 2021
1 parent 5bc20fd commit de60854
Show file tree
Hide file tree
Showing 10 changed files with 236 additions and 6 deletions.
24 changes: 20 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ _[Old](https://jgitver.github.io/maven/configuration/) xml schemas are kept for
- `-Djgitver.config=FILE` : overrides default config file and uses FILE instead
- `-Djgitver.use-version=VERSION` : execute jgitver but finally uses VERSION as the project version
- `-Djgitver.resolve-project-version=true` : replaces the ${project.version} also in properties, dependencies, dependencyManagement, plugins and pluginManagement sections
- `-Djgitver.export-properties-path=FILE` : exports output properties into the given file

#### Working on a detached HEAD

Expand All @@ -119,13 +120,16 @@ Since `1.3.0` it now possible to provide externally the _branch_ information via
- `JGITVER_BRANCH=SOME_BRANCH_NAME && mvn validate` for bash like shells
- `SET JGITVER_BRANCH=SOME_BRANCH_NAME`
`mvn validate`
for windows CMD (I don't know a one iner solution)
for windows CMD (I don't know a one liner solution)


### Available properties
### Available output properties

Since `0.2.0`, the plugin exposes git calculated properties available during the maven build.
Those are available under the following properties name: "jgitver.meta" where `meta` is one of [Metadatas](https://github.com/jgitver/jgitver/blob/master/src/main/java/fr/brouillard/oss/jgitver/metadata/Metadatas.java#L25) name in lowercase.
The plugin exposes git calculated properties available during the maven build.
Those are available under the following properties name: "jgitver.meta" where `meta` is one
of [Metadatas](https://github.com/jgitver/jgitver/blob/master/src/main/java/fr/brouillard/oss/jgitver/metadata/Metadatas.java#L25) name in lowercase
in addition to `jgitver.used_version` which represents the version ultimately
applied (in case it was overriden on the command line using `-Djgitver.use-version=VERSION`).

You can then use them as standard maven properties in your build:

Expand Down Expand Up @@ -192,6 +196,18 @@ resulted in my case
[INFO] Executed tasks
```

You can also output the properties into a file so that they can be picked
up by the next steps in your build pipeline. This is accomplished by setting
the `jgitver.export-properties-path` system property, e.g. from the command
line:

``` text
mvn ... -Djgitver.export-properties-path=./jgitver-output.properties
```

The produced file follows the [Java Properties standard](https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html#load-java.io.Reader-).


## Example

If you want to give it a try you can use the following script that will setup a demo project under `/tmp/jgitver-tester`
Expand Down
2 changes: 2 additions & 0 deletions src/it/verify-export-properties/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
prebuild.log
build.log
25 changes: 25 additions & 0 deletions src/it/verify-export-properties/.mvn/extensions.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!--
Copyright (C) 2016 Matthieu Brouillard [http://oss.brouillard.fr/jgitver-maven-plugin] (matthieu@brouillard.fr)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<extensions xmlns="http://maven.apache.org/EXTENSIONS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/EXTENSIONS/1.0.0 http://maven.apache.org/xsd/core-extensions-1.0.0.xsd">
<extension>
<groupId>@project.groupId@</groupId>
<artifactId>@project.artifactId@</artifactId>
<version>@project.version@</version>
</extension>
</extensions>
20 changes: 20 additions & 0 deletions src/it/verify-export-properties/.mvn/jgitver.config.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!--
Copyright (C) 2016 Matthieu Brouillard [http://oss.brouillard.fr/jgitver-maven-plugin] (matthieu@brouillard.fr)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<configuration>
<failIfDirty>false</failIfDirty>
</configuration>
2 changes: 2 additions & 0 deletions src/it/verify-export-properties/invoker.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# invoker.mavenOpts = -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
invoker.goals = clean verify -Djgitver.export-properties-path=./jgitver-output.properties
32 changes: 32 additions & 0 deletions src/it/verify-export-properties/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2016 Matthieu Brouillard [http://oss.brouillard.fr/jgitver-maven-plugin] (matthieu@brouillard.fr)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>fr.brouillard.oss.it</groupId>
<artifactId>export-properties-is-working</artifactId>
<version>1.0</version>
<packaging>pom</packaging>

<description>A simple IT verifying that properties are exported into a file if so requested</description>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
52 changes: 52 additions & 0 deletions src/it/verify-export-properties/prebuild.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Copyright (C) 2016 Matthieu Brouillard [http://oss.brouillard.fr/jgitver-maven-plugin] (matthieu@brouillard.fr)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
def log = new PrintWriter( new File(basedir, "prebuild.log").newWriter("UTF-8"), true )
log.println( "Prebuild started at: " + new Date() + " in: " + basedir )

[
"git --version",
"rm -rf .git",
"git init",
"git config user.name nobody",
"git config user.email nobody@nowhere.com",
"dd if=/dev/urandom of=content bs=512 count=2",
"git add .",
"git commit --message=initial_commit",
"git tag -a 1.0.0 --message=release_1.0.0",
"dd if=/dev/urandom of=content bs=512 count=2",
"git add -u",
"git commit --message=added_b",
"dd if=/dev/urandom of=content bs=512 count=2",
"git status",
"git log --graph --oneline"
].each{ command ->

def proc = command.execute(null, basedir)
def sout = new StringBuilder(), serr = new StringBuilder()
proc.waitForProcessOutput(sout, serr)

log.println( "cmd: " + command )
log.println( "out:" ) ; log.println( sout.toString().trim() )
log.println( "err:" ) ; log.println( serr.toString().trim() )
log.println( "ret: " + proc.exitValue() )

assert proc.exitValue() == 0

}

log.println( "Prebuild completed at: " + new Date() )
log.close()
return true
42 changes: 42 additions & 0 deletions src/it/verify-export-properties/verify.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Copyright (C) 2016 Matthieu Brouillard [http://oss.brouillard.fr/jgitver-maven-plugin] (matthieu@brouillard.fr)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
def baseDir = new File("$basedir")
def exportedPropsFileStr = 'jgitver-output.properties'

File actions = new File(baseDir, "verify-actions.log")
actions.write 'Actions started at: ' + new Date() + '\n'

actions << 'rm -rf .git'.execute(null, baseDir).text

def logLines = new File("$basedir", "build.log").readLines()
foundLines = logLines.findAll { it =~ /Properties exported to/ }
assert 1 == foundLines.size

File exportedPropsFile = new File(basedir, exportedPropsFileStr)
assert exportedPropsFile.isFile()

Properties properties = new Properties()
exportedPropsFile.withInputStream {
properties.load(it)
}

// The should be a decent amount of properties
assert properties.size() >= 10




return true
22 changes: 22 additions & 0 deletions src/main/java/fr/brouillard/oss/jgitver/JGitverExtension.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@
import fr.brouillard.oss.jgitver.cfg.Configuration;
import fr.brouillard.oss.jgitver.metadata.Metadatas;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.maven.AbstractMavenLifecycleParticipant;
Expand Down Expand Up @@ -133,9 +137,27 @@ public void afterSessionStart(MavenSession mavenSession) throws MavenExecutionEx
.map(version -> Providers.fixVersion(version, finalInfoProvider))
.orElse(infoProvider);

// Put metadatas into Maven session properties
JGitverUtils.fillPropertiesFromMetadatas(
mavenSession.getUserProperties(), infoProvider, logger);

// Put metadatas into exportedProps file (if requested)
Optional<String> exportPropsPathOpt =
JGitverUtils.exportPropertiesPath(mavenSession, logger);
if (exportPropsPathOpt.isPresent()) {
Properties exportedProps = new Properties();
JGitverUtils.fillPropertiesFromMetadatas(exportedProps, infoProvider, logger);
String exportPropsPath = exportPropsPathOpt.get();
try (OutputStream os = new FileOutputStream(exportPropsPath)) {
exportedProps.store(
os, "Output from " + JGitverUtils.EXTENSION_ARTIFACT_ID + " execution.");
logger.info("Properties exported to file \"" + exportPropsPath + "\"");
} catch (IOException ex) {
throw new IllegalArgumentException(
"Cannot write properties to file \"" + exportPropsPath + "\"", ex);
}
}

JGitverSession session = new JGitverSession(infoProvider, rootDirectory);
sessionHolder.setSession(session);
} catch (Exception ex) {
Expand Down
21 changes: 19 additions & 2 deletions src/main/java/fr/brouillard/oss/jgitver/JGitverUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,16 @@ public final class JGitverUtils {
public static final String EXTENSION_PREFIX = "jgitver";
public static final String EXTENSION_GROUP_ID = "fr.brouillard.oss";
public static final String EXTENSION_ARTIFACT_ID = "jgitver-maven-plugin";
public static final String SESSION_MAVEN_PROPERTIES_KEY = EXTENSION_PREFIX + ".session";
public static final String PROJECT_VERSION = "${project.version}";

// Command line keys
public static final String EXTENSION_SKIP = EXTENSION_PREFIX + ".skip";
public static final String EXTENSION_FORCE_COMPUTATION = EXTENSION_PREFIX + ".forceComputation";
public static final String EXTENSION_FLATTEN = EXTENSION_PREFIX + ".flatten";
public static final String EXTENSION_USE_VERSION = EXTENSION_PREFIX + ".use-version";
public static final String SESSION_MAVEN_PROPERTIES_KEY = EXTENSION_PREFIX + ".session";
public static final String PROJECT_VERSION = "${project.version}";
public static final String EXTENSION_EXPORT_PROPERTIES_PATH =
EXTENSION_PREFIX + ".export-properties-path";

public interface CLI {
String OVERRIDE_CONFIG_FILE = EXTENSION_PREFIX + ".config";
Expand Down Expand Up @@ -371,6 +375,19 @@ public static Optional<String> versionOverride(final MavenSession session, final
return getProperty(session, EXTENSION_USE_VERSION, logger);
}

/**
* Provides the path (file name) to export properties to if defined as user or system property.
*
* @param session a running maven session
* @param logger logger
* @return an Optional containing the output filename to use if the corresponding user or system
* property has been defined
*/
public static Optional<String> exportPropertiesPath(
final MavenSession session, final Logger logger) {
return getProperty(session, EXTENSION_EXPORT_PROPERTIES_PATH, logger);
}

/**
* Tries to get the property from the user properties ({@link MavenSession#getUserProperties()})
* or from the system properties ({@link MavenSession#getSystemProperties()}).
Expand Down

0 comments on commit de60854

Please sign in to comment.