Created
April 4, 2014 07:45
-
-
Save mrietveld/9969991 to your computer and use it in GitHub Desktop.
Perl file ("changePomVersion.pl") to change version of an artifact in a pom.xml.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# This file takes 2 arguments when run: | |
# -p <POMFILE> | |
# -v <VERSION> | |
# | |
# The <POMFILE> argument is the path to a pom.xml file whose version should be changed | |
# The <VERSION> argument is the new version that should replaced the existing version | |
# | |
use File::Copy; | |
# - Retrieve options | |
use Getopt::Std; | |
getopts('p:v:'); | |
my $pomFile, $newVer; | |
if( $opt_v ) { | |
$newVer = $opt_v; | |
} else { | |
die "New version required.\n"; | |
} | |
if( $opt_p ) { | |
$pomFile = $opt_p; | |
} else { | |
die "Pom file required.\n"; | |
} | |
my $versionLineMax = 100; | |
# - Print options/info | |
print "Changing $pomFile ($newVer)\n"; | |
# Open original file | |
open( POM, "<$pomFile" ) | |
|| die "Unable to open $pomFile for reading: $!\n"; | |
# Open new file that will replace original | |
open( NEWPOM, ">$pomFile.new" ) | |
|| die "Unable to open $pomFile.new for writing: $!\n"; | |
# Flag to indicate that it's the first <version> element after the </parent> element | |
$afterParent = 0; | |
$lineCount = 0; | |
# Read through POM data (each line is put in the $_ variable | |
while(<POM>) { | |
++$lineCount; | |
# Flag to indicate that the line has been modified and already printed to NEWPOM | |
$replaced = 0; | |
# Does the line contain </parent>? | |
if( m#^\s*</parent># ) { | |
++$afterParent; | |
} elsif( m#^\s*<version># ) { | |
# If </parent> occurs multiple times, just replace <version> element | |
# after the *first* <parent> | |
if( $afterParent == 1 ) { | |
# double check line number | |
if( $lineCount > $versionLineMax ) { | |
die "Failling because first <version> element was found after line $versionLineMax!\n"; | |
} | |
# replace original version with $newVer value | |
$newline = $_; | |
$newline =~ s#<version>([^<]+)</version>#<version>$newVer</version>#; | |
print NEWPOM $newline; | |
$replaced = 1; | |
} | |
} | |
if( ! $replaced ) { | |
# print unmodified lines to new pom file | |
print NEWPOM $_; | |
} | |
} | |
close( POM ); | |
close( NEWPOM ); | |
# replace original pomFile with modified copy | |
move("$pomFile.new", $pomFile) | |
|| die "Unable to replace $pomFile with ${pomFile}.new: $!\n"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment