DEV Community

Cover image for Grabbing version strings with PowerShell
Thomas Künneth
Thomas Künneth

Posted on

Grabbing version strings with PowerShell

The jpackage tool, which is part of OpenJDK since Java 14, can create, well, native packages. Some time ago I wrote a small piece about it, called A quick look at jpackage. In that article I showed how to grab a version string from a Java source file and pass it to jpackage which has an option called --app-version. This is how the version is defined in Java:

public class Clip4Moni {

  public static final String VERSION = "1.3.3";

  public static void main(String[] args) {
Enter fullscreen mode Exit fullscreen mode

And grabbing it might look like this:

VERSION=`sed -n -e 's/.*VERSION = \"\(.*\)\".*/\1/p' < $BASEDIR/src/main/classes/com/thomaskuenneth/clip4moni/Clip4Moni.java`
$JAVA_HOME/bin/jpackage --name Clip4Moni --icon $BASEDIR/artwork/Clip4Moni.icns --app-version $VERSION --type app-image --module-path $BASEDIR/build/modules -m main/com.thomaskuenneth.clip4moni.Clip4Moni
Enter fullscreen mode Exit fullscreen mode

As you can see I am using the sed commandline tool. This was designed for macOS but should run on any other Unix-like system. But what about Windows? Windows has the ancient (no offense intended) cmd.exe and the much much more modern PowerShell. PowerShell has a lot of great builtin capabilities, and handling regular expressions is among them. So it should be easy to do something similar, right? Right.

$version = "???"
$source = Get-Content -Path $base_dir\src\main\classes\com\thomaskuenneth\clip4moni\Clip4Moni.java
foreach($line in $source) {
    if ($line -match "version = `"(.+)`"") {
        $version = $matches[1]
        break
    }
}
Enter fullscreen mode Exit fullscreen mode

The version string will be stored in a variable called $version. I initialize it to ???, just in case... Get-Content gets the contents of the source file. As you surely have guessed it is an array of strings. I iterate over it until my regular expression matches. (.+) is a group, which can later be accessed through $matches[1]. break exits the foreach loop.

Well, and that's all about it. Really nice, isn't it?


Cover image Copyright (c) Thomas Künneth

Top comments (0)