Aide-mémoire Apache Ant
Aide-mémoire Apache Ant
Installation
| Plateforme | Commande |
|---|---|
| Ubuntu/Debian | sudo apt update && sudo apt install ant |
| RHEL/CentOS/Fedora | sudo yum install ant or sudo dnf install ant |
| Arch Linux | sudo pacman -S apache-ant |
| macOS (Homebrew) | brew install ant |
| Windows (Chocolatey) | choco install ant |
| Manual (All Platforms) | Download from apache.org, extract, set ANT_HOME and add bin/ to PATH |
Prérequis : Java JDK 8+ requis. Définir JAVA_HOMEvariable d’environnement. |
Commandes de base
| Commande | Description |
|---|---|
ant -version | Afficher la version d’Ant, la version de Java et les informations du système d’exploitation |
ant | Exécuter la cible par défaut spécifiée dans build.xml |
ant compile | Exécutez la cible “compile” depuis build.xml |
ant clean | Exécuter la cible “clean” (supprime généralement les artefacts de compilation) |
ant -projecthelp | Lister tous les targets disponibles avec leurs descriptions |
ant -p | Forme abrégée de -projecthelp |
ant -f custom-build.xml | Utiliser un fichier de build alternatif au lieu de build.xml |
ant -buildfile mybuild.xml compile | Spécifier le fichier de build et la cible à exécuter |
ant -verbose compile | Afficher les informations détaillées d’exécution |
ant -v test | Forme abrégée de -verbose |
ant -debug package | Verbosité maximale pour le dépannage |
ant -d deploy | Forme abrégée de -debug |
ant -quiet test | Sortie minimale, afficher uniquement les erreurs |
ant -q build | Forme abrégée de -quiet |
ant -logfile build.log compile | Rediriger la sortie vers le fichier journal spécifié |
ant -l output.log test | Forme abrégée de -logfile |
Utilisation avancée
| Commande | Description |
|---|---|
ant -Denv=production deploy | Définir la valeur de propriété en ligne de commande |
ant -Dversion=1.2.3 -Dbuild.number=456 package | Définir plusieurs propriétés |
ant -propertyfile custom.properties build | Charger les propriétés depuis un fichier externe |
ant -find | Rechercher les répertoires parents pour build.xml |
ant -s | Forme courte de -find |
ant -keep-going test | Continuer à exécuter des cibles indépendantes après un échec |
ant -k test | Forme abrégée de -keep-going |
ant -diagnostics | Afficher les informations système et les détails de configuration |
ant -listener org.apache.tools.ant.listener.Log4jListener compile | Ajouter un écouteur d’événement de build personnalisé |
ant -logger org.apache.tools.ant.NoBannerLogger compile | Utiliser une implémentation de logger personnalisée |
ant -inputhandler org.apache.tools.ant.input.SecureInputHandler deploy | Utiliser un gestionnaire d’entrée personnalisé pour une entrée sécurisée |
ant -noclasspath compile | Ignorer la variable d’environnement CLASSPATH |
ant -autoproxy download | Configurer automatiquement les paramètres de proxy Java |
ant -lib /path/to/jars compile | Ajouter un répertoire de JARs au classpath d’Ant |
ant -Dant.executor.class=org.apache.tools.ant.helper.ParallelExecutor build | Activer l’exécution de tâches en parallèle |
ant compile test package | Exécuter plusieurs cibles en séquence |
ant -Dskip.tests=true package | Ignorer conditionnellement des tâches en fonction d’une propriété |
Configuration
Structure de base du fichier build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="MyProject" default="build" basedir=".">
<!-- Properties -->
<property name="src.dir" value="src"/>
<property name="build.dir" value="build"/>
<property name="dist.dir" value="dist"/>
<property name="lib.dir" value="lib"/>
<!-- Classpath -->
<path id="classpath">
<fileset dir="${lib.dir}">
<include name="**/*.jar"/>
</fileset>
</path>
<!-- Clean target -->
<target name="clean" description="Remove build artifacts">
<delete dir="${build.dir}"/>
<delete dir="${dist.dir}"/>
</target>
<!-- Init target -->
<target name="init" depends="clean">
<mkdir dir="${build.dir}"/>
<mkdir dir="${dist.dir}"/>
</target>
<!-- Compile target -->
<target name="compile" depends="init" description="Compile source code">
<javac srcdir="${src.dir}"
destdir="${build.dir}"
classpathref="classpath"
includeantruntime="false"
debug="true"
source="11"
target="11"/>
</target>
<!-- Build target -->
<target name="build" depends="compile" description="Build JAR file">
<jar destfile="${dist.dir}/${ant.project.name}.jar"
basedir="${build.dir}">
<manifest>
<attribute name="Main-Class" value="com.example.Main"/>
</manifest>
</jar>
</target>
</project>
Fichier build.properties
# Project configuration
project.name=MyApplication
project.version=1.0.0
# Directory structure
src.dir=src/main/java
test.dir=src/test/java
resources.dir=src/main/resources
build.dir=target/classes
dist.dir=dist
# Compiler settings
java.source.version=11
java.target.version=11
javac.debug=true
javac.deprecation=true
# Dependencies
lib.dir=lib
Chargement des propriétés dans build.xml
<property file="build.properties"/>
<property file="build-${env}.properties"/>
<property environment="env"/>
Ensembles de fichiers et modèles courants
<!-- Include all Java files -->
<fileset dir="${src.dir}" includes="**/*.java"/>
<!-- Exclude test files -->
<fileset dir="${src.dir}">
<include name="**/*.java"/>
<exclude name="**/*Test.java"/>
</fileset>
<!-- Pattern sets for reuse -->
<patternset id="source.patterns">
<include name="**/*.java"/>
<include name="**/*.properties"/>
<exclude name="**/*Test.java"/>
</patternset>
Cas d’utilisation courants
Cas d’utilisation : Construction complète d’une application Java
# Clean previous builds
ant clean
# Compile, test, and package in one command
ant compile test package
# Build with specific environment properties
ant -Denv=production -propertyfile prod.properties package
# Create distribution with documentation
ant clean compile test package javadoc dist
Cibles du build.xml :
<target name="test" depends="compile">
<junit printsummary="yes" haltonfailure="yes">
<classpath>
<path refid="classpath"/>
<pathelement location="${build.dir}"/>
</classpath>
<batchtest fork="yes">
<fileset dir="${test.dir}">
<include name="**/*Test.java"/>
</fileset>
</batchtest>
</junit>
</target>
<target name="javadoc">
<javadoc sourcepath="${src.dir}"
destdir="${dist.dir}/docs"
packagenames="com.example.*"/>
</target>
Cas d’utilisation : Création de fichier WAR pour application web
# Build and package web application
ant clean compile war
# Deploy to application server
ant -Dserver.path=/opt/tomcat/webapps deploy
Configuration du build.xml :
<target name="war" depends="compile">
<war destfile="${dist.dir}/${project.name}.war"
webxml="web/WEB-INF/web.xml">
<classes dir="${build.dir}"/>
<lib dir="${lib.dir}"/>
<fileset dir="web">
<include name="**/*.jsp"/>
<include name="**/*.html"/>
<include name="**/*.css"/>
<include name="**/*.js"/>
</fileset>
</war>
</target>
<target name="deploy" depends="war">
<copy file="${dist.dir}/${project.name}.war"
todir="${server.path}"/>
</target>
Cas d’utilisation : Construction de projet multi-modules
# Build all modules in parallel
ant -Dant.executor.class=org.apache.tools.ant.helper.ParallelExecutor build-all
# Build specific module
ant -Dmodule=core build-module
# Build and run integration tests
ant build-all integration-test
build.xml avec sous-projets :
<target name="build-all">
<subant target="build">
<fileset dir="." includes="*/build.xml"/>
</subant>
</target>
<target name="build-module">
<ant dir="${module}" target="build" inheritAll="false"/>
</target>
Cas d’utilisation : Builds conditionnels avec vérification de propriété
# Skip tests during build
ant -Dskip.tests=true package
# Build only if sources changed
ant -Dincremental=true compile
# Production build with optimizations
ant -Doptimize=true -Ddebug=false production-build
build.xml avec conditions :
<target name="compile">
<javac srcdir="${src.dir}"
destdir="${build.dir}"
debug="${debug}"
optimize="${optimize}">
<classpath refid="classpath"/>
</javac>
</target>
<target name="test" unless="skip.tests">
<junit printsummary="yes">
<classpath>
<path refid="classpath"/>
<pathelement location="${build.dir}"/>
</classpath>
<batchtest>
<fileset dir="${test.dir}" includes="**/*Test.java"/>
</batchtest>
</junit>
</target>
<target name="package" depends="compile,test">
<jar destfile="${dist.dir}/${ant.project.name}.jar"
basedir="${build.dir}"/>
</target>
Cas d’utilisation : Migration et déploiement de base de données
# Run database migrations
ant -propertyfile db-config.properties db-migrate
# Deploy application with database updates
ant -Denv=staging db-migrate deploy
# Rollback database changes
ant -Dversion=1.2.0 db-rollback
build.xml avec tâches SQL :
<target name="db-migrate">
<sql driver="${db.driver}"
url="${db.url}"
userid="${db.user}"
password="${db.password}"
src="migrations/migrate-${version}.sql"
print="yes"
output="migration.log"/>
</target>
<target name="db-rollback">
<sql driver="${db.driver}"
url="${db.url}"
userid="${db.user}"
password="${db.password}"
src="migrations/rollback-${version}.sql"/>
</target>
Meilleures pratiques
-
Utiliser des fichiers de propriétés pour la configuration : Séparer les paramètres spécifiques à l’environnement de la logique de build. Charger les propriétés avec
<property file="build.properties"/>to keep build.xml clean and reusable. -
Define meaningful target descriptions: Add
descriptionattributes to public targets for betterant -projecthelpoutput. This serves as built-in documentation for your build process. -
Leverage target dependencies: Use
dependsattribute to establish build order and avoid redundant task execution. Ant automatically handles dependency resolution. -
Set
includeantruntime="false"in javac tasks: Prevents Ant runtime libraries from polluting your application classpath, avoiding potential conflicts and reducing JAR size. -
Use filesets and pattern sets for flexibility: Define reusable file patterns with
<patternset>and reference them in multiple targets. This makes maintenance easier and reduces duplication. -
Implement incremental builds: Use
<uptodate>conditions to skip compilation when source files haven’t changed, significantly speeding up development builds. -
Version control your build files: Include
build.xml, property files, and custom tasks in version control. Exclude generated directories likebuild/anddist/using.gitignore. -
Use macros for repeated task sequences: Define
<macrodef>elements for common operations performed across multiple modules or targets, promoting DRY principles. -
Separate concerns with imported build files: Split large build files into logical components (
common-build.xml,test-build.xml) et les importer pour améliorer la maintenabilité. -
Documenter la logique complexe avec des commentaires : Utilisez des commentaires XML pour expliquer la logique de construction non évidente, l’utilisation des propriétés et les dépendances, en particulier dans les projets partagés ou hérités.
Résolution des problèmes
| Problème | Solution |
|---|---|
BUILD FAILED: build.xml does not exist | Run ant -find to search parent directories, or specify file with ant -f path/to/build.xml |
Unable to locate tools.jar | Set JAVA_HOME to JDK (not JRE) directory. Verify with echo $JAVA_HOME and ensure it points to JDK installation |
ClassNotFoundException for custom tasks | Add JAR to Ant’s classpath using -lib option: ant -lib /path/to/jars compile or use <taskdef> with correct classpath |
| Compilation fails with encoding errors | Add encoding="UTF-8" attribute to <javac> task: <javac srcdir="${src.dir}" encoding="UTF-8"/> |
| Out of memory during build | Increase heap size: export ANT_OPTS="-Xmx1024m -Xms512m" (Linux/Mac) or set ANT_OPTS=-Xmx1024m (Windows) |
| Target not found error | Verify target name with ant -projecthelp. Check for typos and ensure target is defined in active build file |
| Circular dependency detected | Review depends attributes in targets. Ant cannot resolve circular references - redesign target dependencies |
| Permission denied when writing files | Vérifiez les permissions du répertoire et assurez-vous qu’Ant a un accès en écriture. Exécutez avec les privilèges utilisateur appropriés ou ajustez la propriété du répertoire |
fork="true" required but task fails | Some tasks (junit, java) require forking. Ensure fork="true" is set and JAVA_HOME points to valid JDK |
| Properties not being overridden | Properties are immutable in Ant - first definition wins. Set properties via command line (-D) before build file loads them |
| Slow builds with large filesets | Use <uptodate> conditions for incremental builds. Enable parallel execution with -Dant.executor.class=org.apache.tools.ant.helper.ParallelExecutor |
| JAR file manifest not correct | Use <manifest> element within <jar> task to specify Main-Class and other attributes explicitly |
Référence des tâches Ant courantes
| Tâche | Description | Exemple |
|---|---|---|
<javac> | Compiler les fichiers sources Java | <javac srcdir="src" destdir="build" includeantruntime="false"/> |
<jar> | Créer une archive JAR | <jar destfile="dist/app.jar" basedir="build"/> |
<war> | Créer une archive WAR | <war destfile="dist/app.war" webxml="web/WEB-INF/web.xml"/> |
<copy> | Copier des fichiers ou des répertoires | <copy todir="backup"><fileset dir="src"/></copy> |
<delete> | Supprimer des fichiers ou des répertoires | <delete dir="build"/> |
<mkdir> | Créer un répertoire | <mkdir dir="dist"/> |
<echo> | Imprimer message | <echo message="Building version ${version}"/> |
<exec> | Exécuter la commande système | <exec executable="git" args="rev-parse HEAD"/> |
<junit> | Exécuter des tests JUnit | <junit printsummary="yes" fork="yes"/> |
<zip> | Créer une archive ZIP | <zip destfile="dist/src.zip" basedir="src"/> |
<sql> | Exécuter des instructions SQL | <sql driver="${db.driver}" url="${db.url}" src="schema.sql"/> |