Files
cappuccino/CommonJS/bin/flatten
T

272 lines
9.4 KiB
Plaintext
Executable File

#!/usr/bin/env objj
require("narwhal").ensureEngine("rhino");
@import <Foundation/Foundation.j>
@import "../lib/cappuccino/objj-analysis-tools.j"
var FILE = require("file");
var OS = require("os");
var UTIL = require("util");
var stream = require("term").stream;
var parser = new (require("args").Parser)();
parser.usage("INPUT_PROJECT OUTPUT_PROJECT");
parser.help("Combine a Cappuccino application into a single JavaScript file.");
parser.option("-m", "--main", "main")
.def("main.j")
.set()
.help("The relative path (from INPUT_PROJECT) to the main file (default: 'main.j')");
parser.option("-F", "--framework", "frameworks")
.push()
.help("Add a frameworks directory, relative to INPUT_PROJECT (default: ['Frameworks'])");
parser.option("-P", "--path", "paths")
.push()
.help("Add a path (relative to the application root) to inline.");
parser.option("-f", "--force", "force")
.def(false)
.set(true)
.help("Force overwriting OUTPUT_PROJECT if it exists");
parser.option("--index", "index")
.def("index.html")
.set()
.help("The root HTML file to modify (default: index.html)");
parser.option("-v", "--verbose", "verbose")
.def(false)
.set(true)
.help("Verbose logging");
parser.helpful();
function main(args)
{
var options = parser.parse(args);
if (options.args.length < 2) {
parser.printUsage(options);
return;
}
var rootPath = FILE.path(options.args[0]).join("").absolute();
var outputPath = FILE.path(options.args[1]).join("").absolute();
if (outputPath.exists()) {
if (options.force) {
// FIXME: why doesn't this work?!
//outputPath.rmtree();
OS.system(["rm", "-rf", outputPath]);
} else {
stream.print("\0red(OUTPUT_PROJECT " + outputPath + " exists. Use -f to overwrite.\0)");
OS.exit(1);
}
}
options.frameworks.push("Frameworks");
var mainPath = String(rootPath.join(options.main));
var frameworks = options.frameworks.map(function(framework) { return rootPath.join(framework); });
var environment = "Browser";
stream.print("\0yellow("+Array(81).join("=")+"\0)");
stream.print("Application root: \0green(" + rootPath + "\0)");
stream.print("Output directory: \0green(" + outputPath + "\0)");
stream.print("\0yellow("+Array(81).join("=")+"\0)");
stream.print("Main file: \0green(" + mainPath + "\0)");
stream.print("Frameworks: \0green(" + frameworks + "\0)");
stream.print("Environment: \0green(" + environment + "\0)");
var flattener = new ObjectiveJFlattener(rootPath);
flattener.options = options;
flattener.setIncludePaths(frameworks);
flattener.setEnvironments([environment, "ObjJ"]);
print("Loading application.");
flattener.load(mainPath);
print("Loading default theme.");
flattener.require("objective-j").objj_eval("("+(function() {
var blend = [[CPThemeBlend alloc] initWithContentsOfURL:[[CPBundle bundleForClass:[CPApplication class]] pathForResource:[CPApplication defaultThemeName] + ".blend"]];
[blend loadWithDelegate:nil];
})+")")();
var applicationJS = flattener.buildApplicationJS();
FILE.copyTree(rootPath, outputPath);
outputPath.join("Application.js").write(applicationJS);
rewriteMainHTML(outputPath.join(options.index));
}
// ObjectiveJFlattener inherits from ObjectiveJRuntimeAnalyzer
function ObjectiveJFlattener(rootPath) {
ObjectiveJRuntimeAnalyzer.apply(this, arguments);
this.filesToCache = {};
this.fileCacheBuffer = [];
this.functionsBuffer = [];
}
ObjectiveJFlattener.prototype = Object.create(ObjectiveJRuntimeAnalyzer.prototype);
ObjectiveJFlattener.prototype.buildApplicationJS = function() {
this.setupFileCache();
this.serializeFunctions();
this.serializeFileCache();
var buffer = [];
buffer.push("var baseURL = new CFURL(\".\", ObjectiveJ.pageURL);");
buffer.push(this.fileCacheBuffer.join("\n"))
buffer.push(this.functionsBuffer.join("\n"));
buffer.push("ObjectiveJ.bootstrap();");
return buffer.join("\n");
}
ObjectiveJFlattener.prototype.serializeFunctions = function() {
var inlineFunctions = true;//this.options.inlineFunctions;
var outputFiles = {};
var _cachedExecutableFunctions = {};
this.require("objective-j").FileExecutable.allFileExecutables().forEach(function(executable) {
var path = executable.path();
if (inlineFunctions)
{
// stringify the function, replacing arguments
var functionString = executable._function.toString().replace(", require, exports, module, system, print, window", ""); // HACK
var relative = this.rootPath.relative(path).toString();
this.functionsBuffer.push("ObjectiveJ.FileExecutable._cacheFunction(new CFURL("+JSON.stringify(relative)+", baseURL),\n"+functionString+");");
}
var bundle = this.context.global.CFBundle.bundleContainingURL(path);
if (bundle && bundle.infoDictionary())
{
var executablePath = bundle.executablePath(),
relativeToBundle = FILE.relative(FILE.join(bundle.path(), ""), path);
if (executablePath)
{
if (inlineFunctions)
{
// remove the code since we're inlining the functions
executable._code = "alert("+JSON.stringify(relativeToBundle)+");";
}
if (!outputFiles[executablePath])
{
outputFiles[executablePath] = [];
outputFiles[executablePath].push("@STATIC;1.0;");
}
var fileContents = executable.toMarkedString();
outputFiles[executablePath].push("p;" + relativeToBundle.length + ";" + relativeToBundle);
outputFiles[executablePath].push("t;" + fileContents.length + ";" + fileContents);
// stream.print("Adding \0green(" + this.rootPath.relative(path) + "\0) to \0cyan(" + this.rootPath.relative(executablePath) + "\0)");
}
}
else
CPLog.warn("No bundle (or info dictionary for) " + rootPath.relative(path));
}, this);
for (var executablePath in outputFiles)
{
var relative = this.rootPath.relative(executablePath).toString();
var contents = outputFiles[executablePath].join("");
this.filesToCache[relative] = contents;
}
}
ObjectiveJFlattener.prototype.serializeFileCache = function() {
for (var relative in this.filesToCache) {
var contents = this.filesToCache[relative];
print("caching: " + relative + " => " + (contents == null ? 404 : 200));
if (contents == null)
this.fileCacheBuffer.push("CFHTTPRequest._cacheRequest(new CFURL("+JSON.stringify(relative)+", baseURL), 404);");
else
this.fileCacheBuffer.push("CFHTTPRequest._cacheRequest(new CFURL("+JSON.stringify(relative)+", baseURL), 200, {}, "+JSON.stringify(contents)+");");
}
}
ObjectiveJFlattener.prototype.setupFileCache = function() {
var paths = {};
UTIL.update(paths, this.requestedURLs);
this.options.paths.forEach(function(relativePath) {
paths[this.rootPath.join(relativePath)] = true;
}, this);
Object.keys(paths).forEach(function(absolute) {
var relative = this.rootPath.relative(absolute).toString();
if (relative.indexOf("..") === 0)
{
print("skipping (parent of app root): " + absolute);
return;
}
if (FILE.isFile(absolute))
{
// if (this.options.maxCachedSize && FILE.size(absolute) > this.options.maxCachedSize)
// {
// print("skipping (larger than "+this.options.maxCachedSize+" bytes): " + absolute);
// return;
// }
var contents = FILE.read(absolute, { charset : "UTF-8" });
this.filesToCache[relative] = contents;
} else {
this.filesToCache[relative] = null;
}
}, this);
}
// "$1" is the matching indentation
var scriptTagsBefore = '$1<script type = "text/javascript">\n$1 OBJJ_AUTO_BOOTSTRAP = false;\n$1</script>';
var scriptTagsAfter = '$1<script type = "text/javascript" src = "Application.js"></script>';
// enable CPLog:
// scriptTagsAfter = '$1<script type = "text/javascript">\n$1 CPLogRegister(CPLogConsole);\n$1</script>\n' + scriptTagsAfter;
function rewriteMainHTML(indexHTMLPath) {
if (indexHTMLPath.isFile()) {
var indexHTML = indexHTMLPath.read();
// attempt to find Objective-J script tag and add ours
var newIndexHTML = indexHTML.replace(/([ \t]+)<script[^>]+Objective-J\.js[^>]+>(?:\s*<\/script>)?/,
scriptTagsBefore+'\n$&\n'+scriptTagsAfter);
if (newIndexHTML !== indexHTML) {
stream.print("\0green(Modified: "+indexHTMLPath+".\0)");
indexHTMLPath.write(newIndexHTML);
return;
}
} else {
stream.print("\0yellow(Warning: "+indexHTMLPath+" does not exist. Specify an alternate index HTML file with the --index option.\0)");
}
stream.print("\0yellow(Warning: Unable to automatically modify "+indexHTMLPath + ".\0)");
stream.print("\nAdd the following before the Objective-J script tag:");
stream.print(scriptTagsBefore.replace(/\$1/g, " "));
stream.print("\nAdd the following after the Objective-J script tag:");
stream.print(scriptTagsAfter.replace(/\$1/g, " "));
}