Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Using the precompiler npm module

  • Loading branch information...
commit 6031966a2aed093436b4ec660e84de2a6e8f1cdb 1 parent 64ecd8e
@petebacondarwin petebacondarwin authored
View
2  .gitignore
@@ -0,0 +1,2 @@
+packages
+.kansorc
View
5 Cakefile
@@ -0,0 +1,5 @@
+{exec} = require 'child_process'
+task 'build', 'Build project from src/*.coffee to lib/*.js', ->
+ exec 'coffee --compile --output build/ src/', (err, stdout, stderr) ->
+ throw err if err
+ console.log stdout + stderr
View
3  README.md
@@ -19,7 +19,8 @@ Add a `coffee-script` field to `kanso.json` with one or both of the following: a
},
```
-Run `kanso fetch` from your terminal to install dependencies. When you `kanso push`:
+Run `kanso intall` from your terminal to install dependencies.
+When you `kanso push`:
1. All coffeescript modules listed in `coffee-script.modules` will be compiled to javascript and uploaded as usual.
2. All coffeescript files in `attachements` directories will be uploaded as attachments at the corrosponding path with a `.js` extension. So `/lib/js/main.coffee` will be uploaded to `/lib/js/main.js`.
View
134 build/compile.js
@@ -1,85 +1,49 @@
-var async, attachments, coffee, compile_attachment, compile_attachments, compile_coffee, compile_module, compile_modules, modules, path, spawn, utils;
-async = require("async");
-utils = require("kanso-utils/utils");
-spawn = require("child_process").spawn;
-path = require("path");
-modules = require("kanso-utils/modules");
-attachments = require("kanso-utils/attachments");
-coffee = require("coffee-script/lib/coffee-script/coffee-script");
-module.exports = {
- before: "properties",
- run: function(root, path, settings, doc, callback) {
- var apply_compile_attachments, apply_compile_modules, attach_paths, module_paths;
- if (!settings["coffee-script"]) {
- return callback(null, doc);
- }
- if (!settings["coffee-script"]["modules"] && !settings["coffee-script"]["attachments"]) {
- return callback(null, doc);
- }
- module_paths = settings["coffee-script"]["modules"] || [];
- if (!Array.isArray(module_paths)) {
- module_paths = [module_paths];
- }
- attach_paths = settings["coffee-script"]["attachments"] || [];
- if (!Array.isArray(attach_paths)) {
- attach_paths = [attach_paths];
- }
- apply_compile_modules = async.apply(compile_modules, doc, path);
- apply_compile_attachments = async.apply(compile_attachments, doc, path);
- return async.parallel([async.apply(async.forEach, module_paths, apply_compile_modules), async.apply(async.forEach, attach_paths, apply_compile_attachments)], function(err) {
- return callback(err, doc);
- });
- }
-};
-compile_modules = function(doc, path, paths, callback) {
- var pattern;
- pattern = /.*\.coffee$/i;
- return utils.find(utils.abspath(paths, path), pattern, function(err, data) {
- var apply_compile_module;
- if (err) {
- return callback(err);
- }
- apply_compile_module = async.apply(compile_module, doc, path);
- return async.forEach(data, apply_compile_module, callback);
- });
-};
-compile_module = function(doc, path, filename, callback) {
- var name;
- name = utils.relpath(filename, path).replace(/\.coffee$/, "");
- return compile_coffee(path, filename, function(err, js) {
- if (err) {
- return callback(err);
- }
- modules.add(doc, name, js.toString());
- return callback();
- });
-};
-compile_attachments = function(doc, path, paths, callback) {
- var pattern;
- pattern = /.*\.coffee$/i;
- return utils.find(utils.abspath(paths, path), pattern, function(err, data) {
- var apply_compile_attachment;
- if (err) {
- return callback(err);
- }
- apply_compile_attachment = async.apply(compile_attachment, doc, path);
- return async.forEach(data, apply_compile_attachment, callback);
- });
-};
-compile_attachment = function(doc, path, filename, callback) {
- var name;
- name = utils.relpath(filename, path).replace(/\.coffee$/, ".js");
- return compile_coffee(path, filename, function(err, js) {
- if (err) {
- return callback(err);
- }
- attachments.add(doc, name, name, new Buffer(js).toString("base64"));
- return callback();
- });
-};
-compile_coffee = function(project_path, filename, callback) {
- var c;
- console.log("Compiling " + utils.relpath(filename, project_path));
- c = coffee.compile(fs.readFileSync(filename, 'utf8'));
- return callback(null, c);
-};
+(function() {
+
+ module.exports = {
+ before: "modules",
+ run: function(root, path, settings, doc, callback) {
+ var async, attachments, attachmentsPaths, coffee, compileAttachment, compileModule, extension_pattern, file_pattern, modules, modulesPaths, precompiler, processAttachments, processModules, utils, _ref, _ref2;
+ modulesPaths = (_ref = settings["coffee-script"]) != null ? _ref["modules"] : void 0;
+ attachmentsPaths = (_ref2 = settings["coffee-script"]) != null ? _ref2["attachments"] : void 0;
+ if (!((modulesPaths != null) || (attachmentsPaths != null))) {
+ console.log("Coffee script precompiler must have either a modules or an attachment setting");
+ return callback(null, doc);
+ }
+ if (modulesPaths == null) modulesPaths = [];
+ if (attachmentsPaths == null) attachmentsPaths = [];
+ async = require("async");
+ utils = require("kanso-utils/utils");
+ precompiler = require("kanso-precompiler-base");
+ coffee = require("coffee-script");
+ file_pattern = /.*\.coffee$/i;
+ extension_pattern = /\.coffee$/;
+ compileAttachment = function(filename, callback) {
+ var js, name;
+ console.log("Compiling attachment");
+ js = coffee.compile(fs.readFileSync(filename, 'utf8'));
+ name = utils.relpath(filename, path).replace(extension_pattern, ".js");
+ precompiler.addAttachment(doc, name, filename, js);
+ return callback(null, doc);
+ };
+ compileModule = function(filename, callback) {
+ var js, name;
+ console.log("Compiling module");
+ js = coffee.compile(fs.readFileSync(filename, 'utf8'));
+ name = utils.relpath(filename, path).replace(extension_pattern, "");
+ precompiler.addModule(doc, name, filename, js);
+ return callback(null, doc);
+ };
+ console.log("Running coffee-script pre-compiler");
+ console.dir();
+ modules = precompiler.normalizePaths(settings["coffee-script"]["modules"], path);
+ attachments = precompiler.normalizePaths(attachmentsPaths, path);
+ processModules = async.apply(precompiler.processPaths, modules, file_pattern, compileModule);
+ processAttachments = async.apply(precompiler.processPaths, attachments, file_pattern, compileAttachment);
+ return async.parallel([processModules, processAttachments], function(err, results) {
+ return callback(err, doc);
+ });
+ }
+ };
+
+}).call(this);
View
22 build/remove.js
@@ -1,12 +1,14 @@
-module.exports = {
- after: "attachments",
- run: function(root, path, settings, doc, callback) {
- var k;
- for (k in doc._attachments || {}) {
- if (/\.coffee$/.test(k)) {
- delete doc._attachments[k];
+(function() {
+
+ module.exports = {
+ after: "attachments",
+ run: function(root, path, settings, doc, callback) {
+ var k;
+ for (k in doc._attachments || {}) {
+ if (/\.coffee$/.test(k)) delete doc._attachments[k];
}
+ return callback(null, doc);
}
- return callback(null, doc);
- }
-};
+ };
+
+}).call(this);
View
6 kanso.json
@@ -1,10 +1,12 @@
{
"name": "coffee-script-precompiler",
- "version": "0.0.9",
+ "version": "0.0.10",
"categories": ["build-tools"],
"description": "Compiles CoffeeScript modules and attachments to javascript on each push",
+ "url": "https://github.com/nrw/coffee-script-precompiler/",
"preprocessors": {
"compile": "build/compile",
"remove": "build/remove"
- }
+ },
+ "dependencies": {}
}
View
1  node_modules/kanso-precompiler-base/.npmignore
@@ -0,0 +1 @@
+node_modules
View
5 node_modules/kanso-precompiler-base/Cakefile
@@ -0,0 +1,5 @@
+{exec} = require 'child_process'
+task 'build', 'Build project', ->
+ exec 'coffee --compile lib/', (err, stdout, stderr) ->
+ throw err if err
+ console.log stdout + stderr
View
64 node_modules/kanso-precompiler-base/README.md
@@ -0,0 +1,64 @@
+This is a small CommonJS module that can be used by packages that precompile files and add them to design documents, such as compiling javascript code, html templates or css stylesheets.
+
+## Usage
+Install the npm package in your own precompiler package:
+
+ npm install kanso-precompiler-base
+
+In your precompiler package code (usually in `build/compile`) require the precompiler to get access to its methods:
+
+ precompiler = require("kanso-precompiler-base")
+
+## Example
+This example is taken from the Eco template precompiler. It uses a method called compileTemplate to actually compile the Eco templates into JavaScript.
+
+ module.exports =
+ before: "modules"
+ run: (root, path, settings, doc, callback) ->
+ console.log "Running eco pre-compiler"
+ return callback(null, doc) unless settings["eco"]?["templates"]?
+
+ # Extract the template paths from the settings
+ templatePaths = precompiler.normalizePaths(settings["eco"]["templates"], path)
+
+ # Create a continuation that processes a template using the given doc and path
+ processTemplate = async.apply(compileTemplate, doc, path)
+
+ # Run processTemplate, asynchronously, on each of the files that match the given pattern, in the given paths
+ precompiler.processPaths(templatePaths, /.*\.j?eco$/i, processTemplate, callback)
+
+Notice also that we pass the callback function that was passed to us into the processPaths function. This is so that Kanso knows when the precompilation is complete but also, more importantly, gives Kanso the doc object to which we have added.
+
+## Reference
+
+### normalizePaths: (paths, cwd)
+Use this method to get a nice array of absolute paths from an entry in the settings object.
+
+- `paths`: either a string or an array containing one or more relative paths to the files to be precompiled.
+- `cwd`: a string containing the current working directory to which the given paths are relative.
+
+
+### processPaths: (paths, pattern, processItem, callback)
+Use this function to process each of the files in each of the paths that match the given pattern
+
+- `paths`: A normalized array of paths to search for items to process
+- `pattern`: A regular expression that matches the files to be processed
+- `processItem`: The function to be executed to actually do the precompilation
+- `callback`: The function to be called once all the items have breen precompiled - of the form: callback(err, doc)
+
+### addModule: (doc, name, originalPath, content)
+Use this function to add a CommonJS module to the design document, which can be required in JS code on the server or can be stitched up by the modules package into the modules.js file for use in the browser.
+
+- `doc`: The design document where the module will be added
+- `name`: The name of the module (without extension)
+- `originalPath`: The original full filename of the module before precompilation
+- `content`: The content of the precompiled module
+
+### addAttachment: (doc, name, originalPath, content)
+Use this function to add an item to the design document as an attachment, which can be downloaded for use in the browser.
+
+- `doc`: The design document where the attachment will be added
+- `name`: The name of the attachment
+- `originalPath`: The original full filename of the attachment before precompilation
+- `content`: The content of the precompiled attachment
+
View
1  node_modules/kanso-precompiler-base/index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/precompiler')
View
31 node_modules/kanso-precompiler-base/lib/precompiler.coffee
@@ -0,0 +1,31 @@
+async = require("async")
+utils = require("kanso-utils/utils")
+modules = require("kanso-utils/modules")
+attachments = require("kanso-utils/attachments")
+
+doProcessPaths = (pattern, processItem, path, callback) ->
+ # Find all the files that match the pattern within the given path
+ utils.find path, pattern, (err, files) ->
+ return callback(err) if err
+ # Process the files asynchronously
+ async.forEach files, processItem, (err, doc)->
+ callback(err, doc)
+
+module.exports =
+ # Ensure that we have an array of absolute paths
+ normalizePaths: (paths, cwd)->
+ paths = [ paths ] unless Array.isArray(paths) # Ensure paths is an array
+ for folder in paths # Convert paths to absolute path
+ utils.abspath(folder, cwd)
+
+ processPaths: (paths, pattern, processItem, callback)->
+ async.forEach(paths, async.apply(doProcessPaths, pattern, processItem), (err,doc)->callback(err, doc))
+
+ addModule: (doc, name, originalPath, content)->
+ modules.add(doc, name, content)
+ # These next two lines are a hack to make sure that the kanso-utils/utils.require works for modules added by this method
+ doc._module_paths ?= {}
+ utils.setPropertyPath(doc._module_paths, name, originalPath);
+
+ addAttachment: (doc, name, originalPath, content)->
+ attachments.add(doc, name, originalPath, content)
View
47 node_modules/kanso-precompiler-base/lib/precompiler.js
@@ -0,0 +1,47 @@
+(function() {
+ var async, attachments, doProcessPaths, modules, utils;
+
+ async = require("async");
+
+ utils = require("kanso-utils/utils");
+
+ modules = require("kanso-utils/modules");
+
+ attachments = require("kanso-utils/attachments");
+
+ doProcessPaths = function(pattern, processItem, path, callback) {
+ return utils.find(path, pattern, function(err, files) {
+ if (err) return callback(err);
+ return async.forEach(files, processItem, function(err, doc) {
+ return callback(err, doc);
+ });
+ });
+ };
+
+ module.exports = {
+ normalizePaths: function(paths, cwd) {
+ var folder, _i, _len, _results;
+ if (!Array.isArray(paths)) paths = [paths];
+ _results = [];
+ for (_i = 0, _len = paths.length; _i < _len; _i++) {
+ folder = paths[_i];
+ _results.push(utils.abspath(folder, cwd));
+ }
+ return _results;
+ },
+ processPaths: function(paths, pattern, processItem, callback) {
+ return async.forEach(paths, async.apply(doProcessPaths, pattern, processItem), function(err, doc) {
+ return callback(err, doc);
+ });
+ },
+ addModule: function(doc, name, originalPath, content) {
+ modules.add(doc, name, content);
+ if (doc._module_paths == null) doc._module_paths = {};
+ return utils.setPropertyPath(doc._module_paths, name, originalPath);
+ },
+ addAttachment: function(doc, name, originalPath, content) {
+ return attachments.add(doc, name, originalPath, content);
+ }
+ };
+
+}).call(this);
View
20 node_modules/kanso-precompiler-base/package.json
@@ -0,0 +1,20 @@
+{
+ "author": "Pete Bacon Darwin",
+ "name": "kanso-precompiler-base",
+ "description": "A small utility library that takes the boiler plate out of creating precompilers for Kanso",
+ "version": "0.0.1",
+ "main": "./index",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/petebacondarwin/kanso-precompiler-base.git"
+ },
+ "engines": {
+ "node": "0.6.x"
+ },
+ "dependencies": {
+ "kanso-utils": "0.1.x",
+ "async": "0.1.x"
+ },
+ "devDependencies": {},
+ "optionalDependencies": {}
+}
View
113 src/compile.coffee
@@ -1,61 +1,56 @@
-async = require("async")
-utils = require("kanso-utils/utils")
-spawn = require("child_process").spawn
-path = require("path")
-modules = require("kanso-utils/modules")
-attachments = require("kanso-utils/attachments")
-coffee = require("coffee-script/lib/coffee-script/coffee-script")
-
module.exports =
- before: "properties"
+ before: "modules"
run: (root, path, settings, doc, callback) ->
- return callback(null, doc) unless settings["coffee-script"]
- return callback(null, doc) if not settings["coffee-script"]["modules"] and not settings["coffee-script"]["attachments"]
-
- module_paths = settings["coffee-script"]["modules"] or []
- module_paths = [ module_paths ] unless Array.isArray(module_paths)
-
- attach_paths = settings["coffee-script"]["attachments"] or []
- attach_paths = [ attach_paths ] unless Array.isArray(attach_paths)
-
- apply_compile_modules = async.apply(compile_modules, doc, path)
- apply_compile_attachments = async.apply(compile_attachments, doc, path)
-
- async.parallel [
- async.apply(async.forEach, module_paths, apply_compile_modules),
- async.apply(async.forEach, attach_paths, apply_compile_attachments)
- ], (err) -> callback err, doc
-
-compile_modules = (doc, path, paths, callback) ->
- pattern = /.*\.coffee$/i
- utils.find utils.abspath(paths, path), pattern, (err, data) ->
- return callback(err) if err
- apply_compile_module = async.apply(compile_module, doc, path)
- async.forEach data, apply_compile_module, callback
-
-compile_module = (doc, path, filename, callback) ->
- name = utils.relpath(filename, path).replace(/\.coffee$/, "")
- compile_coffee path, filename, (err, js) ->
- return callback(err) if err
- modules.add doc, name, js.toString()
- callback()
-
-compile_attachments = (doc, path, paths, callback) ->
- pattern = /.*\.coffee$/i
- utils.find utils.abspath(paths, path), pattern, (err, data) ->
- return callback(err) if err
- apply_compile_attachment = async.apply(compile_attachment, doc, path)
- async.forEach data, apply_compile_attachment, callback
-
-compile_attachment = (doc, path, filename, callback) ->
- name = utils.relpath(filename, path).replace(/\.coffee$/, ".js")
- compile_coffee path, filename, (err, js) ->
- return callback(err) if err
- attachments.add doc, name, name, new Buffer(js).toString("base64")
- callback()
-
-compile_coffee = (project_path, filename, callback) ->
- console.log "Compiling " + utils.relpath(filename, project_path)
-
- c = coffee.compile fs.readFileSync filename, 'utf8'
- callback null, c
+
+ modulesPaths = settings["coffee-script"]?["modules"]
+ attachmentsPaths = settings["coffee-script"]?["attachments"]
+
+ # Check that the settings are valid
+ unless modulesPaths? or attachmentsPaths?
+ console.log "Coffee script precompiler must have either a modules or an attachment setting"
+ return callback(null, doc)
+
+ modulesPaths ?= []
+ attachmentsPaths ?= []
+
+ # Pull in the required libraries
+ async = require("async")
+ utils = require("kanso-utils/utils")
+ precompiler = require("kanso-precompiler-base")
+ coffee = require("coffee-script")
+
+ # Specify the regular expression patterns that identify coffee files
+ file_pattern = /.*\.coffee$/i
+ extension_pattern = /\.coffee$/
+
+ # Compile a coffeescript file and attach it to the design document
+ compileAttachment = (filename, callback) ->
+ console.log("Compiling attachment")
+ js = coffee.compile(fs.readFileSync filename, 'utf8')
+ name = utils.relpath(filename, path).replace(extension_pattern, ".js")
+ precompiler.addAttachment(doc, name, filename,js)
+ callback(null, doc)
+
+ # Compile a coffeescript file and add it as a CommonJS module to the design document
+ compileModule = (filename, callback) ->
+ console.log("Compiling module")
+ js = coffee.compile(fs.readFileSync filename, 'utf8')
+ name = utils.relpath(filename, path).replace(extension_pattern, "")
+ precompiler.addModule(doc, name, filename, js)
+ callback(null, doc)
+
+ console.log "Running coffee-script pre-compiler"
+
+ console.dir()
+
+ # Extract the module and attachment paths from the settings
+ modules = precompiler.normalizePaths(settings["coffee-script"]["modules"], path)
+ attachments = precompiler.normalizePaths(attachmentsPaths, path)
+
+ # Create continuations for the functions that process whole folders of modules and attachments
+ processModules = async.apply(precompiler.processPaths, modules, file_pattern, compileModule)
+ processAttachments = async.apply(precompiler.processPaths, attachments, file_pattern, compileAttachment)
+
+ # Run the modules and attachments in parallel then callback to Kanso to tell it we are done, passing the design document
+ async.parallel([processModules, processAttachments],(err, results)->callback(err, doc))
+
View
3  testapp/kanso.json
@@ -23,6 +23,9 @@
"lib/updates.coffee",
"lib/validate.coffee",
"lib/views.coffee"
+ ],
+ "attachments": [
+ "static/js/test.coffee"
]
},
"dependencies": {
View
3  testapp/static/js/test.coffee
@@ -0,0 +1,3 @@
+class TestClass
+ constructor: (@somefield)->
+ alert("#{@somefield}")
View
2  testapp/templates/base.html
@@ -11,6 +11,6 @@
<script src="{baseURL}/static/js/jquery-1.5.2.min.js"></script>
<script src="{baseURL}/static/js/json2.js"></script>
<script src="{baseURL}/modules.js"></script>
- <script src="{baseURL}/kanso.js"></script>
+ <script src="{baseURL}/static/js/test.js"></script>
</body>
</html>

0 comments on commit 6031966

Please sign in to comment.
Something went wrong with that request. Please try again.