Skip to content

Instantly share code, notes, and snippets.

@stoerr
Created January 10, 2025 16:50
Show Gist options
  • Save stoerr/b5c9c316ba9e68d5072302c8c103b389 to your computer and use it in GitHub Desktop.
Save stoerr/b5c9c316ba9e68d5072302c8c103b389 to your computer and use it in GitHub Desktop.
Mvn wrapper that searches a .m2/settings.xml upwards from the current directory - if you have to use different maven installations for different projects at the same time
#!/bin/bash
# This script calls Maven with settings depending on the directory it's started.
# It searches for .m2/settings.xml in the current directory and parent directories and takes the first it finds.
# This is not done if the command line contains an argument -s or --settings.
# This is useful if you have different settings for different projects.
# In the end it expects the real mvn executable (or probably a link to it) to be named _mvn and in the PATH.
settings_file=".m2/settings.xml"
settings_dir="$(realpath .)"
use_custom_settings=true
prev_arg_is_s=false
# Check if -s or --settings is present in the command-line arguments
for arg in "$@"; do
if $prev_arg_is_s; then
# Skip the argument to -s or --settings
prev_arg_is_s=false
continue
fi
case "$arg" in
-s)
use_custom_settings=false
prev_arg_is_s=true
;;
--settings)
use_custom_settings=false
prev_arg_is_s=true
;;
-s*)
# Handle combined -s<settingsfile>
use_custom_settings=false
;;
--settings=*)
# Handle --settings=<settingsfile>
use_custom_settings=false
;;
esac
done
if $use_custom_settings; then
# Search for settings file in current and parent directories
while true; do
if [ "$settings_dir" = "/" ] || [ "$settings_dir" = "$HOME" ]; then
settings_path=""
break
fi
if [ -f "$settings_dir/$settings_file" ]; then
settings_path="$settings_dir/$settings_file"
break
fi
new_settings_dir="$(dirname "$settings_dir")"
if [ "$new_settings_dir" = "$settings_dir" ]; then
settings_path=""
break
fi
settings_dir="$new_settings_dir"
done
else
settings_path=""
fi
if [ -n "$settings_path" ]; then
echo "Calling mvn with -s $settings_path $*" >&2
exec _mvn -s "$settings_path" "$@"
else
exec _mvn "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment