Wednesday, April 2, 2014

Change maven local repo in one command - Ubuntu/Linux


This will be useful for the developers who works with multiple maven local repositories.

Requirement:  set M2_HOME environment variable, before you start. 

Configuration
Add following  bash function to .bashrc in your home directory. Change M2_LOCATION if you need.



changeM2()
{
if [ -z $M2_HOME ]; then
echo "Set M2_HOME first."
else
# NOTE !.
# M2_LOCATION is the place where I put my all local repos. Change it, if you need.
M2_LOCATION=$M2_HOME/repo
echo "Your Local repository location is set to $M2_LOCATION"
#Validate M2_LOCATION is exist
if [ -d $M2_LOCATION ]; then
CURRENT_M2=$(grep -i "<localRepository>" $M2_HOME/conf/settings.xml | head -1)
echo "Current M2 local repository is set to $CURRENT_M2"
echo "Directories in the $M2_LOCATION"
ls $M2_LOCATION -D
echo ""
read -p "Enter m2 repo name: " NEW_M2_LOCATION;
if [ -z $NEW_M2_LOCATION ]; then
echo "Invalid input. No changes to maven settings."
else
sed -i "s:$CURRENT_M2:<localRepository>$M2_LOCATION/$NEW_M2_LOCATION</localRepository>:g" $M2_HOME/conf/settings.xml
echo ""
echo "localRepository is changed to $M2_LOCATION/$NEW_M2_LOCATION"
echo "New $M2_HOME/conf/settings.xml:"
grep -i "$M2_LOCATION/$NEW_M2_LOCATION" $M2_HOME/conf/settings.xml
fi
else
echo "$M2_LOCATION does not exists. Create $M2_LOCATION first."
fi
fi
}
view raw .bashrc hosted with ❤ by GitHub
Then reload the .bashrc using command,
$ source ~/.bashrc


How to use: 

Type changeM2 in the terminal and give the name of the m2 repo (folder) you wish to change.