Permalink
Browse files

reorganizes internal libs and utils. mostly renaming, minor code refa…

…ctoring
  • Loading branch information...
1 parent 74d8e43 commit f5133698ae128e115096118969b1403f9a59ebde @jonschlinkert jonschlinkert committed Sep 30, 2013
View
1 .jshintrc
@@ -8,7 +8,6 @@
"sub": true,
"undef": false,
"boss": true,
- "eqnull": true,
"globals": {
"module": true,
"exports": true,
View
18 lib/assemble.js
@@ -1,19 +1,23 @@
/**
+ * Assemble
* Assemble <http://assemble.io>
* Created and maintained by Jon Schlinkert and Brian Woodward
*
* Copyright (c) 2013 Upstage.
* Licensed under the MIT License (MIT).
*/
-// NPM Libs
-var _ = require('lodash');
+// node_modules
+var yfm = require('assemble-yaml');
+var _ = require('lodash');
+
var Assemble = function() {
- var dataUtils = require('./data');
+ // Assemble utils.
var engineUtils = require('./engine');
- var utils = require('./util');
+ var collection = require('./collection');
+
var steps = [];
var init = function(task, grunt){
@@ -35,7 +39,7 @@ var Assemble = function() {
// add default collections
this.options.collections = _.union(this.options.collections, ['tags', 'categories', { name: 'pages' }]);
- this.options.collections = utils.collection.normalize(this.options.collections);
+ this.options.collections = collection.normalize(this.options.collections);
// if there is a pages property and it's an array, turn it into an object
if(this.options.pages && grunt.util.kindOf(this.options.pages) === 'array') {
@@ -97,9 +101,9 @@ var Assemble = function() {
step: step,
build: build,
- data: dataUtils,
+ data: yfm,
engine: engineUtils,
- util: utils
+ util: collection
};
};
View
183 lib/collection.js
@@ -0,0 +1,183 @@
+/**
+ * Assemble Collections
+ * Assemble <http://assemble.io>
+ * Created and maintained by Jon Schlinkert and Brian Woodward
+ *
+ * Copyright (c) 2013 Upstage.
+ * Licensed under the MIT License (MIT).
+ */
+
+
+// node_modules
+var _ = require('lodash');
+
+// Internal libs.
+var inflection = require('inflection');
+
+// The module to be exported.
+var collection = module.exports = {};
+
+
+collection.update = function(col, page, context) {
+ 'use strict';
+
+ if(!context[col.name]) {
+ return col;
+ }
+
+ var singularName = col.inflection || inflection.singularize(col.name);
+ var pageCol = context[col.name] || [];
+ if(toString.call(pageCol) !== '[object Array]') {
+ pageCol = [pageCol];
+ }
+
+ pageCol.forEach(function(pageItem) {
+ var i = _.findIndex(col.items, function(item) {
+ return item[singularName] === pageItem;
+ });
+
+ if(i === -1) {
+ var obj = {};
+ obj[singularName] = pageItem;
+ obj.pages = [page];
+ col.items.push(obj);
+ } else {
+ col.items[i].pages.push(page);
+ }
+ });
+ return col;
+};
+
+
+collection.sort = function(col) {
+ 'use strict';
+
+ var descMap = ['desc', 'descending'];
+ var itemMap = ['this', ''];
+
+ var sortby = _.contains(itemMap, (col.sortby || '')) ? '' : col.sortby;
+ var sortorder = _.contains(descMap, (col.sortorder || 'ASC').toLowerCase()) ? 'DESC' : 'ASC';
+
+ if(sortby === '') {
+
+ // sort items by the actual item
+ col.items.sort(function(a, b) {
+ if(a[col.inflection] && b[col.inflection]) {
+ if(a[col.inflection] < b[col.inflection]) {
+ return -1;
+ } else if (a[col.inflection] > b[col.inflection]) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+ });
+
+ if(sortorder !== 'ASC') {
+ col.items.reverse();
+ }
+
+ } else {
+
+ // for each item sort the pages by the page.data property
+ col.items.forEach(function(item) {
+
+ item.pages.sort(function(a, b) {
+ if(a.data[sortby] && b.data[sortby]) {
+ if(a.data[sortby] < b.data[sortby]) {
+ return -1;
+ } else if (a.data[sortby] > b.data[sortby]) {
+ return 1;
+ } else {
+ return 0;
+ }
+ } else {
+ return 0;
+ }
+ });
+
+ if(sortorder !== 'ASC') {
+ item.pages.reverse();
+ }
+
+ });
+
+ // now sort the items by the first page in each item
+ col.items.sort(function(a, b) {
+ if(a.pages.length > 0 && b.pages.length > 0) {
+ if(a.pages[0].data[sortby] && b.pages[0].data[sortby]) {
+ if(a.pages[0].data[sortby] < b.pages[0].data[sortby]) {
+ return -1;
+ } else if(a.pages[0].data[sortby] > b.pages[0].data[sortby]) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+ } else {
+ return 0;
+ }
+ });
+
+ if(sortorder !== 'ASC') {
+ col.items.reverse();
+ }
+
+ }
+
+ return col;
+
+};
+
+
+/**
+ * Takes in a list of collection definitions and normalizes
+ * them to a be all objects with smart defaults
+ * @param {Array} collections: List of collections as either strings or objects
+ * @return {Array} Return list of collections, all as objects
+ */
+collection.normalize = function(collections) {
+ 'use strict';
+
+ var rtn = {};
+ collections.forEach(function(item) {
+
+ if(typeof item === 'string') {
+ if(rtn[item]) {
+ item = rtn[item];
+ } else {
+ item = {
+ name: item,
+ inflection: inflection.singularize(item),
+ sortorder: 'ASC',
+ sortby: '',
+ items: []
+ };
+ }
+ } else {
+ item.items = [];
+ }
+
+ if(item.name === 'pages') {
+ item.inflection = '_page';
+ item.sortby = (item.sortby || '') === '' ? 'name' : item.sortby;
+ item.items = [{
+ '_page': 'all',
+ pages: []
+ }];
+ }
+
+ rtn[item.name] = item;
+
+ });
+
+ return rtn;
+
+
+};
+
+
+var filterOptionsProperties = ['defaultLayout', 'initializeEngine', 'registerFunctions', 'registerPartial'];
+collection.filterProperties = function(opts) {
+ return _.omit(opts, filterOptionsProperties);
+};
View
28 lib/data/index.js
@@ -1,28 +0,0 @@
-/**
- * Data
- *
- * Assemble <http://assemble.io>
- * Created and maintained by Jon Schlinkert and Brian Woodward
- *
- * Copyright (c) 2013 Upstage.
- * Licensed under the MIT License (MIT).
- */
-
-var frontmatter = require('assemble-yaml');
-var markdown = require('./markdown');
-
-module.exports = exports = {
-
- readYFM: function(src, opts) {
- return frontmatter.extract(src, opts);
- },
-
- readMarkdown: function(src, opts) {
- return markdown.read(src, opts);
- },
-
- convertMarkdown: function(src, opts) {
- return markdown.convert(src, opts);
- }
-
-};
View
107 lib/data/markdown.js
@@ -1,107 +0,0 @@
-/**
- * Markdown
- *
- * Assemble <http://assemble.io>
- * Created and maintained by Jon Schlinkert and Brian Woodward
-*
- * Copyright (c) 2013 Upstage.
- * Licensed under the MIT License (MIT).
-*/
-
-
-var marked = require('marked');
-var hljs = require('highlight.js');
-var fs = require('fs');
-var _ = require('lodash');
-
-
-/*
-* CREDIT: Some of the following code is from grunt-markdown
-* https://github.com/treasonx/grunt-markdown
-*/
-
-var markdown = {
-
- init: function(opts) {
- this.options = _.extend({fromFile: true}, opts);
- return this;
- },
-
- read: function(src, opts) {
-
- if(opts) {
- this.init(opts);
- }
-
- // read in a file and convert it to html using marked
- if(!fs.existsSync(src)) {
- console.log("File " + src + " not found.");
- return '';
- }
-
- var md = fs.readFileSync(src, 'utf8');
- return this.convert(md);
- },
-
- convert: function(src, opts) {
-
- if(opts) {
- this.init(opts);
- }
-
- // wrapLines function from grunt-markdown
- var codeLines = this.options.codeLines;
- var shouldWrap = false;
- if(codeLines && codeLines.before && codeLines.after) {
- shouldWrap = true;
- }
-
- var wrapLines = function(code) {
- var out = [];
- var before = codeLines.before;
- var after = codeLines.after;
- code = code.split('\n');
- code.forEach(function(line) {
- out.push(before+line+after);
- });
- return out.join('\n');
- };
-
- // highlighting function setup from grunt-markdown
- if(typeof this.options.highlight === 'string') {
- if(this.options.highlight === 'auto') {
-
- this.options.highlight = function(code) {
- var out = hljs.highlightAuto(code).value;
- if(shouldWrap) {
- out = wrapLines(out);
- }
- return out;
- };
-
- } else if (this.options.highlight === 'manual') {
-
- this.options.highlight = function(code, lang) {
- var out = code;
- try {
- code = hljs.highlight(lang, code).value;
- } catch(e) {
- out = hljs.highlightAuto(code).value;
- }
- if(shouldWrap) {
- out = wrapLines(out);
- }
- return out;
- };
-
- }
- }
-
- marked.setOptions(this.options);
- var html = marked(src);
- return html;
- }
-
-};
-
-module.exports = exports = markdown;
View
9 lib/engine/index.js → lib/engine.js
@@ -1,16 +1,19 @@
/**
- * Engine
- *
+ * Assemble Engine Factory
* Assemble <http://assemble.io>
* Created and maintained by Jon Schlinkert and Brian Woodward
*
* Copyright (c) 2013 Upstage.
* Licensed under the MIT License (MIT).
*/
-var grunt = require('grunt');
+// node_modules
+var grunt = require('grunt');
+
+// Internal libs.
var helpers = require('./helpers');
+
var EngineFactory = function() {
'use strict';
View
0 lib/engine/extensions.yml → lib/extensions.yml
File renamed without changes.
View
26 lib/engine/helpers.js → lib/helpers.js
@@ -1,26 +1,32 @@
/**
- * Helpers
- *
+ * Assemble Helpers
* Assemble <http://assemble.io>
* Created and maintained by Jon Schlinkert and Brian Woodward
*
* Copyright (c) 2013 Upstage.
* Licensed under the MIT License (MIT).
*/
+// Node.js
+var path = require('path');
+var fs = require('fs');
+
+// node_modules
var resolve = require('resolve-dep');
-var grunt = require('grunt');
-var path = require('path');
-var _ = require('lodash');
-var fs = require('fs');
+var grunt = require('grunt');
+var _ = grunt.util._;
-module.exports.register = function(glob, plugin, engine, options) {
- var resolvedFiles = resolve.loadDev(glob) || [];
- var localFiles = grunt.file.expand(options, glob) || [];
+module.exports.register = function(patterns, plugin, engine, options) {
- var files = _.union([], resolvedFiles, localFiles);
+ // Resolve and load helpers from node_modules, if the helper name is listed both
+ // in the "helpers" option of the assemble task and devDependencies.
+ var resolvedFiles = resolve.loadDev(patterns) || [];
+ // Load local helpers defined in the "helpers" option of the assemble task.
+ var localFiles = grunt.file.expand(options, patterns) || [];
+
+ var files = _.union([], resolvedFiles, localFiles);
files.forEach(function(file) {
var helper = null;
try {
View
66 lib/markdown.js
@@ -0,0 +1,66 @@
+/**
+ * Assemble Markdown
+ * Assemble <http://assemble.io>
+ * Created and maintained by Jon Schlinkert and Brian Woodward
+ *
+ * Copyright (c) 2013 Upstage.
+ * Licensed under the MIT License (MIT).
+ */
+
+// Node.js
+var fs = require('fs');
+
+// node_modules
+var marked = require('marked');
+var hljs = require('highlight.js');
+var grunt = require('grunt');
+var _ = grunt.util._;
+
+// The module to be exported.
+var markdown = module.exports = {};
+
+
+markdown.init = function(opts) {
+ opts = opts || {};
+ this.options = _.extend({}, {fromFile: true}, opts);
+ return this;
+};
+
+
+markdown.convert = function(src, opts) {
+ if(opts) {this.init(opts);}
+ if(typeof this.options.highlight === 'string') {
+ if(this.options.highlight === 'auto') {
+ this.options.highlight = function(code) {
+ return hljs.highlightAuto(code).value;
+ };
+ } else if (this.options.highlight === 'manual') {
+ this.options.highlight = function(code, lang) {
+ try {
+ code = hljs.highlight(lang, code).value;
+ } catch(e) {
+ code = hljs.highlightAuto(code).value;
+ }
+ return code;
+ };
+ }
+ }
+
+ marked.setOptions(this.options);
+ return marked(src);
+};
+
+
+markdown.read = function(src, opts) {
+ if(opts) {this.init(opts);}
+ // Verify that the markdown file exists.
+ if(!grunt.file.exists(src)) {
+ console.log("File " + src + " not found.");
+ return '';
+ }
+ // Convert markdown to HTML
+ return this.convert(grunt.file.read(src));
+};
+
+
+
View
172 lib/util/collection.js
@@ -1,172 +0,0 @@
-/**
- * Collections
- *
- * Assemble <http://assemble.io>
- * Created and maintained by Jon Schlinkert and Brian Woodward
- *
- * Copyright (c) 2013 Upstage.
- * Licensed under the MIT License (MIT).
- */
-
-var inflection = require('inflection');
-var _ = require('lodash');
-
-var collection = {
-
- update: function(col, page, context) {
-
- if(!context[col.name]) {
- return col;
- }
-
- var singularName = col.inflection || inflection.singularize(col.name);
-
- var pageCol = context[col.name] || [];
- if(toString.call(pageCol) !== '[object Array]') {
- pageCol = [pageCol];
- }
-
- pageCol.forEach(function(pageItem) {
-
- var i = _.findIndex(col.items, function(item) {
- return item[singularName] === pageItem;
- });
-
- if(i === -1) {
- var obj = {};
- obj[singularName] = pageItem;
- obj.pages = [page];
- col.items.push(obj);
- } else {
- col.items[i].pages.push(page);
- }
- });
- return col;
- },
-
- sort: function(col) {
-
- var descMap = ['desc', 'descending'];
- var itemMap = ['this', ''];
-
- var sortby = _.contains(itemMap, (col.sortby || '')) ? '' : col.sortby;
- var sortorder = _.contains(descMap, (col.sortorder || 'ASC').toLowerCase()) ? 'DESC' : 'ASC';
-
- if(sortby === '') {
-
- // sort items by the actual item
- col.items.sort(function(a, b) {
- if(a[col.inflection] && b[col.inflection]) {
- if(a[col.inflection] < b[col.inflection]) {
- return -1;
- } else if (a[col.inflection] > b[col.inflection]) {
- return 1;
- } else {
- return 0;
- }
- }
- });
-
- if(sortorder !== 'ASC') {
- col.items.reverse();
- }
-
- } else {
-
- // for each item sort the pages by the page.data property
- col.items.forEach(function(item) {
-
- item.pages.sort(function(a, b) {
- if(a.data[sortby] && b.data[sortby]) {
- if(a.data[sortby] < b.data[sortby]) {
- return -1;
- } else if (a.data[sortby] > b.data[sortby]) {
- return 1;
- } else {
- return 0;
- }
- } else {
- return 0;
- }
- });
-
- if(sortorder !== 'ASC') {
- item.pages.reverse();
- }
-
- });
-
- // now sort the items by the first page in each item
- col.items.sort(function(a, b) {
- if(a.pages.length > 0 && b.pages.length > 0) {
- if(a.pages[0].data[sortby] && b.pages[0].data[sortby]) {
- if(a.pages[0].data[sortby] < b.pages[0].data[sortby]) {
- return -1;
- } else if(a.pages[0].data[sortby] > b.pages[0].data[sortby]) {
- return 1;
- } else {
- return 0;
- }
- }
- } else {
- return 0;
- }
- });
-
- if(sortorder !== 'ASC') {
- col.items.reverse();
- }
-
- }
-
- return col;
-
- },
-
- /**
- * Takes in a list of collection definitions and normalizes
- * them to a be all objects with smart defaults
- * @param {Array} collections: List of collections as either strings or objects
- * @return {Array} Return list of collections, all as objects
- */
- normalize: function(collections) {
-
- var rtn = {};
- collections.forEach(function(item) {
-
- if(typeof item === 'string') {
- if(rtn[item]) {
- item = rtn[item];
- } else {
- item = {
- name: item,
- inflection: inflection.singularize(item),
- sortorder: 'ASC',
- sortby: '',
- items: []
- };
- }
- } else {
- item.items = [];
- }
-
- if(item.name === 'pages') {
- item.inflection = '_page';
- item.sortby = (item.sortby || '') === '' ? 'name' : item.sortby;
- item.items = [{
- '_page': 'all',
- pages: []
- }];
- }
-
- rtn[item.name] = item;
-
- });
-
- return rtn;
- }
-
-};
-
-
-module.exports = exports = collection;
View
24 lib/util/index.js
@@ -1,24 +0,0 @@
-/**
- * Assemble <http://assemble.io>
- * Created and maintained by Jon Schlinkert and Brian Woodward
- *
- * Copyright (c) 2013 Upstage.
- * Licensed under the MIT License (MIT).
- */
-
-var _ = require('lodash');
-var collection = require('./collection');
-
-var filterOptionsProperties = [
- 'defaultLayout',
- 'initializeEngine',
- 'registerFunctions',
- 'registerPartial'
-];
-
-module.exports = exports = {
- collection: collection,
- filterProperties: function(opts) {
- return _.omit(opts, filterOptionsProperties);
- }
-};
View
253 tasks/assemble.js
@@ -9,35 +9,36 @@
module.exports = function(grunt) {
// Grunt utils
- var file = grunt.file;
- var log = grunt.log;
- var kindOf = grunt.util.kindOf;
- var _str = grunt.util._.str;
var async = grunt.util.async;
+ var _str = grunt.util._.str;
+ var file = grunt.file;
- // Node utils
- var path = require('path');
- var fs = require('fs');
- var util = require('util');
+ // Node.js
+ var path = require('path');
+ var fs = require('fs');
+ var util = require('util');
- // NPM utils
+ // node_modules
var inflection = require('inflection');
- var _ = require('lodash');
+ var yfm = require('assemble-yaml');
+ var _ = require('lodash');
// Assemble utils
- var assemble = require('../lib/assemble');
+ var collection = require('../lib/collection');
+ var assemble = require('../lib/assemble');
+ var Utils = require('./utils/utils');
- grunt.registerMultiTask('assemble', 'Compile template files with specified engines', function() {
+ grunt.registerMultiTask('assemble', 'Compile template files with specified engines', function() {
+
var done = this.async();
var self = this;
-
// functions for use in build steps
var optionsConfiguration = function(assemble, next) {
- grunt.verbose.writeln('validating options');
+ grunt.verbose.writeln('Validating options');
if(_str.endsWith(assemble.options.ext, '.')) {
grunt.warn('Invalid ext "' + assemble.options.ext + '". ext cannot end with a period.');
@@ -79,7 +80,7 @@ module.exports = function(grunt) {
var registerPartial = function(engine, filename, content) { engine.registerPartial(filename, content); };
assemble.options.registerPartial = assemble.options.registerPartial || registerPartial;
- assemble.fileExt = extension(src);
+ assemble.fileExt = Utils.extension(src);
assemble.filenameRegex = /[^\\\/:*?"<>|\r\n]+$/i;
assemble.fileExtRegex = new RegExp('\\.' + assemble.fileExt + '$');
@@ -141,7 +142,7 @@ module.exports = function(grunt) {
partial = removeHbsWhitespace(assemble,partial);
// get the data
- var partialInfo = assemble.data.readYFM(partial, {fromFile: false});
+ var partialInfo = yfm.extract(partial, {fromFile: false});
assemble.options.data[filename] = _.extend({}, partialInfo.context || {}, assemble.options.data[filename] || {});
// register the partial
@@ -169,7 +170,7 @@ module.exports = function(grunt) {
var ext = path.extname(filepath);
var filename = path.basename(filepath, ext);
- var fileReader = dataFileReaderFactory(ext);
+ var fileReader = Utils.dataFileReaderFactory(ext);
var filecontent = grunt.file.read(filepath);
@@ -180,16 +181,16 @@ module.exports = function(grunt) {
if(filename === 'data') {
// if this is the base data file, load it into the options.data object directly
- assemble.options.data = _.extend({}, assemble.options.data || {}, fileReader(filepath));
+ assemble.options.data = _.extend({}, (assemble.options.data || {}), fileReader(filepath));
} else {
// otherwise it's an element in options.data
var d = fileReader(filepath);
if(d[filename]) {
// json object contains root object name so extend it in options.json
- assemble.options.data[filename] = _.extend({}, assemble.options.data[filename] || {}, d[filename]);
+ assemble.options.data[filename] = _.extend({}, (assemble.options.data[filename] || {}), d[filename]);
} else {
// add the entire object
- assemble.options.data[filename] = _.extend({}, assemble.options.data[filename] || {}, d);
+ assemble.options.data[filename] = _.extend({}, (assemble.options.data[filename] || {}), d);
}
}
complete ++;
@@ -233,7 +234,7 @@ module.exports = function(grunt) {
}
src = src || filePair.src;
- //var basePath = findBasePath(src, true);
+ //var basePath = Utils.findBasePath(src, true);
// some of the code for calculating destination paths files was
// inspired by https://github.com/gruntjs/grunt-contrib-copy
@@ -244,64 +245,68 @@ module.exports = function(grunt) {
var useFileInfo = (typeof fileInfo !== 'undefined');
- srcFile = urlNormalize(path.normalize(srcFile));
+ srcFile = Utils.pathNormalize(path.normalize(srcFile));
var filename = path.basename(srcFile, path.extname(srcFile));
- if(detectDestType(filePair.dest) === 'directory') {
+
+ if(Utils.detectDestType(filePair.dest) === 'directory') {
destFile = (isExpandedPair) ? filePair.dest : path.join(
filePair.dest, (assemble.options.flatten ? path.basename(srcFile) : srcFile)
);
} else {
destFile = filePair.dest;
}
- destFile = urlNormalize(path.join(path.dirname(destFile), path.basename(destFile, path.extname(destFile)))) + assemble.options.ext;
+ var destDirname = path.dirname(destFile);
+ var destBasename = path.basename(destFile, path.extname(destFile));
+ destFile = Utils.pathNormalize(path.join(destDirname, destBasename)) + assemble.options.ext;
grunt.verbose.writeln('Reading ' + filename.magenta);
- // setup options.assets so it's the relative path to the dest assets folder
- // from the new dest file TODO: this needs to be looked at again after the
- // other dest changes
- grunt.verbose.writeln('AssetsPath: ' + assetsPath);
- grunt.verbose.writeln('DestFile: ' + path.dirname(destFile));
- assemble.options.assets = urlNormalize(
- path.relative(path.resolve(path.dirname(destFile)), path.resolve(assetsPath))
- );
- // if the assets relative path is blank, then it's the same folder so update
- // to be '' or './'
+ /**
+ * Calculate "assets" path
+ */
+
+
+ // `options.assets` generate the relative path to the dest "assets"
+ // directory from the location of the newly generated dest file
+ grunt.verbose.writeln('assetsPath: ' + assetsPath);
+ grunt.verbose.writeln('DestFile: ' + destDirname);
+ assemble.options.assets = Utils.pathNormalize(
+ path.relative(path.resolve(destDirname), path.resolve(assetsPath))
+ );
+ // if the assets relative path is blank, then it's the same folder
+ // so update to be '' or './'
if (!assemble.options.assets || assemble.options.assets.length === 0) {
// if the original path had a trailing slash
- if (hasTrailingSlash(assetsPath)) {
+ if (Utils.hasTrailingSlash(assetsPath)) {
// return './'
assemble.options.assets = './';
} else {
// otherwise return ''
assemble.options.assets = '.';
}
}
-
// if the original path had a trailing slash and the calculated path does
// not, add a trailing slash
- if (hasTrailingSlash(assetsPath) && !hasTrailingSlash(assemble.options.assets)) {
-
+ if (Utils.hasTrailingSlash(assetsPath) && !Utils.hasTrailingSlash(assemble.options.assets)) {
assemble.options.assets += '/';
-
// if the original path did not have a trailing slash and the calculated
// path does, remove the trailing slash
- } else if (!hasTrailingSlash(assetsPath) && hasTrailingSlash(assemble.options.assets)) {
-
+ } else if (!Utils.hasTrailingSlash(assetsPath) && Utils.hasTrailingSlash(assemble.options.assets)) {
assemble.options.assets = assemble.options.assets.substring(0, assemble.options.assets.length - 2);
-
}
- grunt.verbose.writeln(('\t' + 'Src: ' + srcFile));
- grunt.verbose.writeln(('\t' + 'Dest: ' + destFile));
- grunt.verbose.writeln(('\t' + 'Assets: ' + assemble.options.assets));
+ grunt.verbose.writeln(('\t' + 'srcFile: ' + srcFile));
+ grunt.verbose.writeln(('\t' + 'destFile: ' + destFile));
+ grunt.verbose.writeln(('\t' + 'assets: ' + assemble.options.assets));
+
+
var page = useFileInfo ? (fileInfo.content || '') : grunt.file.read(srcFile);
try {
- grunt.verbose.writeln('compiling page ' + filename.magenta);
+ grunt.verbose.writeln('Compiling page ' + filename.magenta);
var pageContext = {};
// If the page file is empty, we still want to process it. Since the compiler
@@ -313,23 +318,25 @@ module.exports = function(grunt) {
// If options.removeHbsWhitespace is true
page = removeHbsWhitespace(assemble, page);
- var pageInfo = assemble.data.readYFM(page, {fromFile: false});
+ var pageInfo = yfm.extract(page, {fromFile: false});
pageContext = useFileInfo ? (fileInfo.data || fileInfo.metadata || {}) : pageInfo.context;
+ // Page object
var pageObj = {
'_page': 'all',
+
dirname : path.dirname(destFile),
filename: path.basename(destFile),
- pageName: path.basename(destFile),
+ pageName: path.basename(destFile), // deprecated, use pagename or filename
pagename: path.basename(destFile),
basename: path.basename(filename, path.extname(filename)),
- src: srcFile,
- dest: destFile,
- assets: assemble.options.assets,
- ext: assemble.options.ext,
- extname: assemble.options.ext,
- page: pageInfo.content,
- data: pageContext
+ src : srcFile,
+ dest : destFile,
+ assets : assemble.options.assets,
+ ext : assemble.options.ext,
+ extname : assemble.options.ext,
+ page : pageInfo.content,
+ data : pageContext
};
if(pageObj.data.published === false) {
@@ -338,13 +345,13 @@ module.exports = function(grunt) {
}
assemble.options.collections.pages.items[0].pages.push(pageObj);
-
- _.each(assemble.options.collections, function(item, key) {
+ _(assemble.options.collections).forEach(function(item, key) {
if(key !== 'pages') {
- assemble.options.collections[key] = assemble.util.collection.update(item, pageObj, pageContext);
+ assemble.options.collections[key] = collection.update(item, pageObj, pageContext);
}
});
+
} catch(err) {
grunt.warn(err);
return false;
@@ -361,7 +368,6 @@ module.exports = function(grunt) {
pairDone();
return false;
}
-
pairDone();
}, buildDone); // filePair.src.forEach
},
@@ -375,26 +381,24 @@ module.exports = function(grunt) {
buildDone();
return false;
}
-
if(!buildPage(filename, fileInfo)) {
buildDone();
return false;
}
});
}
-
buildDone();
}
], done);
}, stepDone); // this.files.forEach
},
function(stepDone){
- grunt.verbose.writeln('information compiled');
+ grunt.verbose.writeln('Information compiled');
- assemble.options.pages = assemble.util.collection.sort(assemble.options.collections.pages).items[0].pages;
- _.each(assemble.options.collections, function(item, key) {
+ assemble.options.pages = collection.sort(assemble.options.collections.pages).items[0].pages;
+ _(assemble.options.collections).forEach(function(item, key) {
if(key !== 'pages') {
- assemble.options[key] = assemble.util.collection.sort(item).items;
+ assemble.options[key] = collection.sort(item).items;
}
});
@@ -403,17 +407,22 @@ module.exports = function(grunt) {
], function(){ next(assemble); });
};
- var renderPages = function(assemble, next) {
+
+ /**
+ * Render pages
+ * @param {[type]} assemble [description]
+ * @param {Function} next [description]
+ * @return {[type]} [description]
+ */
+ var renderPages = function(assemble, next) {
grunt.verbose.writeln(('\n' + 'Assembling pages...').yellow);
async.forEach(assemble.options.pages, function(page, done) {
-
grunt.verbose.writeln(require('util').inspect(page));
build(page, assemble, function(err, result) {
grunt.log.write('Assembling ' + (page.dest).cyan +' ');
-
if(err) {
grunt.verbose.write(' ');
grunt.log.error();
@@ -422,16 +431,18 @@ module.exports = function(grunt) {
return;
}
grunt.verbose.writeln('..');
+
+ // Write the file.
file.write(page.dest, result);
grunt.verbose.writeln('Assembled ' + (page.dest).cyan +' OK'.green);
-
grunt.log.notverbose.ok();
done();
}); // build
+
+
}, function(){
grunt.log.ok(((assemble.options.pages).length).toString() + ' pages assembled.');
-
next(assemble);
});
};
@@ -457,53 +468,19 @@ module.exports = function(grunt) {
});
- // ==========================================================================
- // HELPERS
- // ==========================================================================
-
- var findBasePath = function(srcFiles, basePath) {
- if (basePath === false) {
- return '';
- }
-
- if (grunt.util.kindOf(basePath) === 'string' && basePath.length >= 1) {
- return _(path.normalize(basePath)).trim(path.sep);
- }
-
- var foundPath;
- var basePaths = [];
- var dirName;
-
- srcFiles.forEach(function(srcFile) {
- srcFile = path.normalize(srcFile);
- dirName = path.dirname(srcFile);
-
- basePaths.push(dirName.split(path.sep));
- });
-
- basePaths = _.intersection.apply([], basePaths);
-
- foundPath = path.join.apply(path, basePaths);
-
- if (foundPath === '.') {
- foundPath = '';
- }
-
- return foundPath;
- };
-
// ==========================================================================
// BUILD
// ==========================================================================
var build = function(currentPage, assemble, callback) {
- var src = currentPage.srcFile;
+ var src = currentPage.srcFile;
var filename = currentPage.filename;
- var options = assemble.options;
+ var options = assemble.options;
+
+ grunt.verbose.writeln('Currentpage: ' + currentPage);
- grunt.verbose.writeln('currentPage: ' + currentPage);
var page = currentPage.page,
pageContext = currentPage.data,
layout = _.cloneDeep(options.defaultLayout),
@@ -514,7 +491,7 @@ module.exports = function(grunt) {
EngineLoader = options.EngineLoader,
context = {};
- grunt.verbose.writeln('variables loaded');
+ grunt.verbose.writeln('Variables loaded');
//options.data = null;
@@ -663,7 +640,7 @@ module.exports = function(grunt) {
// If options.removeHbsWhitespace is true
layout = removeHbsWhitespace(assemble, layout);
- var layoutInfo = assemble.data.readYFM(layout, {fromFile: false});
+ var layoutInfo = yfm.extract(layout, {fromFile: false});
var layoutData = layoutInfo.context;
var results = {
@@ -711,63 +688,13 @@ module.exports = function(grunt) {
return layout.replace(assemble.engine.bodyRegex, function() { return body; });
};
- var detectDestType = function(dest) {
- if(_str.endsWith(path.normalize(dest), path.sep)) {
- return 'directory';
- } else {
- return 'file';
- }
- };
-
- var hasTrailingSlash = function(filePath) {
- return _str.endsWith(path.normalize(filePath), path.sep);
- };
-
- var logBlock = function(heading, message) {
- grunt.verbose.writeln(heading.cyan);
- grunt.verbose.writeln(message);
- grunt.verbose.writeln();
- };
var getEngineOf = function(fileName) {
- var ext = extension(fileName);
+ var ext = Utils.extension(fileName);
+ console.log(assemble.engine.extensions[ext]);
return _( _(assemble.engine.extensions).keys() ).include(ext) ? assemble.engine.extensions[ext] : false;
};
- var extension = function(fileName) {
- grunt.verbose.writeln('extension');
- grunt.verbose.writeln(fileName);
- if(kindOf(fileName) === 'array' && fileName.length > 0) {
- fileName = fileName[0];
- }
- return _(fileName.match(/[^.]*$/)).last();
- };
-
- // Windows? (from grunt.file)
- var win32 = process.platform === 'win32';
- var urlNormalize = function(urlString) {
- if (win32) {
- return urlString.replace(/\\/g, '/');
- } else {
- return urlString;
- }
- };
-
- var dataFileReaderFactory = function(ext) {
- var reader = grunt.file.readJSON;
- switch(ext) {
- case '.json':
- reader = grunt.file.readJSON;
- break;
-
- case '.yml':
- case '.yaml':
- reader = grunt.file.readYAML;
- break;
- }
- return reader;
- };
-
// Attempt to remove extra whitespace around Handlebars expressions
// in generated HTML, similar to what mustache.js does
var removeHbsWhitespace = function(assemble, filecontent) {
@@ -778,4 +705,4 @@ module.exports = function(grunt) {
return filecontent;
};
-};
+};
View
111 tasks/utils/utils.js
@@ -0,0 +1,111 @@
+/*
+ * Assemble Utils
+ * https://github.com/assemble/
+ *
+ * Copyright (c) 2013 Upstage
+ * Licensed under the MIT license.
+ */
+
+
+// Node.js
+var path = require('path');
+
+// node_modules
+var grunt = require('grunt');
+var _str = grunt.util._.str;
+var _ = require('lodash'); // newer methods
+
+// The module to be exported.
+var Utils = module.exports = {};
+
+
+
+// Windows? (from grunt.file)
+var win32 = process.platform === 'win32';
+Utils.pathNormalize = function(urlString) {
+ if (win32) {
+ return urlString.replace(/\\/g, '/');
+ } else {
+ return urlString;
+ }
+};
+
+
+Utils.extension = function(filename) {
+ grunt.verbose.writeln('extension');
+ grunt.verbose.writeln(filename);
+ if(grunt.util.kindOf(filename) === 'array' && filename.length > 0) {
+ filename = filename[0];
+ }
+ return _(filename.match(/[^.]*$/)).last();
+};
+
+/**
+ * Is the given path a directory or a file?
+ * @param {String} filepath
+ * @return {String}
+ */
+Utils.detectDestType = function(filepath) {
+ // if(_str.endsWith(path.normalize(filepath), path.sep)) {
+ // return 'directory';
+ // } else {
+ // return 'file';
+ // }
+ if(grunt.file.isDir(filepath)) {
+ return 'directory';
+ } else if (grunt.file.isFile(filepath)) {
+ if (grunt.file.exists(filepath)) {
+ return 'file';
+ } else {
+ throw new Error('Invalid file path.');
+ }
+ }
+};
+
+
+Utils.findBasePath = function(srcFiles, basePath) {
+ if (basePath === false) {return '';}
+ if (grunt.util.kindOf(basePath) === 'string' && basePath.length >= 1) {
+ return _(path.normalize(basePath)).trim(path.sep);
+ }
+ var foundPath, basePaths = [], dirName;
+ srcFiles.forEach(function(srcFile) {
+ srcFile = path.normalize(srcFile);
+ dirName = path.dirname(srcFile);
+ basePaths.push(dirName.split(path.sep));
+ });
+ basePaths = _.intersection.apply([], basePaths);
+ foundPath = path.join.apply(path, basePaths);
+ if (foundPath === '.') {foundPath = '';}
+ return foundPath;
+};
+
+
+/**
+ * Check if the give file path ends with a slash.
+ * @param {String} filePath
+ * @return {Boolean}
+ */
+Utils.hasTrailingSlash = function(filePath) {
+ return _str.endsWith(path.normalize(filePath), path.sep);
+};
+
+
+/**
+ * Read in the given data file based on the file extension.
+ * @param {String} ext The file extension to check.
+ * @return {Object} JSON data object.
+ */
+Utils.dataFileReaderFactory = function(ext) {
+ var reader = grunt.file.readJSON;
+ switch(ext) {
+ case '.json':
+ reader = grunt.file.readJSON;
+ break;
+ case '.yml':
+ case '.yaml':
+ reader = grunt.file.readYAML;
+ break;
+ }
+ return reader;
+};
View
10 test/assemble_test.js
@@ -1,3 +1,4 @@
+/*global require:true */
/**
* Assemble <http://assemble.io>
* Created and maintained by Jon Schlinkert and Brian Woodward
@@ -6,14 +7,13 @@
* Licensed under the MIT License (MIT).
*/
-/*global require:true */
-var assemble = require('../lib/assemble.js'),
- expect = require('chai').expect;
+var assemble = require('../lib/assemble');
+var expect = require('chai').expect;
-describe("awesome", function() {
+
+describe("awesome", function() {
it('should run an awesome test', function() {
expect(1).to.equal(1);
});
-
});
View
24 test/collection_tests.js
@@ -1,3 +1,4 @@
+/*global require:true */
/**
* Assemble <http://assemble.io>
* Created and maintained by Jon Schlinkert and Brian Woodward
@@ -6,15 +7,16 @@
* Licensed under the MIT License (MIT).
*/
-/*global require:true */
-var expect = require('chai').expect;
-var util = require('../lib/util');
-var _ = require('lodash');
-var grunt = require('grunt');
-var path = require('path');
+var collection = require('../lib/collection');
+var expect = require('chai').expect;
+var grunt = require('grunt');
+var path = require('path');
+var _ = require('lodash');
+
+
var getCollection = function(file) {
- return grunt.file.readJSON(path.join('.', 'test', 'fixtures', 'data', 'collections', file));
+ return grunt.file.readJSON(path.join('./test/fixtures/data/collections', file));
};
var fakeCollection = getCollection('fakeCollection.json');
@@ -26,7 +28,7 @@ describe('Collections', function() {
it("by item name asc", function(done) {
var expected = getCollection('expected-sortby-item-asc.json');
var col = _.cloneDeep(fakeCollection);
- var actual = util.collection.sort(col);
+ var actual = collection.sort(col);
grunt.verbose.writeln(require('util').inspect(actual, null, 10));
expect(actual).to.deep.equal(expected);
done();
@@ -36,7 +38,7 @@ describe('Collections', function() {
var expected = getCollection('expected-sortby-item-desc.json');
var col = _.cloneDeep(fakeCollection);
col.sortorder = 'DESC';
- var actual = util.collection.sort(col);
+ var actual = collection.sort(col);
grunt.verbose.writeln(require('util').inspect(actual, null, 10));
expect(actual).to.deep.equal(expected);
done();
@@ -46,7 +48,7 @@ describe('Collections', function() {
var expected = getCollection('expected-sortby-page-property-asc.json');
var col = _.cloneDeep(fakeCollection);
col.sortby = 'title';
- var actual = util.collection.sort(col);
+ var actual = collection.sort(col);
grunt.verbose.writeln(require('util').inspect(actual, null, 10));
expect(actual).to.deep.equal(expected);
done();
@@ -57,7 +59,7 @@ describe('Collections', function() {
var col = _.cloneDeep(fakeCollection);
col.sortorder = 'DESC';
col.sortby = 'title';
- var actual = util.collection.sort(col);
+ var actual = collection.sort(col);
grunt.verbose.writeln(require('util').inspect(actual, null, 10));
expect(actual).to.deep.equal(expected);
done();
View
8 test/engine_test.js
@@ -6,9 +6,11 @@
* Licensed under the MIT License (MIT).
*/
-var assembleEngine = require('../lib/engine'),
- engineHelpers = require('../lib/engine/helpers'),
- expect = require('chai').expect;
+var assembleEngine = require('../lib/engine');
+var assembleHelpers = require('../lib/helpers');
+var expect = require('chai').expect;
+
+
describe('Loading default handlebars engine', function() {
View
1 test/helpers/helper-lists.js
@@ -7,6 +7,7 @@
*/
module.exports.register = function(Handlebars, options) {
+ /*jshint eqnull: true */
var toString = function(val) {
if (val == null) {
View
12 test/markdown_test.js
@@ -6,8 +6,10 @@
* Licensed under the MIT License (MIT).
*/
-var assembleData = require('../lib/data');
- expect = require('chai').expect;
+var markdown = require('../lib/markdown');
+var expect = require('chai').expect;
+
+
describe('Converting Markdown files', function() {
@@ -34,19 +36,19 @@ describe('Converting Markdown files', function() {
describe('Using new style', function() {
it("convert markdown string", function(done) {
- var data = assembleData.convertMarkdown(simple, opts);
+ var data = markdown.convert(simple, opts);
//expect(data).to.equal(simpleExpected);
done();
});
it("read markdown file", function(done) {
- var data = assembleData.readMarkdown('./test/fixtures/pages/simple1.md', opts);
+ var data = markdown.read('./test/fixtures/pages/simple1.md', opts);
expect(data).to.equal(simpleExpected);
done();
});
it("convert markdown file with code highlighting", function(done) {
- var data = assembleData.readMarkdown('./test/fixtures/pages/complex1.md', opts);
+ var data = markdown.read('./test/fixtures/pages/complex1.md', opts);
//console.log(data);
//expect(complexExpected).to.deep.equal(data);
done();
View
24 test/yfm_test.js
@@ -1,3 +1,4 @@
+/*global require:true */
/**
* Assemble <http://assemble.io>
* Created and maintained by Jon Schlinkert and Brian Woodward
@@ -6,13 +7,12 @@
* Licensed under the MIT License (MIT).
*/
-/*global require:true */
-var assembleData = require('../lib/data'),
- expect = require('chai').expect;
+var yfm = require('assemble-yaml');
+var expect = require('chai').expect;
-describe('Reading From Files', function() {
+describe('Reading From Files', function() {
var simpleExpected = {
context: {
@@ -31,25 +31,25 @@ describe('Reading From Files', function() {
it("yaml file starts with --- no content", function(done) {
- var data = assembleData.readYFM('./test/fixtures/pages/simple1.yml');
+ var data = yfm.extract('./test/fixtures/pages/simple1.yml');
expect(simpleExpected.context).to.deep.equal(data.context);
done();
});
it("yaml file starts and ends with --- no content", function(done) {
- var data = assembleData.readYFM('./test/fixtures/pages/simple2.yml');
+ var data = yfm.extract('./test/fixtures/pages/simple2.yml');
expect(simpleExpected.context).to.deep.equal(data.context);
done();
});
it("yaml file starts and ends with --- has content", function(done) {
- var data = assembleData.readYFM('./test/fixtures/pages/simple3.hbs');
+ var data = yfm.extract('./test/fixtures/pages/simple3.hbs');
expect(simpleExpected.context).to.deep.equal(data.context);
done();
});
it("hbs file with complex yaml data and content", function(done) {
- var data = assembleData.readYFM("./test/fixtures/pages/complex.hbs");
+ var data = yfm.extract("./test/fixtures/pages/complex.hbs");
expect(complexExpected).to.deep.equal(data);
done();
});
@@ -82,25 +82,25 @@ describe('Reading From Strings', function() {
};
it("yaml string starts with --- no content", function(done) {
- var data = assembleData.readYFM(simple1, opts);
+ var data = yfm.extract(simple1, opts);
expect(simpleExpected.context).to.deep.equal(data.context);
done();
});
it("yaml string starts and ends with --- no content", function(done) {
- var data = assembleData.readYFM(simple2, opts);
+ var data = yfm.extract(simple2, opts);
expect(simpleExpected.context).to.deep.equal(data.context);
done();
});
it("yaml string starts and ends with --- has content", function(done) {
- var data = assembleData.readYFM(simple3, opts);
+ var data = yfm.extract(simple3, opts);
expect(simpleExpected.context).to.deep.equal(data.context);
done();
});
it("hbs string with complex yaml data and content", function(done) {
- var data = assembleData.readYFM(complex, opts);
+ var data = yfm.extract(complex, opts);
expect(complexExpected).to.deep.equal(data);
done();
});

0 comments on commit f513369

Please sign in to comment.