Re: ant task to compute lines of code
On 11/18/2012 10:43 AM, Laura Schmidt wrote:
Hello,
I want to find out the total lines of code of a project using an ant task.
On the commandline I would do this like this:
find src -name *.java | wc -l
In ant, I only managed to output all the code:
<target name="loc">
<exec executable="find">
<arg line="src -name *.java -exec cat {} ;"/>
</exec>
</target>
So I can get the loc like this:
ant -f project.xml loc | wc -l
But how can I integrate the "wc -l" in the ant task?
I would code an ant task to do it.
Actually I have.
:-)
See below.
Arne
================
code:
package dk.vajhoej.anttasks.codestats;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
public class JavaCodeStatsTask extends Task {
private String label;
private boolean cf;
private boolean cl;
private List<FileSet> allfs = new ArrayList<FileSet>();
@Override
public void execute() {
int nf = 0;
int nl = 0;
for(FileSet fs : allfs) {
DirectoryScanner ds = fs.getDirectoryScanner();
for(String fnm : ds.getIncludedFiles()) {
File f = new File(ds.getBasedir(), fnm);
nf++;
try {
BufferedReader br = new BufferedReader(new
FileReader(f));
while(br.readLine() != null) {
nl++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(label + ":");
if(cf) {
System.out.println(" Number of files: " + nf);
}
if(cl) {
System.out.println(" Number of lines: " + nl);
}
}
/**
* Specify label to use.
* @param label label
*/
public void setLabel(String label) {
this.label = label;
}
/**
* Specify whether to count files.
* @param cf true=count false=not count
*/
public void setCountfiles(boolean cf) {
this.cf = cf;
}
/**
* Specify whether to count lines.
* @param cl true=count false=not count
*/
public void setCountlines(boolean cl) {
this.cl = cl;
}
/**
* Specify a file set to process.
* @param fs file set
*/
public void addFileSet(FileSet fs) {
allfs.add(fs);
}
}
example:
<target name="count">
<taskdef name="javacodestats" classpath="${anttaskslib}"
classname="dk.vajhoej.anttasks.codestats.JavaCodeStatsTask"/>
<javacodestats label="Library" countfiles="yes" countlines="yes">
<fileset dir="src" includes="dk/vajhoej/record/*.java"/>
</javacodestats>
<javacodestats label="Unit test" countfiles="yes" countlines="yes">
<fileset dir="src" includes="dk/vajhoej/record/test/*.java"/>
</javacodestats>
</target>