gradlew
Overview
`gradlew` is a Unix shell script designed to serve as the Gradle startup launcher on Unix-like systems (Linux, macOS, Cygwin). It acts as a platform-independent wrapper around the Gradle build tool, facilitating the setup of the Java Virtual Machine (JVM) environment and invoking the Gradle Wrapper runtime. The script handles environment configuration, JVM options, classpath setup, OS-specific adaptations, and finally launches the Gradle Wrapper Java process.
The primary purpose of this script is to abstract the complexities involved in launching Gradle builds, ensuring that the correct JVM and dependencies are used regardless of the user's environment or operating system nuances.
Detailed Explanation
Variables
DEFAULT_JVM_OPTS
Default JVM options applied when launching the Gradle JVM. Initially empty but can be overridden by environment variables.APP_NAME
Set to"Gradle", used for display and identification purposes (e.g., dock name on macOS).APP_BASE_NAME
The basename of the script file, typicallygradlew.MAX_FD
Maximum file descriptors limit, initialized to"maximum"to attempt to raise the limit to the OS maximum.cygwin, msys, darwin
Boolean flags to detect the current OS environment:cygwinfor Cygwinmsysfor MSYS (Minimal SYStem)darwinfor macOS.
APP_HOME
The absolute path to the directory where the script resides, resolved even if the script is a symbolic link.CLASSPATH
Set to the location of the Gradle Wrapper.jarfile inside the script directory.JAVACMD
The Java executable command determined based on the environment (JAVA_HOMEor systemjava).JVM_OPTS
Array holding JVM options collected from defaults and environment variables.
Functions
warn
warn ( ) {
echo "$*"
}
Purpose: Prints a warning message to standard output.
Parameters:
$*: Any string message to display.
Returns: None.
Usage Example:
warn "This is a warning message."
die
die ( ) {
echo
echo "$*"
echo
exit 1
}
Purpose: Prints an error message and terminates the script with an exit code of 1.
Parameters:
$*: Error message to display.
Returns: Does not return; exits the script.
Usage Example:
die "Fatal error: JAVA_HOME not set correctly."
splitJvmOpts
function splitJvmOpts() {
JVM_OPTS=("$@")
}
Purpose: Parses and splits JVM option strings into an array to correctly handle spaces and quoting.
Parameters:
$@: List of JVM options as separate arguments.
Returns: Populates the global
JVM_OPTSarray.Usage: Called with all JVM options concatenated from default and environment variables.
Implementation Details and Workflow
OS Detection:
The script detects whether it is running on Cygwin, MSYS, or Darwin (macOS) environments by parsing the output ofuname. This information guides path handling and OS-specific JVM options.Resolving Script Location:
The script resolves any symbolic links pointing to the script to determine the true script location. This enables settingAPP_HOMEreliably to the root directory of the Gradle installation.Classpath Setup:
The classpath is set to the Gradle Wrapper jar (gradle-wrapper.jar) inside thegradle/wrapperdirectory relative toAPP_HOME.Java Executable Determination:
The script checks for a validJAVA_HOMEenvironment variable and verifies the existence and executability of the Java binary inside it. If missing or invalid, it attempts to usejavafrom the system PATH. If no valid Java executable is found, it terminates with an error.Max File Descriptor Limit:
On non-Cygwin and non-Darwin systems, it attempts to increase the maximum number of file descriptors to the system maximum or a user-defined value. This improves Gradle's ability to open many files simultaneously during builds.macOS Dock Integration:
On Darwin, additional JVM options are appended to set the application name and icon for the macOS dock.Cygwin Path Conversion:
For Cygwin environments, the script converts POSIX paths to Windows paths forAPP_HOME,CLASSPATH, andJAVACMDto ensure compatibility with Windows JVMs and Gradle.It also processes command line arguments to convert them as appropriate, skipping options starting with
-.JVM Options Assembly:
JVM options are gathered fromDEFAULT_JVM_OPTS,JAVA_OPTS, andGRADLE_OPTSenvironment variables, parsed viasplitJvmOptsinto an array. Additionally, a system property is added to identify the Gradle app name.Execution:
The script finally usesexecto replace the shell process with thejavaprocess, launching the Java classorg.gradle.wrapper.GradleWrapperMainwith the assembled JVM options and all original script arguments.
Usage Example
To use the Gradle Wrapper on a Unix-like system:
./gradlew build
This will:
Configure the JVM environment,
Resolve script location,
Set up classpath and JVM options,
Launch the Gradle Wrapper main class,
Execute the
buildGradle task.
Interaction with Other System Components
Gradle Wrapper JAR:
This script depends on thegradle-wrapper.jarfile located ingradle/wrapperunderAPP_HOME. This JAR contains the Java code that bootstraps and downloads the correct Gradle distribution.Java Runtime Environment:
The script requires a valid Java installation, either viaJAVA_HOMEor available in the system PATH.Environment Variables:
It respects and integrates JVM options set throughJAVA_OPTSandGRADLE_OPTSenvironment variables.Operating System:
The script adapts behavior based on OS type, handling file descriptor limits, path formats, and UI integration (macOS dock).User Invocation:
End users invoke this script to run Gradle commands without needing to install Gradle manually, relying on the wrapper to manage Gradle versions.
Visual Diagram
The following flowchart illustrates the main flow and decision points within the `gradlew` script:
flowchart TD
Start[Start Script] --> DetectOS{Detect OS Environment}
DetectOS -->|Cygwin| SetCygwinTrue[Set cygwin=true]
DetectOS -->|Darwin| SetDarwinTrue[Set darwin=true]
DetectOS -->|MSYS| SetMsysTrue[Set msys=true]
DetectOS -->|Others| NoFlag[No OS Flag]
SetCygwinTrue --> ResolveLinks
SetDarwinTrue --> ResolveLinks
SetMsysTrue --> ResolveLinks
NoFlag --> ResolveLinks
ResolveLinks[Resolve Script Symlinks] --> SetAppHome[Set APP_HOME]
SetAppHome --> SetClasspath[Set CLASSPATH to gradle-wrapper.jar]
SetClasspath --> DetermineJavaCmd{JAVA_HOME set?}
DetermineJavaCmd -->|Yes| CheckJavaExec[Check JAVA_HOME/java executable]
DetermineJavaCmd -->|No| UseSystemJava[Use 'java' from PATH]
CheckJavaExec -->|Executable| JavaCmdReady[Set JAVACMD]
CheckJavaExec -->|Not Executable| DieError[Exit with error]
UseSystemJava --> CheckJavaInPath{Is 'java' in PATH?}
CheckJavaInPath -->|Yes| JavaCmdReady
CheckJavaInPath -->|No| DieError
JavaCmdReady --> IncreaseFDLimit{Not cygwin or darwin?}
IncreaseFDLimit -->|Yes| TryIncreaseFD[Attempt ulimit -n]
IncreaseFDLimit -->|No| SkipFDLimit[Skip]
TryIncreaseFD --> WarnOnFail[Warn if fails] --> SetupDarwinOptions
SkipFDLimit --> SetupDarwinOptions
SetupDarwinOptions{Is darwin?} -->|Yes| AddDockOptions
SetupDarwinOptions -->|No| SetupCygwinPaths
AddDockOptions --> SetupCygwinPaths
SetupCygwinPaths{Is cygwin?} -->|Yes| ConvertPathsAndArgs
SetupCygwinPaths -->|No| PrepareJvmOpts
ConvertPathsAndArgs --> PrepareJvmOpts
PrepareJvmOpts[Split JVM_OPTS from DEFAULT_JVM_OPTS, JAVA_OPTS, GRADLE_OPTS] --> AddAppNameProperty
AddAppNameProperty[Add -Dorg.gradle.appname property] --> ExecJava
ExecJava[Execute Java command:\njava ${JVM_OPTS} -classpath CLASSPATH org.gradle.wrapper.GradleWrapperMain args] --> End[End]
Summary
The `gradlew` Unix shell script is an essential bootstrapper for Gradle builds, responsible for:
Environment detection and adaptation,
JVM and classpath setup,
Handling OS-specific intricacies,
Launching the Gradle Wrapper Java main process.
It enables users to run Gradle builds reliably without manual setup of Gradle distributions or complex environment configurations, supporting seamless and reproducible build environments across different Unix-like platforms.