Skip to content

Instantly share code, notes, and snippets.

@mpetuska
Last active January 8, 2022 17:58
Show Gist options
  • Save mpetuska/86c05e02b2199e5a2f186da0c2c3f2fd to your computer and use it in GitHub Desktop.
Save mpetuska/86c05e02b2199e5a2f186da0c2c3f2fd to your computer and use it in GitHub Desktop.
Utility script to find and run the nearest gradle wrapper.

Installation

  1. Download the raw script: curl -o ~/.local/bin/gradlew https://gist.githubusercontent.com/mpetuska/86c05e02b2199e5a2f186da0c2c3f2fd/raw/gradlew.sh
  2. Adjust permissions: chmod +x ~/.local/bin/gradlew
  3. (Optional) Make a shortcut: ln -s ~/.local/bin/gradlew ~/.local/bin/gw

There's also an installation script available:

curl https://gist.githubusercontent.com/mpetuska/86c05e02b2199e5a2f186da0c2c3f2fd/raw/installGW.sh | bash

Usage

With this script setup, you can invoke gradle commands from any directory in multi-module project via nearest wrapper. The script supports both, nested and flat module structure.

Here's an example nested project structure

/parent
  /moduleA
  /moduleB
    /moduleC

With the structure above, you can invoke gradlew or gw command from any child subdirectory and automatically target that module's tasks. For instance the following will invoke :moduleA:test task only from parent's gradlew.

# pwd - /parent/moduleA
gw test

This also works with flat gradfle project structure

/parent
/moduleA
/moduleB
  /moduleC
#!/usr/bin/env bash
currentDir=`pwd`
targetDir=$currentDir
gradlewFile=`pwd`/gradlew
function find-gradlew() {
gradlewFile=`find $1 -name gradlew | head -n 1`
}
while [[ -d ${targetDir} ]]; do
if [[ -f ${gradlewFile} ]]; then
targetDir=`echo ${gradlewFile} | sed -e "s/\/gradlew$//"`
targetDir=`cd ${targetDir}; pwd`
gradlewFile=${targetDir}/gradlew
root=`(cd ${targetDir}/..; pwd)`
if [[ ${currentDir} =~ ^${targetDir} ]]; then
root=${targetDir}
fi
gradlePath=`echo ${currentDir} | sed -e "s:^${root}::" | sed -e "s:/:\::g"`
args=""
if [[ ${targetDir} != ${currentDir} ]]; then
for arg in "$@" ; do
if [[ ${arg::1} =~ [-\'\":] ]]; then
args="${args} ${arg}"
else
args="${args} ${gradlePath}:${arg}"
fi
done
else
args="$@"
fi
commandLine="${gradlewFile} -p ${targetDir} ${args}"
echo Working Directory: ${currentDir}
echo Executing: ${commandLine}
bash ${commandLine}
exit 0
else
targetDir=${targetDir}/..
find-gradlew ${targetDir}
fi
done
exit 1
curl -o ~/.local/bin/gradlew https://gist.githubusercontent.com/mpetuska/86c05e02b2199e5a2f186da0c2c3f2fd/raw/gradlew.sh
chmod +x ~/.local/bin/gradlew
ln -s ~/.local/bin/gradlew ~/.local/bin/gw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment