FileDocCategorySizeDatePackage
FixCRLF.javaAPI DocApache Ant 1.7021336Wed Dec 13 06:16:20 GMT 2006org.apache.tools.ant.taskdefs

FixCRLF

public class FixCRLF extends MatchingTask implements org.apache.tools.ant.filters.ChainableReader
Converts text source files to local OS formatting conventions, as well as repair text files damaged by misconfigured or misguided editors or file transfer programs.

This task can take the following arguments:

  • srcdir
  • destdir
  • include
  • exclude
  • cr
  • eol
  • tab
  • eof
  • encoding
  • targetencoding
Of these arguments, only sourcedir is required.

When this task executes, it will scan the srcdir based on the include and exclude properties.

This version generalises the handling of EOL characters, and allows for CR-only line endings (the standard on Mac systems prior to OS X). Tab handling has also been generalised to accommodate any tabwidth from 2 to 80, inclusive. Importantly, it will leave untouched any literal TAB characters embedded within string or character constants.

Warning: do not run on binary files. Caution: run with care on carefully formatted files. This may sound obvious, but if you don't specify asis, presume that your files are going to be modified. If "tabs" is "add" or "remove", whitespace characters may be added or removed as necessary. Similarly, for CR's - in fact "eol"="crlf" or cr="add" can result in cr characters being removed in one special case accommodated, i.e., CRCRLF is regarded as a single EOL to handle cases where other programs have converted CRLF into CRCRLF.

since
Ant 1.1
ant.task
category="filesystem"

Fields Summary
public static final String
ERROR_FILE_AND_SRCDIR
error string for using srcdir and file
private static final org.apache.tools.ant.util.FileUtils
FILE_UTILS
private boolean
preserveLastModified
private File
srcDir
private File
destDir
private File
file
private org.apache.tools.ant.filters.FixCrLfFilter
filter
private Vector
fcv
private String
encoding
Encoding to assume for the files
private String
outputEncoding
Encoding to use for output files
Constructors Summary
Methods Summary
public final java.io.Readerchain(java.io.Reader rdr)
Chain this task as a reader.

param
rdr Reader to chain.
return
a Reader.
since
Ant 1.7?


                          
          
        return filter.chain(rdr);
    
public voidexecute()
Executes the task.

throws
BuildException on error.

        // first off, make sure that we've got a srcdir and destdir
        validate();

        // log options used
        String enc = encoding == null ? "default" : encoding;
        log("options:"
            + " eol=" + filter.getEol().getValue()
            + " tab=" + filter.getTab().getValue()
            + " eof=" + filter.getEof().getValue()
            + " tablength=" + filter.getTablength()
            + " encoding=" + enc
            + " outputencoding="
            + (outputEncoding == null ? enc : outputEncoding),
            Project.MSG_VERBOSE);

        DirectoryScanner ds = super.getDirectoryScanner(srcDir);
        String[] files = ds.getIncludedFiles();

        for (int i = 0; i < files.length; i++) {
            processFile(files[i]);
        }
    
private voidprocessFile(java.lang.String file)

        File srcFile = new File(srcDir, file);
        long lastModified = srcFile.lastModified();
        File destD = destDir == null ? srcDir : destDir;

        if (fcv == null) {
            FilterChain fc = new FilterChain();
            fc.add(filter);
            fcv = new Vector(1);
            fcv.add(fc);
        }
        File tmpFile = FILE_UTILS.createTempFile("fixcrlf", "", null);
        tmpFile.deleteOnExit();
        try {
            FILE_UTILS.copyFile(srcFile, tmpFile, null, fcv, false, false,
                encoding, outputEncoding == null ? encoding : outputEncoding,
                getProject());

            File destFile = new File(destD, file);

            boolean destIsWrong = true;
            if (destFile.exists()) {
                // Compare the destination with the temp file
                log("destFile exists", Project.MSG_DEBUG);
                destIsWrong = !FILE_UTILS.contentEquals(destFile, tmpFile);
                log(destFile + (destIsWrong ? " is being written"
                    : " is not written, as the contents are identical"),
                    Project.MSG_DEBUG);
            }
            if (destIsWrong) {
                FILE_UTILS.rename(tmpFile, destFile);
                if (preserveLastModified) {
                    log("preserved lastModified", Project.MSG_DEBUG);
                    FILE_UTILS.setFileLastModified(destFile, lastModified);
                }
                tmpFile = null;
            }
        } catch (IOException e) {
            throw new BuildException(e);
        }
    
public voidsetCr(org.apache.tools.ant.taskdefs.FixCRLF$AddAsisRemove attr)
Specify how carriage return (CR) characters are to be handled.

param
attr valid values:
  • add: ensure that there is a CR before every LF
  • asis: leave CR characters alone
  • remove: remove all CR characters
deprecated
since 1.4.x. Use {@link #setEol setEol} instead.

        log("DEPRECATED: The cr attribute has been deprecated,",
            Project.MSG_WARN);
        log("Please use the eol attribute instead", Project.MSG_WARN);
        String option = attr.getValue();
        CrLf c = new CrLf();
        if (option.equals("remove")) {
            c.setValue("lf");
        } else if (option.equals("asis")) {
            c.setValue("asis");
        } else {
            // must be "add"
            c.setValue("crlf");
        }
        setEol(c);
    
public voidsetDestdir(java.io.File destDir)
Set the destination where the fixed files should be placed. Default is to replace the original file.

param
destDir the destination directory.

        this.destDir = destDir;
    
public voidsetEncoding(java.lang.String encoding)
Specifies the encoding Ant expects the files to be in--defaults to the platforms default encoding.

param
encoding String encoding name.

        this.encoding = encoding;
    
public voidsetEof(org.apache.tools.ant.taskdefs.FixCRLF$AddAsisRemove attr)
Specify how DOS EOF (control-z) characters are to be handled.

param
attr valid values:
  • add: ensure that there is an eof at the end of the file
  • asis: leave eof characters alone
  • remove: remove any eof character found at the end

        filter.setEof(FixCrLfFilter.AddAsisRemove.newInstance(attr.getValue()));
    
public voidsetEol(org.apache.tools.ant.taskdefs.FixCRLF$CrLf attr)
Specify how EndOfLine characters are to be handled.

param
attr valid values:
  • asis: leave line endings alone
  • cr: convert line endings to CR
  • lf: convert line endings to LF
  • crlf: convert line endings to CRLF

        filter.setEol(FixCrLfFilter.CrLf.newInstance(attr.getValue()));
    
public voidsetFile(java.io.File file)
Set a single file to convert.

since
Ant 1.6.3
param
file the file to convert.

        this.file = file;
    
public voidsetFixlast(boolean fixlast)
Specify whether a missing EOL will be added to the final line of a file.

param
fixlast whether to fix the last line.

        filter.setFixlast(fixlast);
    
public voidsetJavafiles(boolean javafiles)
Set to true if modifying Java source files.

param
javafiles whether modifying Java files.

        filter.setJavafiles(javafiles);
    
public voidsetOutputEncoding(java.lang.String outputEncoding)
Specifies the encoding that the files are to be written in--same as input encoding by default.

param
outputEncoding String outputEncoding name.

        this.outputEncoding = outputEncoding;
    
public voidsetPreserveLastModified(boolean preserve)
Set whether to preserve the last modified time as the original files.

param
preserve true if timestamps should be preserved.
since
Ant 1.6.3

        preserveLastModified = preserve;
    
public voidsetSrcdir(java.io.File srcDir)
Set the source dir to find the source text files.

param
srcDir the source directory.

        this.srcDir = srcDir;
    
public voidsetTab(org.apache.tools.ant.taskdefs.FixCRLF$AddAsisRemove attr)
Specify how tab characters are to be handled.

param
attr valid values:
  • add: convert sequences of spaces which span a tab stop to tabs
  • asis: leave tab and space characters alone
  • remove: convert tabs to spaces

        filter.setTab(FixCrLfFilter.AddAsisRemove.newInstance(attr.getValue()));
    
public voidsetTablength(int tlength)
Specify tab length in characters.

param
tlength specify the length of tab in spaces.
throws
BuildException on error.

        try {
            filter.setTablength(tlength);
        } catch (IOException e) {
            throw new BuildException(e);
        }
    
private voidvalidate()

        if (file != null) {
            if (srcDir != null) {
                throw new BuildException(ERROR_FILE_AND_SRCDIR);
            }
            //patch file into the fileset
            fileset.setFile(file);
            //set our parent dir
            srcDir = file.getParentFile();
        }
        if (srcDir == null) {
            throw new BuildException("srcdir attribute must be set!");
        }
        if (!srcDir.exists()) {
            throw new BuildException("srcdir does not exist!");
        }
        if (!srcDir.isDirectory()) {
            throw new BuildException("srcdir is not a directory!");
        }
        if (destDir != null) {
            if (!destDir.exists()) {
                throw new BuildException("destdir does not exist!");
            }
            if (!destDir.isDirectory()) {
                throw new BuildException("destdir is not a directory!");
            }
        }