Ant 15 best practices

Source: Internet
Author: User
ArticleDirectory
    • 1. adopt consistent encoding specifications
    • 3. Use a single Build File
    • 4. Provide good help
    • 5. Clear tasks
    • 6. Use ant to manage task subordination
    • 7. Define and reuse the file path
    • 8. Define proper task subordination
    • 9. Use attributes
    • 10. Keep the build process independent
    • 11. Use the version control system
    • 12. Use ant as the "minimum denominator"
    • 13. Use the zipfileset attribute
    • 14. Test the clean task
    • 15. Avoid ant encapsulation for specific platforms
    • Summary
    • Reference
Ant Top 10 Best Practices

From: http://oreilly.com.cn/news/ant15toppractices.php? C = Java

 

Author: Eric M. Burke, coauthor of Java eXtreme Programming cookbook

Original article: http://www.onjava.com/pub/a/onjava/2003/12/17/ant_bestpractices.html

Xu Tong http://www.cnblogs.com/itech/admin/msn:xt121@hotmail.com

 

Before ant emerged, Java applications should be built and deployed using a "hodgedge" that includes scripts, make files, various versions of IDE, and even manual operations on specific platforms ". Currently, almost all open-source Java projects are using ant, and most internal projects are using ant. The wide use of ant in these projects naturally leads to an urgent need for a set of ant best practices.

This article summarizes my favorite ant skills or best practices, most of which are inspired by my personal project errors or the "Terror" stories I 've heard from others. For example, someone told me that a project generated by XDocletCodePut it in a version control tool with the lock file function. When a developer modifiesSource codeRemember to manually check out and lock all the files to be regenerated. Then, manually run the code generator so that ant can compile the Code only now. This method still has the following problems:

    • The generated code cannot be stored in the version control system.
    • Ant (XDoclet in this case) should automatically determine the source files involved in the next build, insteadProgramManually confirm.
    • The ant build file should define the correct task dependency, so that the programmer does not have to call the task in a specific order to complete the build.

When I start a new project, I first write the ant build file. The ant file clearly defines the build process and is used by every programmer in the team. The techniques listed in this article are based on the assumption that ant builds a file, which must be carefully written, should be maintained in the version control system and reconstructed on a regular basis. Below are my top 10 ant best practices.

1. adopt consistent encoding specifications

Some ant users like some hate the XML syntax of their build files. Rather than jumping into this confusing debate, let's take a look at some methods that keep the XML Build File concise.

First and foremost, it takes time to format your XML to make it clear. Ant can work regardless of whether XML is beautiful or not. However, ugly XML is hard to understand. If you leave blank lines between tasks with regular indentation, each line of text cannot exceed 90 columns, XML is surprisingly easy to read. In addition, you can use excellent editors or IDE tools that can highlight the XML syntax, so you will not have to read it.

Similarly, you can select words with clear meanings and easy to understand to name tasks and attributes. For example,Dir. ReportsRatioRptsGood.A specific encoding specification is not important. You only need to come up with a set of specifications and stick to them.

2. Set Build. xml In the project root directory

Ant Build FileBuild. xmlIt can be placed anywhere, but in the top-level directory of the project, it can keep the project concise. This is the most common specification. developers can find the expected specification in the top-level directory.Build. xml. Placing the build file in the root directory also makes it easy to understand the logical relationship between different directories in the project directory tree. The following is a typical project directory hierarchy:

[Root dir]
| Build. xml
+ -- SRC
+ -- Lib (including third-party jar packages)
+ -- Build (generated by the build task)
+ -- Dist (generated by the build task)

WhenBuild. xmlIn the top-level directory, if you are in a subdirectory of the project, you only need to enter the: ant-find compile command, and you can compile the code using the command line without changing the working directory. The parameter-find tells ant to find the file that exists in the parent directory.Build. xmlAnd execute.

3. Use a single Build File

Some people like to break down a large project into several small build files, and each build file shares a small part of the entire build process. This is indeed a matter of different views, but we should realize that splitting the build file will increase the difficulty of understanding the overall build process. Be sure to avoid engineering when a single build file clearly shows the build level ).

Even if you divide the project into multiple build files, you should also enable the programmer to find the core under the project root directory.Build. xml. Although the file only delegates the actual build work to the lower-level build file, the file should also be available.

4. Provide good help

Make the building file self-document as much as possible. Adding a task description is the easiest way. When you enter ant-projecthelp, you can see a list of jobs with descriptions. For example, you can define a task as follows:

<Target name = "compile"
Description = "compiles code, output goes to the build dir.">

The simplest rule is to describe all the tasks that you want programmers to call through the command line. Description attributes cannot be used for internal tasks generally used to execute intermediate processing processes, such as generating code or creating output directories.

In this case, you can add XML annotations to the build file for processing. You can also define a help task to show detailed instructions when the programmer inputs ant help.

<Target name = "help" Description = "display detailed usage information">
<Echo> Detailed Help... </echo> </Target>

5. Clear tasks

Each build file should contain a clear task to delete all generated files and directories so that the system returns to the initial state before the build file is executed. After the clear task is executed, all the files that still exist should be managed by the version control system. For example:

<Target name = "clean"
Description = "destroys all generated files and dirs.">
<Delete dir = "$ {dir. Build}"/>
<Delete dir = "$ {dir. Dist}"/>
</Target>

Do not automatically call the clean task unless it is a special task that generates the entire system version. When programmers only execute compilation tasks or other tasks, they do not need to build files to execute annoying and unnecessary clearing tasks in advance. Believe that programmers can determine when to clear all files.

6. Use ant to manage task subordination

Assume that your application consists of the swing GUI component, Web interface, EJB layer, and public application code. In large systems, you need to clearly define which layer of the system each Java package belongs. Otherwise, hundreds of thousands of files will be re-compiled for any modifications. Poor task subordination management can lead to overly complex and fragile systems. Changing the GUI panel design should not cause re-Compilation of Servlet and EJB.

When the system becomes large, the Code dependent on the client may be introduced to the server if you do not pay attention to it. This is because a typical ide project file uses a single classpath to compile any file. Ant allows you to control building activities more effectively.

Design your ant build file to compile a large project: first, compile the public application code and compress the compilation result into a jar package file. Then, compile the project code at the previous layer and rely on the JAR file generated in the first step during compilation. Repeat this process until the code compilation at the highest level is complete.

Step-by-Step building enhances task subordination management. If you work on the underlying Java framework and occasionally reference high-level GUI template components, the Code does not need to be compiled. This is because the build file does not contain the code of the high-level GUI panel component in the source path when compiling the underlying framework.

7. Define and reuse the file path

If the file path is defined centrally in one place and reused in the entire build file, the build file is easier to understand. The following is an example:

<Project name = "sample" default = "compile" basedir = ".">
<Path id = "classpath. Common">
<Pathelement location = "$ {JDOM. Jar. withpath}"/>
... Etc </path>
<Path id = "classpath. Client">
<Pathelement location = "$ {guistuff. Jar. withpath}"/>
<Pathelement location = "$ {another. Jar. withpath}"/>
<! -- Reuse the common classpath -->
<Path refID = "classpath. Common"/>
</Path>
<Target name = "compile. Common" depends = "prepare">
<Javac destdir = "$ {dir. Build}" srcdir = "$ {dir. SRC}">
<Classpath refID = "classpath. Common"/>
<Include name = "com/oreilly/common/**"/>
</Javac>
</Target>
</Project>

As the project grows and the construction becomes increasingly complex, this technology is becoming more and more valuable. You may need to define different file paths for compiling applications of different levels, such as running unit tests, running applications, running XDoclet, and generating javadocs. This method of defining the componentized path is much better than defining the path separately for each task. Otherwise, the track of task subordination is easily lost.

8. Define proper task subordination

Assume that the DIST task belongs to the jar task, which task belongs to the compile task and which task belongs to the prepare task? The ant Build File ultimately defines the dependency diagram of the task, which must be carefully defined and maintained.

The dependencies of tasks should be checked regularly to ensure that the build work is correctly executed. Large build files tend to add more tasks over time, so it is very difficult to build a file due to unnecessary subordination at the end. For example, you may find that the programmer only needs to re-generate the EJB code when compiling some gui code that does not use EJB.

Ignoring the subordination of a task in the name of "optimization" is another common error. This error forces programmers to remember and call a series of tasks in a specific order to get the appropriate results. Better practice: provide clear descriptions of common tasks that contain the correct task subordination, and provide a set of "expert" tasks that allow you to perform individual building steps manually, these tasks do not provide a complete build process, but allow expert users to skip some steps during fast and annoying coding.

9. Use attributes

Any information that requires configuration or may change should be defined as the ant attribute. The same is true for values that appear multiple times in the build file. Attributes can be defined either in the build file header or separately in an attribute file for better flexibility. The following is a style that defines attributes in the build file:

<Project name = "sample" default = "compile" basedir = ".">
<Property name = "dir. Build" value = "build"/>
<Property name = "dir. SRC" value = "src"/>
<Property name = "JDOM. Home" value = "../Java-tools/jdom-b8"/>
<Property name = "JDOM. Jar" value = "JDOM. Jar"/>
<Property name = "JDOM. Jar. withpath"
Value = "$ {JDOM. Home}/build/$ {JDOM. Jar}"/>
Etc...
</Project>

Or you can use the property file:

<Project name = "sample" default = "compile" basedir = ".">
<Property file = "sample. properties"/>
Etc...
</Project>

In the Property FileSample. PropertiesMedium:

Dir. Build = build
Dir. src = SRC
JDOM. Home = ../Java-tools/jdom-b8
JDOM. Jar = JDOM. jarjdom. Jar. withpath =$ {JDOM. Home}/build/$ {JDOM. Jar}

It is advantageous to define attributes in an independent file, which can clearly define the configurable part in the build. In addition, when developers work on different operating systems, you can provide different versions of the file on different platforms.

10. Keep the build process independent

To maximize scalability, do not apply external paths and library files. The most important thing is not to rely on the programmer's classpath settings. Instead, use relative paths in the build file and define your own paths. If you reference an absolute path, for exampleC: \ Java \ toolsOther developers may not use the same directory structure as you, so they will not be able to use your build files.

If you deploy an open source project, you should provide the release versions of all jar files required to compile the code. Of course, this is based on compliance with the license agreement. For internal projects, relevant jar files should be managed in the version control system and checked out to a location that everyone knows.

When you must reference an external path, define the path as an attribute. Enable programmers to overload these attributes with parameters that suit their own machine environment. You can also use the following syntax to reference environment variables:

<Property environment = "env"/>
<Property name = "dir. JBoss" value = "$ {env. jboss_home}"/>

11. Use the version control system

Building a file is an important product and version control should be performed like code. When you mark your code, the same tag is also applied to the build file. In this way, you can use the corresponding build file when you need to trace back to the old version and build it.

In addition to building files, you should also maintain third-party jar files in version control. Similarly, this allows you to re-build the old version of the software. This also makes it easier to ensure that all developers have consistent jar files, because they are extracted from the version control system together with the build files.

Generally, building results should not be stored in the version control system. If your source code is well controlled, You can regenerate any version of the product through the build process.

12. Use ant as the "minimum denominator"

If your development team uses ide tools, why do programmers need to worry about ant when they click the icon to build the entire application?

The issue with IDE is about team consistency and reproducibility. Almost all IDE is designed to improve the individual productivity of programmers, rather than the continuous construction of development teams. A typical IDE requires each programmer to define their own project files. Programmers may have different directory structures, may use different versions of library files, and may work on different platforms. This will lead to this situation: the code that runs well in Bob cannot run in Sally.

No matter what ide your development team uses, you must create ant build files that all programmers can use. To create a programmer, you must execute the ant Build File rules before submitting the new code to the version control system. This ensures that the code is built through the same ant build file. When a problem occurs, use the ant build file of the Project Standard instead of executing a clean build through an IDE.

Programmers are free to choose any IDE tool or editor they are used. However, ant should serve as a public baseline to ensure that the Code is always buildable.

13. Use the zipfileset attribute

Ant is often used to generate war, jar, zip, and ear files. These files usually require a specific internal directory structure, but they often do not match the directory structure of your source code and the compiling environment.

the most common method is to write an ant task, copy a large number of files to a temporary directory according to the expected directory structure, and generate a compressed file. This is not the most effective method. Using the zipfileset attribute is a better solution. It allows you to select files from any location and put them into the compressed files according to different directory structures. The following is an example:

appxml =" $ {dir. resources}/application. XML ">
















In this example, all jar files are stored inLibDirectory. HR. jar and billing. jar are copied from the build directory. Therefore, we use the zipfileset attribute to move them toLibDirectory. The prefix attribute specifies the target path in the ear file.

14. Test the clean task

If your build file contains clean and compile tasks, perform the following tests. Step 1: Execute ant clean; Step 2: Execute ant compile; Step 3: Execute ant compile. Step 3 should not do anything. If the file is compiled again, it indicates that there is a problem with your build file.

The Build File should only execute the task when the input file associated with the output file changes. It is inefficient for a Build File to execute tasks such as compilation, copying, or other work tasks. When the project grows, even small and inefficient work will become a big problem.

15. Avoid ant encapsulation for specific platforms

For whatever reason, some people prefer the simple nameCompileSuch as batch files or scripts to load their products. When you look at the script content, you will find the following content:

Ant compile

In fact, developers are familiar with ant, and can completely type ant compile by themselves. Do not use scripts for specific platforms just to call ant. This will only make others learn and understand your script for the first time. In addition, you cannot provide scripts for each operating system, which is really disturbing other users.

Summary

Too many companies rely on manual methods and special programs to compile code and generate software releases. Development teams that do not use ant or similar tools to define the Build Process spend too much time Capturing problems in the code compilation process: Code Compiled successfully by some developers, but it failed to go to other developers.

Generating and maintaining build scripts is not an attractive task, but a necessary task. A good ant build file will enable you to concentrate on your favorite job-write code!

Reference
    • ant
    • antgraph: ant dependent visualization tool
    • ant: the definitive guide, O 'Reilly
    • JAVA eXtreme Programming cookbook, O 'Reilly

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.