一个搜集java源代码的scala程序

jboss的源代码目录太零碎了,写了一个Scala脚本,搜索多个源目录,把java文件按包名路径复制到统一目录下。方便调试时绑定源码。

package net.danieldeng.sourceextractor
import scala.io.Source
import java.io._;
import org.apache.commons.io.FileUtils

object SourceExtractor {
  val PackagePattern = """^\s*package\s+(.+?)\s*;\s*$""".r;
  
  def help = {
    print(
        """
SourceExtractor <option> source_directory_1 source_directory_2 ... 

Options:
  -d <destination> : Specify destination directory
  -c <codec charset> : Charset used by source files. Default UTF-8.
  -h : Show this help information."""
    );
  }

  def parseArg(args: Array[String]): Config = {
    val config = new Config(List(), null, "UTF-8");
    def parse(argList: List[String]): Unit = {
      argList match {
        case "-d" :: dest :: xs => config.destDir = dest; parse(xs);
        case "-c" :: charset :: xs => config.codec = charset; parse(xs);
        case "-h" :: xs => help;exit;
        case source :: xs => config.srcDir = (source :: config.srcDir).reverse; parse(xs);
        case List() => ;
      }
    }
    parse(List(args: _*));
    return config;
  }

  private def copy(f: File, packageName: String, dest: String) {
    val path = dest + File.separator + packageName.replaceAllLiterally(""".""", File.separator);
    val dir = prepareDir(path);
    FileUtils.copyFileToDirectory(f, dir);
  }

  private def prepareDir(path: String): File =
    new File(path) match {
      case dest if !(dest exists) => if (dest.mkdirs) dest else throw new IOException("Cannot create directory " + path);
      case dest if !(dest isDirectory) => throw new IllegalArgumentException(path + " is not a directory");
      case dest => dest;
    };

  def main(args: Array[String]): Unit = {
    val config = parseArg(args);
    val dest = prepareDir(config.destDir);
    config.srcDir.foreach(
      src => {
        val it = FileUtils.iterateFiles(new File(src), Array("java"), true);
        while (it.hasNext) {
          val f = it.next;
          val source = Source.fromFile(f, config.codec);
          try {
            source.getLines().find(_ match {
              case PackagePattern(packageName) =>
                {
                  copy(f, packageName, dest.getAbsolutePath);
                  true
                };
              case _ => false;
            });
          } finally {
            source.close();
          }
        }
      });
  }
}

class Config(
  var srcDir: List[String],
  var destDir: String,
  var codec: String);


你可能感兴趣的:(scala)