// Copyright (C) 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.caja.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.google.caja.SomethingWidgyHappenedError;
import com.google.caja.lexer.escaping.Escaping;
import com.google.caja.util.Charsets;
/**
* Takes as input a JS file and outputs a JS file that has a variable
* initialized to its contents.
*
* @author Jasvir Nagra <jasvir@gmail.com>
*/
public final class JsToVar implements BuildCommand {
public boolean build(
List<File> inputs, List<File> dependencies, Map<String, Object> options,
File output) throws IOException {
Writer out = new OutputStreamWriter(
new FileOutputStream(output), Charsets.UTF_8.name());
try {
String currentDate = "" + new Date();
if (currentDate.indexOf("*/") >= 0) {
throw new SomethingWidgyHappenedError("Date should not contain '*/'");
}
out.write("/* Copyright Google Inc.\n");
out.write(" * Licensed under the Apache Licence Version 2.0\n");
out.write(" * Autogenerated at " + currentDate + "\n");
out.write(" */\n");
out.write("var ");
Escaping.escapeJsIdentifier(varName(output), true /*asciiOnly*/, out);
out.write(" = ");
out.write('"');
Escaping.escapeJsString(concatFiles(inputs), true /*asciiOnly*/,
true /* embeddable */, out);
out.write('"');
out.write(';');
} finally {
out.close();
}
return true;
}
private String varName(File output) {
String name = output.getName();
return name.endsWith(".js") ? name.substring(0, name.length() - 3) : name;
}
private String concatFiles(Iterable<? extends File> inputs)
throws IOException {
StringBuilder result = new StringBuilder();
for (File input : inputs) {
BufferedReader reader = new BufferedReader(new FileReader(input));
try {
String line = null;
while (null != (line = reader.readLine())) {
result.append(line + "\n");
}
} finally {
reader.close();
}
}
return result.toString();
}
}