YUI CompressorをANTから利用できるようにする。

はじめに

先日YUIJavaScript圧縮ツールが公開されたのを見て、色々と遊んでいたわけですが検証とか遊びならいいですが…毎回毎回Javaコマンド叩いて圧縮するのもめんどくさいなと思っていました。1つや2つならANTを利用してJavaタスクを書いて自動化しますが…jsの数が70近くあるようなライブラリではそれも面倒なので専用のタスクを書いてみた次第です。

使い方

タスク定義
[project]
    +--- builx.xml
    +--- [build]
            +--- YUICTask.class
            +--- yuicompressor-1.0.jar
<taskdef name="yuic" classname="YUICTask"
         classpath="build;build/yuicompressor-1.0.jar" />

上記のディレクトリ構成のときのclasspath設定です。クラスが見つからないとかAntに怒られる時はclasspathの設定がいじってあげる。

呼出し
<yuic todir="dist/js">
    <fileset dir="dev/js" />
</yuic>

Antのcopyタスクを拡張しているので基本はcopyタスクと同じ。万が一.js以外のものが入っている場合はYUICompressorからエラーでて止まるので<fileset>とかファイル選択系でJSのみ選んであげたほうが無難。

ソース

import java.io.*;
import java.util.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.util.*;
import org.apache.tools.ant.types.*;
import org.apache.tools.ant.taskdefs.*;

public class YUICTask extends Copy
{
    public YUICTask(){
        super();
    }

    protected void doFileOperations()
    {
        super.doFileOperations();

        if (fileCopyMap.size() > 0) {
            Enumeration e = fileCopyMap.keys();
            while (e.hasMoreElements()) {
                    String fromFile = (String) e.nextElement();
                    String[] toFiles = (String[]) fileCopyMap.get(fromFile);
 
                    for (int i = 0; i < toFiles.length; i++) {
                        String toFile = toFiles[i];

                        if (fromFile.equals(toFile)) {
                            log("Skipping self-copy of " + fromFile, verbosity);
                            continue;
                        }

                        doCompressor(fromFile, toFile);
                    }
                }
            }
    }

    protected void doCompressor(String fromFile, String toFile)
    {
        String[] args = new String[3];

        args[0] = "-o";
        args[1] = toFile;
        args[2] = fromFile;

        YUICompressor.main(args);
    }
}

突貫工事なのでバグ多し...。