Skip to content

Instantly share code, notes, and snippets.

@merikan
Last active July 5, 2019 12:39
Show Gist options
  • Save merikan/dcfdb707f2681e004f1cb9446c1598f1 to your computer and use it in GitHub Desktop.
Save merikan/dcfdb707f2681e004f1cb9446c1598f1 to your computer and use it in GitHub Desktop.
Maven and Gradle wrapper functions

Using the wrapper is the preferred way to start a build and it is a great way to ensure a reliable, controlled and standardized execution of the build in the local development environment and your CI/CD pipeline. Wrappers are avaliable for both Maven and Gradle.

One disturbing problem with wrappers is that you can't run it from a sub-module. This is because it will not find the wrapper executable since it is installed in the root of the project. The solution to that problem is to use a small function in your shell that overloads your standard maven and gradle command and that will help you locate the wrapper executable.
Below are two shell functions I'm using in my environment. Just copy and paste them into a suitable start script depending on your environment, .bashrc or .zshrc.

This is how they work:

  1. If it's a git repository then look for a wrapper in the toplevel directory
  2. If not a git repository search uppwards for a wrapper and continue to search as long as we have a pom.xml or a *.gradle file present.
  3. If no wrapper found, run the native builder for Maven or Gradle
# run gradle wrapper in git toplevel directory or current/parent directories if found, else run native gradle.
function gradle {
local dir=`pwd`
if command -v git >/dev/null 2>&1 && [ -e "$(git rev-parse --show-toplevel 2>/dev/null)" ]; then
dir=$(git rev-parse --show-toplevel 2>/dev/null);
else
while [ -e "$dir" ] && ! [ -e $dir/gradlew ] && [ -n $(find $dir -maxdepth 1 -name '*.gradle' -print -quit) ]; do dir=${dir%/*}; done
fi
if [ -e $dir/gradlew ]; then
echo "Running wrapper at $dir"
$dir/gradlew $@
return $?
fi
echo "No wrapper found, running native Gradle"
command gradle $@
}
# run maven wrapper in git toplevel directory or current/parent directories if found, else run native mvn.
function mvn {
local dir=`pwd`
if command -v git >/dev/null 2>&1 && [ -e "$(git rev-parse --show-toplevel 2>/dev/null)" ]; then
dir=$(git rev-parse --show-toplevel 2>/dev/null);
else
while [ -e "$dir" ] && [ -e $dir/pom.xml ] && ! [ -e $dir/mvnw ] ; do dir=${dir%/*}; done
fi
if [ -e $dir/mvnw ]; then
echo "Running wrapper at $dir"
$dir/mvnw $@
return $?
fi
echo "No wrapper found, running native Maven"
command mvn $@
}

GitHubGist uses ASCIIbetical order.

This file is the name of the gist
File _ReadMe.md is used as description for the Gist and it will be at the top of the list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment