Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Created September 17, 2025 16:56
Show Gist options
  • Select an option

  • Save WomB0ComB0/2ac83fc3b56f770399098cb7ebea429e to your computer and use it in GitHub Desktop.

Select an option

Save WomB0ComB0/2ac83fc3b56f770399098cb7ebea429e to your computer and use it in GitHub Desktop.
jmaven - Enhanced with AI-generated documentation
#!/usr/bin/env bash
set -euo pipefail
# Defaults
NAME=""
GROUP_ID="com.example"
ARTIFACT_ID=""
PACKAGE=""
ARCH_GID="org.apache.maven.archetypes"
ARCH_AID="maven-archetype-quickstart"
ARCH_VER="1.5" # Quickstart page lists 1.5 as current
JAVA_VER="" # If unset, archetype default is used
JUNIT_VER="" # If unset, archetype default is used
OUTPUT_DIR="$(pwd)"
BATCH=true
DRY_RUN=false
FORCE=false
usage() {
cat <<'EOF'
Usage: new-mvn.sh [-n NAME] [-g GROUP_ID] [-a ARTIFACT_ID] [-p PACKAGE]
[-G ARCH_GROUP_ID] [-T ARCH_ARTIFACT_ID] [-A ARCH_VERSION]
[-J JAVA_COMPILER_VERSION] [-U JUNIT_VERSION]
[-o OUTPUT_DIR] [--no-batch] [--dry-run] [-f] [-h]
Options:
-n NAME Human-friendly project/app name (used to derive artifactId if -a not set)
-g GROUP_ID Maven groupId (default: com.example)
-a ARTIFACT_ID Maven artifactId (default: derived from NAME)
-p PACKAGE Base Java package (default: GROUP_ID + '.' + artifactId with '-' -> '_')
-G ARCH_GROUP_ID Archetype groupId (default: org.apache.maven.archetypes)
-T ARCH_ARTIFACT_ID Archetype artifactId (default: maven-archetype-quickstart)
-A ARCH_VERSION Archetype version (default: 1.5)
-J JAVA_COMPILER_VERSION Passes -DjavaCompilerVersion (optional)
-U JUNIT_VERSION Passes -DjunitVersion (optional)
-o OUTPUT_DIR Where to generate the project (default: current dir)
--no-batch Don’t use Maven batch mode (-B)
--dry-run Print the mvn command without executing
-f Force: skip existence checks on target directory
-h Show this help
EOF
}
slugify_artifact() {
# Lowercase, spaces/underscores -> '-', remove invalid chars, collapse dashes
local s="${1,,}"
s="${s// /-}"
s="${s//_/-}"
s="$(echo "$s" | sed -E 's/[^a-z0-9.-]+/-/g; s/-+/-/g; s/^-+//; s/-+$//')"
# Ensure not empty
if [[ -z "$s" ]]; then s="app"; fi
echo "$s"
}
pkg_from_group_and_artifact() {
local gid="$1"
local aid="$2"
# artifactId '-' -> '_' for a legal package segment
local seg="${aid//-/_}"
# Remove illegal characters from package segment
seg="$(echo "$seg" | sed -E 's/[^A-Za-z0-9_]+/_/g')"
echo "${gid}.${seg}"
}
require_cmd() {
command -v "$1" >/dev/null 2>&1 || { echo "Error: '$1' not found in PATH" >&2; exit 127; }
}
# Parse args
while (( "$#" )); do
case "$1" in
-n) NAME="$2"; shift 2;;
-g) GROUP_ID="$2"; shift 2;;
-a) ARTIFACT_ID="$2"; shift 2;;
-p) PACKAGE="$2"; shift 2;;
-G) ARCH_GID="$2"; shift 2;;
-T) ARCH_AID="$2"; shift 2;;
-A) ARCH_VER="$2"; shift 2;;
-J) JAVA_VER="$2"; shift 2;;
-U) JUNIT_VER="$2"; shift 2;;
-o) OUTPUT_DIR="$2"; shift 2;;
--no-batch) BATCH=false; shift;;
--dry-run) DRY_RUN=true; shift;;
-f) FORCE=true; shift;;
-h|--help) usage; exit 0;;
*) echo "Unknown option: $1" >&2; usage; exit 2;;
esac
done
# Derive artifactId from NAME if needed
if [[ -z "${ARTIFACT_ID}" ]]; then
if [[ -z "${NAME}" ]]; then
echo "Error: provide at least -n NAME or -a ARTIFACT_ID" >&2
usage; exit 2
fi
ARTIFACT_ID="$(slugify_artifact "$NAME")"
fi
# Derive package if missing
if [[ -z "${PACKAGE}" ]]; then
PACKAGE="$(pkg_from_group_and_artifact "$GROUP_ID" "$ARTIFACT_ID")"
fi
# Prepare target directory check
TARGET_DIR="${OUTPUT_DIR%/}/${ARTIFACT_ID}"
if ! $FORCE; then
if [[ -e "$TARGET_DIR" ]]; then
echo "Error: target directory already exists: $TARGET_DIR (use -f to override)" >&2
exit 3
fi
fi
require_cmd mvn
# Build mvn command
args=()
$BATCH && args+=("-B")
args+=("archetype:generate")
args+=("-DarchetypeGroupId=${ARCH_GID}")
args+=("-DarchetypeArtifactId=${ARCH_AID}")
args+=("-DarchetypeVersion=${ARCH_VER}")
args+=("-DgroupId=${GROUP_ID}")
args+=("-DartifactId=${ARTIFACT_ID}")
args+=("-Dpackage=${PACKAGE}")
args+=("-DoutputDirectory=${OUTPUT_DIR}")
# Only pass Java/JUnit if explicitly set
[[ -n "$JAVA_VER" ]] && args+=("-DjavaCompilerVersion=${JAVA_VER}")
[[ -n "$JUNIT_VER" ]] && args+=("-DjunitVersion=${JUNIT_VER}")
echo ">>> Running:"
printf 'mvn %q ' "${args[@]}"
echo
if $DRY_RUN; then
echo "(dry run)"; exit 0
fi
mvn "${args[@]}"
echo
echo "✓ Project generated at: ${TARGET_DIR}"
echo " Next steps:"
echo " cd ${TARGET_DIR}"
echo " mvn -q -ntp test"

jmaven

File Type: TXT
Lines: 144
Size: 4.4 KB
Generated: 9/17/2025, 12:56:13 PM


Code Analysis: new-mvn.sh

This is a Bash script designed to streamline the creation of new Maven projects using Maven archetypes. It automates the process of generating a project structure based on user-defined parameters or defaults.

Purpose:

The script simplifies the creation of new Maven projects by:

  • Providing a command-line interface for specifying project details.
  • Deriving default values for missing parameters (e.g., artifactId from project name, package name from groupId and artifactId).
  • Executing the mvn archetype:generate command with the appropriate parameters.
  • Performing basic error checking (e.g., checking for the existence of the target directory).

Key Elements and Functionality:

  1. Argument Parsing:

    • The script uses getopts (implicitly through the while loop and case statement) to parse command-line arguments.
    • It supports options for specifying the project name (-n), groupId (-g), artifactId (-a), package name (-p), archetype coordinates (-G, -T, -A), Java and JUnit versions (-J, -U), output directory (-o), batch mode (--no-batch), dry-run mode (--dry-run), and force mode (-f).
  2. Default Value Derivation:

    • If the artifactId is not provided (-a), it's derived from the project name (-n) using the slugify_artifact function.
    • If the package name is not provided (-p), it's derived from the groupId and artifactId using the pkg_from_group_and_artifact function.
  3. slugify_artifact Function:

    • This function takes a string (presumably the project name) as input and transforms it into a valid artifactId.
    • It converts the string to lowercase, replaces spaces and underscores with hyphens, removes invalid characters, and collapses multiple hyphens into a single hyphen.
  4. pkg_from_group_and_artifact Function:

    • This function takes the groupId and artifactId as input and constructs a default package name.
    • It replaces hyphens in the artifactId with underscores to create a valid package segment.
  5. require_cmd Function:

    • This function checks if a given command is available in the system's PATH.
    • It's used to ensure that Maven (mvn) is installed before proceeding.
  6. Target Directory Check:

    • The script checks if the target directory already exists.
    • If it does, the script exits with an error message unless the -f (force) option is specified.
  7. Maven Command Construction:

    • The script constructs the mvn archetype:generate command with the appropriate parameters based on the user's input and the derived default values.
    • It uses an array (args) to store the command-line arguments.
    • Conditional logic is used to include optional parameters (e.g., Java and JUnit versions) only if they are explicitly set.
  8. Execution:

    • If the --dry-run option is specified, the script prints the mvn command without executing it.
    • Otherwise, the script executes the mvn command using mvn "${args[@]}".
  9. Post-Generation Instructions:

    • After the project is generated, the script prints instructions on how to navigate to the project directory and run the tests.

Runtime and Dependencies:

  • Bash: The script is written in Bash and requires a Bash interpreter to run.
  • Maven: The script depends on Maven (mvn) being installed and available in the system's PATH.
  • sed: The slugify_artifact and pkg_from_group_and_artifact functions use sed for string manipulation.

How it Works:

  1. The script parses command-line arguments to gather project details.
  2. It derives default values for missing parameters.
  3. It checks for the existence of the target directory.
  4. It constructs the mvn archetype:generate command with the appropriate parameters.
  5. It executes the mvn command (unless --dry-run is specified).
  6. It prints post-generation instructions.

Usage:

To use the script, save it to a file (e.g., new-mvn.sh) and make it executable (chmod +x new-mvn.sh). Then, run it from the command line with the desired options.

Example:

./new-mvn.sh -n MyProject -g com.example -a myproject

This will generate a new Maven project with the name "MyProject", groupId "com.example", and artifactId "myproject" in the current directory.

Next Steps and Potential Improvements:

  • More Robust Error Handling: The script could be improved by adding more robust error handling, such as checking for invalid input values and handling Maven execution errors.
  • Interactive Mode: The script could be extended to support an interactive mode where the user is prompted for missing parameters.
  • Archetype Selection: The script could allow the user to select from a list of available Maven archetypes.
  • Parameter Validation: Add validation to ensure parameters like JAVA_VER and JUNIT_VER are valid versions.
  • Configuration File: Allow reading default values from a configuration file.
  • Logging: Implement more detailed logging for debugging purposes.
  • Progress Bar: Add a progress bar or spinner during the Maven archetype generation process.

Description generated using AI analysis

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