diff --git a/build.js b/build.js index 06426a7..0c43a42 100644 --- a/build.js +++ b/build.js @@ -3,12 +3,13 @@ module.exports = { srcBase: 'src/', src: { - js: ['**/*.js', '!bin/skeleton/**', '!bin/client/**'] + // handleCopy should copy the negated files here but it is apparently not working + js: ['**/*.js', '!bin/skeleton/**/*.js'] }, distBase: 'dist/', config: { jscs: { configPath: '.jscsrc', esnext: true }, '6to5': { blacklist: ['generators'] }, - mocha: { bail: true, timeout: 5000 } + mocha: { bail: true, timeout: 20000 } } }; diff --git a/package.json b/package.json index 34db9cd..13da8e6 100755 --- a/package.json +++ b/package.json @@ -36,7 +36,6 @@ "permalinks": "^0.2.1", "rimraf": "^2.2.8", "stylus": "^0.45.1", - "traceur": "0.0.49", "underscore": "^1.6.0", "v8-argv": "^0.2.0" }, @@ -44,7 +43,7 @@ "chalk": "^0.5.1", "gulp": "^3.8.10", "gulp-batch": "^1.0.4", - "gulp-filter": "^1.0.2", + "gulp-filter": "^2.0.0", "gulp-jscs": "^1.3.1", "gulp-jshint": "^1.9.0", "gulp-load-plugins": "^0.8.0", diff --git a/src/bin/cli/program.js b/src/bin/cli/program.js index 9587cd2..dcd4bd5 100644 --- a/src/bin/cli/program.js +++ b/src/bin/cli/program.js @@ -28,37 +28,40 @@ program }); program - .command('build') + .command('build [path]') .description('Build your static website') - .action(() => { + // [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function + .action(function(path = '.') { let core = require('../core'); - core.init(); + core.init(path); }); program - .command('new_post ["title"]') + .command('new_post ["title"] [path]') .description('Create a new post') - .action((title) => { - newFile('post', title); + // [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function + .action(function(title, path = '.') { + newFile(path, 'post', title); }); program - .command('new_page ["title"]') + .command('new_page ["title"] [path]') .description('Create a new page') - .action((title) => { - newFile('page', title); + // [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function + .action(function(title, path = '.') { + newFile(path, 'page', title); }); program - .command('run [port]') + .command('run [port] [path]') .description('Run you static site locally. Port is optional') // [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function - .action(function(port = 9356) { + .action(function(port = 9356, path = '.') { let core = require('../core'), - build = core.init(); + build = core.init(path); if (build) { build.then(function() { - run(port); + run(path, port); }); } }); diff --git a/src/bin/cli/util.js b/src/bin/cli/util.js index f465f8b..ad0a245 100644 --- a/src/bin/cli/util.js +++ b/src/bin/cli/util.js @@ -117,9 +117,9 @@ function config(sitePath) { * @param {string} type - The new file's type. Can be either 'post' or 'page'. * @param {string} title - The new file's title. */ -function newFile(type, title) { +function newFile(sitePath, type, title) { var clc = cliColor(), - langs = getConfig().i18n.languages, + langs = getConfig(sitePath).i18n.languages, template = '\n' + '# ' + title, - path = type === 'post' ? postspath : pagespath, + filedir = path.join(sitePath, type === 'post' ? postspath : pagespath), filename = titleToFilename(title); langs.forEach((lang) => { - if (!fs.existsSync(path + lang)) { - fs.mkdirSync(path + lang); + let fileLangDir = path.join(filedir, lang); + if (!fs.existsSync(fileLangDir)) { + fs.mkdirSync(fileLangDir); } - fs.writeFileSync(path + lang + '/' + filename, template); + fs.writeFileSync(path.join(fileLangDir, filename), template); }); console.log(clc.info( @@ -147,9 +148,9 @@ function newFile(type, title) { )); } -function run(port) { +function run(sitePath, port) { let clc = cliColor(); - let file = new staticServer.Server(path.join(process.cwd(), 'public')); + let file = new staticServer.Server(path.join(sitePath, 'public')); console.log(clc.info('Harmonic site is running on http://localhost:' + port)); diff --git a/src/bin/client/traceur-runtime.js b/src/bin/client/traceur-runtime.js deleted file mode 100644 index 8f25a96..0000000 --- a/src/bin/client/traceur-runtime.js +++ /dev/null @@ -1,1330 +0,0 @@ -(function(global) { - 'use strict'; - if (global.$traceurRuntime) { - return; - } - var $Object = Object; - var $TypeError = TypeError; - var $create = $Object.create; - var $defineProperties = $Object.defineProperties; - var $defineProperty = $Object.defineProperty; - var $freeze = $Object.freeze; - var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor; - var $getOwnPropertyNames = $Object.getOwnPropertyNames; - var $getPrototypeOf = $Object.getPrototypeOf; - var $hasOwnProperty = $Object.prototype.hasOwnProperty; - var $toString = $Object.prototype.toString; - function nonEnum(value) { - return { - configurable: true, - enumerable: false, - value: value, - writable: true - }; - } - var types = { - void: function voidType() {}, - any: function any() {}, - string: function string() {}, - number: function number() {}, - boolean: function boolean() {} - }; - var method = nonEnum; - var counter = 0; - function newUniqueString() { - return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__'; - } - var symbolInternalProperty = newUniqueString(); - var symbolDescriptionProperty = newUniqueString(); - var symbolDataProperty = newUniqueString(); - var symbolValues = $create(null); - function isSymbol(symbol) { - return typeof symbol === 'object' && symbol instanceof SymbolValue; - } - function typeOf(v) { - if (isSymbol(v)) - return 'symbol'; - return typeof v; - } - function Symbol(description) { - var value = new SymbolValue(description); - if (!(this instanceof Symbol)) - return value; - throw new TypeError('Symbol cannot be new\'ed'); - } - $defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol)); - $defineProperty(Symbol.prototype, 'toString', method(function() { - var symbolValue = this[symbolDataProperty]; - if (!getOption('symbols')) - return symbolValue[symbolInternalProperty]; - if (!symbolValue) - throw TypeError('Conversion from symbol to string'); - var desc = symbolValue[symbolDescriptionProperty]; - if (desc === undefined) - desc = ''; - return 'Symbol(' + desc + ')'; - })); - $defineProperty(Symbol.prototype, 'valueOf', method(function() { - var symbolValue = this[symbolDataProperty]; - if (!symbolValue) - throw TypeError('Conversion from symbol to string'); - if (!getOption('symbols')) - return symbolValue[symbolInternalProperty]; - return symbolValue; - })); - function SymbolValue(description) { - var key = newUniqueString(); - $defineProperty(this, symbolDataProperty, { - value: this - }); - $defineProperty(this, symbolInternalProperty, { - value: key - }); - $defineProperty(this, symbolDescriptionProperty, { - value: description - }); - $freeze(this); - symbolValues[key] = this; - } - $defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol)); - $defineProperty(SymbolValue.prototype, 'toString', { - value: Symbol.prototype.toString, - enumerable: false - }); - $defineProperty(SymbolValue.prototype, 'valueOf', { - value: Symbol.prototype.valueOf, - enumerable: false - }); - $freeze(SymbolValue.prototype); - Symbol.iterator = Symbol(); - function toProperty(name) { - if (isSymbol(name)) - return name[symbolInternalProperty]; - return name; - } - function getOwnPropertyNames(object) { - var rv = []; - var names = $getOwnPropertyNames(object); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - if (!symbolValues[name]) - rv.push(name); - } - return rv; - } - function getOwnPropertyDescriptor(object, name) { - return $getOwnPropertyDescriptor(object, toProperty(name)); - } - function getOwnPropertySymbols(object) { - var rv = []; - var names = $getOwnPropertyNames(object); - for (var i = 0; i < names.length; i++) { - var symbol = symbolValues[names[i]]; - if (symbol) - rv.push(symbol); - } - return rv; - } - function hasOwnProperty(name) { - return $hasOwnProperty.call(this, toProperty(name)); - } - function getOption(name) { - return global.traceur && global.traceur.options[name]; - } - function setProperty(object, name, value) { - var sym, - desc; - if (isSymbol(name)) { - sym = name; - name = name[symbolInternalProperty]; - } - object[name] = value; - if (sym && (desc = $getOwnPropertyDescriptor(object, name))) - $defineProperty(object, name, { - enumerable: false - }); - return value; - } - function defineProperty(object, name, descriptor) { - if (isSymbol(name)) { - if (descriptor.enumerable) { - descriptor = $create(descriptor, { - enumerable: { - value: false - } - }); - } - name = name[symbolInternalProperty]; - } - $defineProperty(object, name, descriptor); - return object; - } - function polyfillObject(Object) { - $defineProperty(Object, 'defineProperty', { - value: defineProperty - }); - $defineProperty(Object, 'getOwnPropertyNames', { - value: getOwnPropertyNames - }); - $defineProperty(Object, 'getOwnPropertyDescriptor', { - value: getOwnPropertyDescriptor - }); - $defineProperty(Object.prototype, 'hasOwnProperty', { - value: hasOwnProperty - }); - Object.getOwnPropertySymbols = getOwnPropertySymbols; - function is(left, right) { - if (left === right) - return left !== 0 || 1 / left === 1 / right; - return left !== left && right !== right; - } - $defineProperty(Object, 'is', method(is)); - function assign(target, source) { - var props = $getOwnPropertyNames(source); - var p, - length = props.length; - for (p = 0; p < length; p++) { - target[props[p]] = source[props[p]]; - } - return target; - } - $defineProperty(Object, 'assign', method(assign)); - function mixin(target, source) { - var props = $getOwnPropertyNames(source); - var p, - descriptor, - length = props.length; - for (p = 0; p < length; p++) { - descriptor = $getOwnPropertyDescriptor(source, props[p]); - $defineProperty(target, props[p], descriptor); - } - return target; - } - $defineProperty(Object, 'mixin', method(mixin)); - } - function exportStar(object) { - for (var i = 1; i < arguments.length; i++) { - var names = $getOwnPropertyNames(arguments[i]); - for (var j = 0; j < names.length; j++) { - (function(mod, name) { - $defineProperty(object, name, { - get: function() { - return mod[name]; - }, - enumerable: true - }); - })(arguments[i], names[j]); - } - } - return object; - } - function toObject(value) { - if (value == null) - throw $TypeError(); - return $Object(value); - } - function spread() { - var rv = [], - k = 0; - for (var i = 0; i < arguments.length; i++) { - var valueToSpread = toObject(arguments[i]); - for (var j = 0; j < valueToSpread.length; j++) { - rv[k++] = valueToSpread[j]; - } - } - return rv; - } - function getPropertyDescriptor(object, name) { - while (object !== null) { - var result = $getOwnPropertyDescriptor(object, name); - if (result) - return result; - object = $getPrototypeOf(object); - } - return undefined; - } - function superDescriptor(homeObject, name) { - var proto = $getPrototypeOf(homeObject); - if (!proto) - throw $TypeError('super is null'); - return getPropertyDescriptor(proto, name); - } - function superCall(self, homeObject, name, args) { - var descriptor = superDescriptor(homeObject, name); - if (descriptor) { - if ('value' in descriptor) - return descriptor.value.apply(self, args); - if (descriptor.get) - return descriptor.get.call(self).apply(self, args); - } - throw $TypeError("super has no method '" + name + "'."); - } - function superGet(self, homeObject, name) { - var descriptor = superDescriptor(homeObject, name); - if (descriptor) { - if (descriptor.get) - return descriptor.get.call(self);else if ('value' in descriptor)return descriptor.value - ; - } - return undefined; - } - function superSet(self, homeObject, name, value) { - var descriptor = superDescriptor(homeObject, name); - if (descriptor && descriptor.set) { - descriptor.set.call(self, value); - return; - } - throw $TypeError("super has no setter '" + name + "'."); - } - function getDescriptors(object) { - var descriptors = {}, - name, - names = $getOwnPropertyNames(object); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - descriptors[name] = $getOwnPropertyDescriptor(object, name); - } - return descriptors; - } - function createClass(ctor, object, staticObject, superClass) { - $defineProperty(object, 'constructor', { - value: ctor, - configurable: true, - enumerable: false, - writable: true - }); - if (arguments.length > 3) { - if (typeof superClass === 'function') - ctor.__proto__ = superClass; - ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object)); - } else { - ctor.prototype = object; - } - $defineProperty(ctor, 'prototype', { - configurable: false, - writable: false - }); - return $defineProperties(ctor, getDescriptors(staticObject)); - } - function getProtoParent(superClass) { - if (typeof superClass === 'function') { - var prototype = superClass.prototype; - if ($Object(prototype) === prototype || prototype === null) - return superClass.prototype; - } - if (superClass === null) - return null; - throw new TypeError(); - } - function defaultSuperCall(self, homeObject, args) { - if ($getPrototypeOf(homeObject) !== null) - superCall(self, homeObject, 'constructor', args); - } - var ST_NEWBORN = 0; - var ST_EXECUTING = 1; - var ST_SUSPENDED = 2; - var ST_CLOSED = 3; - var END_STATE = -3; - function addIterator(object) { - return defineProperty(object, Symbol.iterator, nonEnum(function() { - return this; - })); - } - function GeneratorContext() { - this.state = 0; - this.GState = ST_NEWBORN; - this.storedException = undefined; - this.finallyFallThrough = undefined; - this.sent = undefined; - this.returnValue = undefined; - this.tryStack_ = []; - } - GeneratorContext.prototype = { - pushTry: function(catchState, finallyState) { - if (finallyState !== null) { - var finallyFallThrough = null; - for (var i = this.tryStack_.length - 1; i >= 0; i--) { - if (this.tryStack_[i].catch !== undefined) { - finallyFallThrough = this.tryStack_[i].catch; - break; - } - } - if (finallyFallThrough === null) - finallyFallThrough = -3; - this.tryStack_.push({ - finally: finallyState, - finallyFallThrough: finallyFallThrough - }); - } - if (catchState !== null) { - this.tryStack_.push({ - catch: catchState - }); - } - }, - popTry: function() { - this.tryStack_.pop(); - } - }; - function getNextOrThrow(ctx, moveNext, action) { - return function(x) { - switch (ctx.GState) { - case ST_EXECUTING: - throw new Error(("\"" + action + "\" on executing generator")); - case ST_CLOSED: - throw new Error(("\"" + action + "\" on closed generator")); - case ST_NEWBORN: - if (action === 'throw') { - ctx.GState = ST_CLOSED; - throw x; - } - if (x !== undefined) - throw $TypeError('Sent value to newborn generator'); - case ST_SUSPENDED: - ctx.GState = ST_EXECUTING; - ctx.action = action; - ctx.sent = x; - var value = moveNext(ctx); - var done = value === ctx; - if (done) - value = ctx.returnValue; - ctx.GState = done ? ST_CLOSED : ST_SUSPENDED; - return { - value: value, - done: done - }; - } - }; - } - function generatorWrap(innerFunction, self) { - var moveNext = getMoveNext(innerFunction, self); - var ctx = new GeneratorContext(); - return addIterator({ - next: getNextOrThrow(ctx, moveNext, 'next'), - throw: getNextOrThrow(ctx, moveNext, 'throw') - }); - } - function AsyncFunctionContext() { - GeneratorContext.call(this); - this.err = undefined; - var ctx = this; - ctx.result = new Promise(function(resolve, reject) { - ctx.resolve = resolve; - ctx.reject = reject; - }); - } - AsyncFunctionContext.prototype = Object.create(GeneratorContext.prototype); - function asyncWrap(innerFunction, self) { - var moveNext = getMoveNext(innerFunction, self); - var ctx = new AsyncFunctionContext(); - ctx.createCallback = function(newState) { - return function(value) { - ctx.state = newState; - ctx.value = value; - moveNext(ctx); - }; - }; - ctx.createErrback = function(newState) { - return function(err) { - ctx.state = newState; - ctx.err = err; - moveNext(ctx); - }; - }; - moveNext(ctx); - return ctx.result; - } - function getMoveNext(innerFunction, self) { - return function(ctx) { - while (true) { - try { - return innerFunction.call(self, ctx); - } catch (ex) { - ctx.storedException = ex; - var last = ctx.tryStack_[ctx.tryStack_.length - 1]; - if (!last) { - ctx.GState = ST_CLOSED; - ctx.state = END_STATE; - throw ex; - } - ctx.state = last.catch !== undefined ? last.catch : last.finally; - if (last.finallyFallThrough !== undefined) - ctx.finallyFallThrough = last.finallyFallThrough; - } - } - }; - } - function setupGlobals(global) { - global.Symbol = Symbol; - polyfillObject(global.Object); - } - setupGlobals(global); - global.$traceurRuntime = { - asyncWrap: asyncWrap, - createClass: createClass, - defaultSuperCall: defaultSuperCall, - exportStar: exportStar, - generatorWrap: generatorWrap, - setProperty: setProperty, - setupGlobals: setupGlobals, - spread: spread, - superCall: superCall, - superGet: superGet, - superSet: superSet, - toObject: toObject, - toProperty: toProperty, - type: types, - typeof: typeOf - }; -})(typeof global !== 'undefined' ? global : this); -(function() { - function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { - var out = []; - if (opt_scheme) { - out.push(opt_scheme, ':'); - } - if (opt_domain) { - out.push('//'); - if (opt_userInfo) { - out.push(opt_userInfo, '@'); - } - out.push(opt_domain); - if (opt_port) { - out.push(':', opt_port); - } - } - if (opt_path) { - out.push(opt_path); - } - if (opt_queryData) { - out.push('?', opt_queryData); - } - if (opt_fragment) { - out.push('#', opt_fragment); - } - return out.join(''); - } - ; - var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$'); - var ComponentIndex = { - SCHEME: 1, - USER_INFO: 2, - DOMAIN: 3, - PORT: 4, - PATH: 5, - QUERY_DATA: 6, - FRAGMENT: 7 - }; - function split(uri) { - return (uri.match(splitRe)); - } - function removeDotSegments(path) { - if (path === '/') - return '/'; - var leadingSlash = path[0] === '/' ? '/' : ''; - var trailingSlash = path.slice(-1) === '/' ? '/' : ''; - var segments = path.split('/'); - var out = []; - var up = 0; - for (var pos = 0; pos < segments.length; pos++) { - var segment = segments[pos]; - switch (segment) { - case '': - case '.': - break; - case '..': - if (out.length) - out.pop(); - else - up++; - break; - default: - out.push(segment); - } - } - if (!leadingSlash) { - while (up-- > 0) { - out.unshift('..'); - } - if (out.length === 0) - out.push('.'); - } - return leadingSlash + out.join('/') + trailingSlash; - } - function joinAndCanonicalizePath(parts) { - var path = parts[ComponentIndex.PATH] || ''; - path = removeDotSegments(path.replace(/\/\//.g, '/')); - parts[ComponentIndex.PATH] = path; - return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]); - } - function canonicalizeUrl(url) { - var parts = split(url); - return joinAndCanonicalizePath(parts); - } - function resolveUrl(base, url) { - var parts = split(url); - var baseParts = split(base); - if (parts[ComponentIndex.SCHEME]) { - return joinAndCanonicalizePath(parts); - } else { - parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME]; - } - for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) { - if (!parts[i]) { - parts[i] = baseParts[i]; - } - } - if (parts[ComponentIndex.PATH][0] == '/') { - return joinAndCanonicalizePath(parts); - } - var path = baseParts[ComponentIndex.PATH]; - var index = path.lastIndexOf('/'); - path = path.slice(0, index + 1) + parts[ComponentIndex.PATH]; - parts[ComponentIndex.PATH] = path; - return joinAndCanonicalizePath(parts); - } - function isAbsolute(name) { - if (!name) - return false; - if (name[0] === '/') - return true; - var parts = split(name); - if (parts[ComponentIndex.SCHEME]) - return true; - return false; - } - $traceurRuntime.canonicalizeUrl = canonicalizeUrl; - $traceurRuntime.isAbsolute = isAbsolute; - $traceurRuntime.removeDotSegments = removeDotSegments; - $traceurRuntime.resolveUrl = resolveUrl; -})(); -(function(global) { - 'use strict'; - var $__2 = $traceurRuntime, - canonicalizeUrl = $__2.canonicalizeUrl, - resolveUrl = $__2.resolveUrl, - isAbsolute = $__2.isAbsolute; - var moduleInstantiators = Object.create(null); - var baseURL; - if (global.location && global.location.href) - baseURL = resolveUrl(global.location.href, './'); - else - baseURL = ''; - var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) { - this.url = url; - this.value_ = uncoatedModule; - }; - ($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {}); - var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) { - $traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]); - this.func = func; - }; - var $UncoatedModuleInstantiator = UncoatedModuleInstantiator; - ($traceurRuntime.createClass)(UncoatedModuleInstantiator, { - getUncoatedModule: function() { - if (this.value_) - return this.value_; - return this.value_ = this.func.call(global); - } - }, {}, UncoatedModuleEntry); - function getUncoatedModuleInstantiator(name) { - if (!name) - return; - var url = ModuleStore.normalize(name); - return moduleInstantiators[url]; - } - ; - var moduleInstances = Object.create(null); - var liveModuleSentinel = {}; - function Module(uncoatedModule) { - var isLive = arguments[1]; - var coatedModule = Object.create(null); - Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) { - var getter, - value; - if (isLive === liveModuleSentinel) { - var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name); - if (descr.get) - getter = descr.get; - } - if (!getter) { - value = uncoatedModule[name]; - getter = function() { - return value; - }; - } - Object.defineProperty(coatedModule, name, { - get: getter, - enumerable: true - }); - })); - Object.preventExtensions(coatedModule); - return coatedModule; - } - var ModuleStore = { - normalize: function(name, refererName, refererAddress) { - if (typeof name !== "string") - throw new TypeError("module name must be a string, not " + typeof name); - if (isAbsolute(name)) - return canonicalizeUrl(name); - if (/[^\.]\/\.\.\//.test(name)) { - throw new Error('module name embeds /../: ' + name); - } - if (name[0] === '.' && refererName) - return resolveUrl(refererName, name); - return canonicalizeUrl(name); - }, - get: function(normalizedName) { - var m = getUncoatedModuleInstantiator(normalizedName); - if (!m) - return undefined; - var moduleInstance = moduleInstances[m.url]; - if (moduleInstance) - return moduleInstance; - moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel); - return moduleInstances[m.url] = moduleInstance; - }, - set: function(normalizedName, module) { - normalizedName = String(normalizedName); - moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() { - return module; - })); - moduleInstances[normalizedName] = module; - }, - get baseURL() { - return baseURL; - }, - set baseURL(v) { - baseURL = String(v); - }, - registerModule: function(name, func) { - var normalizedName = ModuleStore.normalize(name); - if (moduleInstantiators[normalizedName]) - throw new Error('duplicate module named ' + normalizedName); - moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func); - }, - bundleStore: Object.create(null), - register: function(name, deps, func) { - if (!deps || !deps.length) { - this.registerModule(name, func); - } else { - this.bundleStore[name] = { - deps: deps, - execute: func - }; - } - }, - getAnonymousModule: function(func) { - return new Module(func.call(global), liveModuleSentinel); - }, - getForTesting: function(name) { - var $__0 = this; - if (!this.testingPrefix_) { - Object.keys(moduleInstances).some((function(key) { - var m = /(traceur@[^\/]*\/)/.exec(key); - if (m) { - $__0.testingPrefix_ = m[1]; - return true; - } - })); - } - return this.get(this.testingPrefix_ + name); - } - }; - ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ - ModuleStore: ModuleStore - })); - var setupGlobals = $traceurRuntime.setupGlobals; - $traceurRuntime.setupGlobals = function(global) { - setupGlobals(global); - }; - $traceurRuntime.ModuleStore = ModuleStore; - global.System = { - register: ModuleStore.register.bind(ModuleStore), - get: ModuleStore.get, - set: ModuleStore.set, - normalize: ModuleStore.normalize - }; - $traceurRuntime.getModuleImpl = function(name) { - var instantiator = getUncoatedModuleInstantiator(name); - return instantiator && instantiator.getUncoatedModule(); - }; -})(typeof global !== 'undefined' ? global : this); -System.register("traceur-runtime@0.0.25/src/runtime/polyfills/utils", [], function() { - "use strict"; - var __moduleName = "traceur-runtime@0.0.25/src/runtime/polyfills/utils"; - var toObject = $traceurRuntime.toObject; - function toUint32(x) { - return x | 0; - } - return { - get toObject() { - return toObject; - }, - get toUint32() { - return toUint32; - } - }; -}); -System.register("traceur-runtime@0.0.25/src/runtime/polyfills/ArrayIterator", [], function() { - "use strict"; - var $__4; - var __moduleName = "traceur-runtime@0.0.25/src/runtime/polyfills/ArrayIterator"; - var $__5 = $traceurRuntime.getModuleImpl("traceur-runtime@0.0.25/src/runtime/polyfills/utils"), - toObject = $__5.toObject, - toUint32 = $__5.toUint32; - var ARRAY_ITERATOR_KIND_KEYS = 1; - var ARRAY_ITERATOR_KIND_VALUES = 2; - var ARRAY_ITERATOR_KIND_ENTRIES = 3; - var ArrayIterator = function ArrayIterator() {}; - ($traceurRuntime.createClass)(ArrayIterator, ($__4 = {}, Object.defineProperty($__4, "next", { - value: function() { - var iterator = toObject(this); - var array = iterator.iteratorObject_; - if (!array) { - throw new TypeError('Object is not an ArrayIterator'); - } - var index = iterator.arrayIteratorNextIndex_; - var itemKind = iterator.arrayIterationKind_; - var length = toUint32(array.length); - if (index >= length) { - iterator.arrayIteratorNextIndex_ = Infinity; - return createIteratorResultObject(undefined, true); - } - iterator.arrayIteratorNextIndex_ = index + 1; - if (itemKind == ARRAY_ITERATOR_KIND_VALUES) - return createIteratorResultObject(array[index], false); - if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES) - return createIteratorResultObject([index, array[index]], false); - return createIteratorResultObject(index, false); - }, - configurable: true, - enumerable: true, - writable: true - }), Object.defineProperty($__4, Symbol.iterator, { - value: function() { - return this; - }, - configurable: true, - enumerable: true, - writable: true - }), $__4), {}); - function createArrayIterator(array, kind) { - var object = toObject(array); - var iterator = new ArrayIterator; - iterator.iteratorObject_ = object; - iterator.arrayIteratorNextIndex_ = 0; - iterator.arrayIterationKind_ = kind; - return iterator; - } - function createIteratorResultObject(value, done) { - return { - value: value, - done: done - }; - } - function entries() { - return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES); - } - function keys() { - return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS); - } - function values() { - return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES); - } - return { - get entries() { - return entries; - }, - get keys() { - return keys; - }, - get values() { - return values; - } - }; -}); -System.register("traceur-runtime@0.0.25/node_modules/rsvp/lib/rsvp/asap", [], function() { - "use strict"; - var __moduleName = "traceur-runtime@0.0.25/node_modules/rsvp/lib/rsvp/asap"; - var $__default = function asap(callback, arg) { - var length = queue.push([callback, arg]); - if (length === 1) { - scheduleFlush(); - } - }; - var browserGlobal = (typeof window !== 'undefined') ? window : {}; - var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; - function useNextTick() { - return function() { - process.nextTick(flush); - }; - } - function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { - characterData: true - }); - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - function useSetTimeout() { - return function() { - setTimeout(flush, 1); - }; - } - var queue = []; - function flush() { - for (var i = 0; i < queue.length; i++) { - var tuple = queue[i]; - var callback = tuple[0], - arg = tuple[1]; - callback(arg); - } - queue = []; - } - var scheduleFlush; - if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { - scheduleFlush = useNextTick(); - } else if (BrowserMutationObserver) { - scheduleFlush = useMutationObserver(); - } else { - scheduleFlush = useSetTimeout(); - } - return { - get default() { - return $__default; - } - }; -}); -System.register("traceur-runtime@0.0.25/src/runtime/polyfills/Promise", [], function() { - "use strict"; - var __moduleName = "traceur-runtime@0.0.25/src/runtime/polyfills/Promise"; - var async = $traceurRuntime.getModuleImpl("traceur-runtime@0.0.25/node_modules/rsvp/lib/rsvp/asap").default; - function isPromise(x) { - return x && typeof x === 'object' && x.status_ !== undefined; - } - function chain(promise) { - var onResolve = arguments[1] !== (void0) ? arguments[1] : (function(x) { - return x; - }); - var onReject = arguments[2] !== (void0) ? arguments[2] : (function(e) { - throw e; - }); - var deferred = getDeferred(promise.constructor); - switch (promise.status_) { - case undefined: - throw TypeError; - case 'pending': - promise.onResolve_.push([deferred, onResolve]); - promise.onReject_.push([deferred, onReject]); - break; - case 'resolved': - promiseReact(deferred, onResolve, promise.value_); - break; - case 'rejected': - promiseReact(deferred, onReject, promise.value_); - break; - } - return deferred.promise; - } - function getDeferred(C) { - var result = {}; - result.promise = new C((function(resolve, reject) { - result.resolve = resolve; - result.reject = reject; - })); - return result; - } - var Promise = function Promise(resolver) { - var $__6 = this; - this.status_ = 'pending'; - this.onResolve_ = []; - this.onReject_ = []; - resolver((function(x) { - promiseResolve($__6, x); - }), (function(r) { - promiseReject($__6, r); - })); - }; - ($traceurRuntime.createClass)(Promise, { - catch: function(onReject) { - return this.then(undefined, onReject); - }, - then: function() { - var onResolve = arguments[0] !== (void0) ? arguments[0] : (function(x) { - return x; - }); - var onReject = arguments[1]; - var $__6 = this; - var constructor = this.constructor; - return chain(this, (function(x) { - x = promiseCoerce(constructor, x); - return x === $__6 ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x); - }), onReject); - } - }, { - resolve: function(x) { - return new this((function(resolve, reject) { - resolve(x); - })); - }, - reject: function(r) { - return new this((function(resolve, reject) { - reject(r); - })); - }, - cast: function(x) { - if (x instanceof this) - return x; - if (isPromise(x)) { - var result = getDeferred(this); - chain(x, result.resolve, result.reject); - return result.promise; - } - return this.resolve(x); - }, - all: function(values) { - var deferred = getDeferred(this); - var count = 0; - var resolutions = []; - try { - for (var i = 0; i < values.length; i++) { - ++count; - this.cast(values[i]).then(function(i, x) { - resolutions[i] = x; - if (--count === 0) - deferred.resolve(resolutions); - }.bind(undefined, i), (function(r) { - if (count > 0) - count = 0; - deferred.reject(r); - })); - } - if (count === 0) - deferred.resolve(resolutions); - } catch (e) { - deferred.reject(e); - } - return deferred.promise; - }, - race: function(values) { - var deferred = getDeferred(this); - try { - for (var i = 0; i < values.length; i++) { - this.cast(values[i]).then((function(x) { - deferred.resolve(x); - }), (function(r) { - deferred.reject(r); - })); - } - } catch (e) { - deferred.reject(e); - } - return deferred.promise; - } - }); - function promiseResolve(promise, x) { - promiseDone(promise, 'resolved', x, promise.onResolve_); - } - function promiseReject(promise, r) { - promiseDone(promise, 'rejected', r, promise.onReject_); - } - function promiseDone(promise, status, value, reactions) { - if (promise.status_ !== 'pending') - return; - for (var i = 0; i < reactions.length; i++) { - promiseReact(reactions[i][0], reactions[i][1], value); - } - promise.status_ = status; - promise.value_ = value; - promise.onResolve_ = promise.onReject_ = undefined; - } - function promiseReact(deferred, handler, x) { - async((function() { - try { - var y = handler(x); - if (y === deferred.promise) - throw new TypeError;else if (isPromise(y))chain(y, deferred.resolve, deferred.reject) - ; - else - deferred.resolve(y); - } catch (e) { - deferred.reject(e); - } - })); - } - var thenableSymbol = '@@thenable'; - function promiseCoerce(constructor, x) { - if (isPromise(x)) { - return x; - } else if (x && typeof x.then === 'function') { - var p = x[thenableSymbol]; - if (p) { - return p; - } else { - var deferred = getDeferred(constructor); - x[thenableSymbol] = deferred.promise; - try { - x.then(deferred.resolve, deferred.reject); - } catch (e) { - deferred.reject(e); - } - return deferred.promise; - } - } else { - return x; - } - } - return { - get Promise() { - return Promise; - } - }; -}); -System.register("traceur-runtime@0.0.25/src/runtime/polyfills/String", [], function() { - "use strict"; - var __moduleName = "traceur-runtime@0.0.25/src/runtime/polyfills/String"; - var $toString = Object.prototype.toString; - var $indexOf = String.prototype.indexOf; - var $lastIndexOf = String.prototype.lastIndexOf; - function startsWith(search) { - var string = String(this); - if (this == null || $toString.call(search) == '[object RegExp]') { - throw TypeError(); - } - var stringLength = string.length; - var searchString = String(search); - var searchLength = searchString.length; - var position = arguments.length > 1 ? arguments[1] : undefined; - var pos = position ? Number(position) : 0; - if (isNaN(pos)) { - pos = 0; - } - var start = Math.min(Math.max(pos, 0), stringLength); - return $indexOf.call(string, searchString, pos) == start; - } - function endsWith(search) { - var string = String(this); - if (this == null || $toString.call(search) == '[object RegExp]') { - throw TypeError(); - } - var stringLength = string.length; - var searchString = String(search); - var searchLength = searchString.length; - var pos = stringLength; - if (arguments.length > 1) { - var position = arguments[1]; - if (position !== undefined) { - pos = position ? Number(position) : 0; - if (isNaN(pos)) { - pos = 0; - } - } - } - var end = Math.min(Math.max(pos, 0), stringLength); - var start = end - searchLength; - if (start < 0) { - return false; - } - return $lastIndexOf.call(string, searchString, start) == start; - } - function contains(search) { - if (this == null) { - throw TypeError(); - } - var string = String(this); - var stringLength = string.length; - var searchString = String(search); - var searchLength = searchString.length; - var position = arguments.length > 1 ? arguments[1] : undefined; - var pos = position ? Number(position) : 0; - if (isNaN(pos)) { - pos = 0; - } - var start = Math.min(Math.max(pos, 0), stringLength); - return $indexOf.call(string, searchString, pos) != -1; - } - function repeat(count) { - if (this == null) { - throw TypeError(); - } - var string = String(this); - var n = count ? Number(count) : 0; - if (isNaN(n)) { - n = 0; - } - if (n < 0 || n == Infinity) { - throw RangeError(); - } - if (n == 0) { - return ''; - } - var result = ''; - while (n--) { - result += string; - } - return result; - } - function codePointAt(position) { - if (this == null) { - throw TypeError(); - } - var string = String(this); - var size = string.length; - var index = position ? Number(position) : 0; - if (isNaN(index)) { - index = 0; - } - if (index < 0 || index >= size) { - return undefined; - } - var first = string.charCodeAt(index); - var second; - if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) { - second = string.charCodeAt(index + 1); - if (second >= 0xDC00 && second <= 0xDFFF) { - return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - } - } - return first; - } - function raw(callsite) { - var raw = callsite.raw; - var len = raw.length >>> 0; - if (len === 0) - return ''; - var s = ''; - var i = 0; - while (true) { - s += raw[i]; - if (i + 1 === len) - return s; - s += arguments[++i]; - } - } - function fromCodePoint() { - var codeUnits = []; - var floor = Math.floor; - var highSurrogate; - var lowSurrogate; - var index = -1; - var length = arguments.length; - if (!length) { - return ''; - } - while (++index < length) { - var codePoint = Number(arguments[index]); - if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) { - throw RangeError('Invalid code point: ' + codePoint); - } - if (codePoint <= 0xFFFF) { - codeUnits.push(codePoint); - } else { - codePoint -= 0x10000; - highSurrogate = (codePoint >> 10) + 0xD800; - lowSurrogate = (codePoint % 0x400) + 0xDC00; - codeUnits.push(highSurrogate, lowSurrogate); - } - } - return String.fromCharCode.apply(null, codeUnits); - } - return { - get startsWith() { - return startsWith; - }, - get endsWith() { - return endsWith; - }, - get contains() { - return contains; - }, - get repeat() { - return repeat; - }, - get codePointAt() { - return codePointAt; - }, - get raw() { - return raw; - }, - get fromCodePoint() { - return fromCodePoint; - } - }; -}); -System.register("traceur-runtime@0.0.25/src/runtime/polyfills/polyfills", [], function() { - "use strict"; - var __moduleName = "traceur-runtime@0.0.25/src/runtime/polyfills/polyfills"; - var Promise = $traceurRuntime.getModuleImpl("traceur-runtime@0.0.25/src/runtime/polyfills/Promise").Promise; - var $__9 = $traceurRuntime.getModuleImpl("traceur-runtime@0.0.25/src/runtime/polyfills/String"), - codePointAt = $__9.codePointAt, - contains = $__9.contains, - endsWith = $__9.endsWith, - fromCodePoint = $__9.fromCodePoint, - repeat = $__9.repeat, - raw = $__9.raw, - startsWith = $__9.startsWith; - var $__9 = $traceurRuntime.getModuleImpl("traceur-runtime@0.0.25/src/runtime/polyfills/ArrayIterator"), - entries = $__9.entries, - keys = $__9.keys, - values = $__9.values; - function maybeDefineMethod(object, name, value) { - if (!(name in object)) { - Object.defineProperty(object, name, { - value: value, - configurable: true, - enumerable: false, - writable: true - }); - } - } - function maybeAddFunctions(object, functions) { - for (var i = 0; i < functions.length; i += 2) { - var name = functions[i]; - var value = functions[i + 1]; - maybeDefineMethod(object, name, value); - } - } - function polyfillPromise(global) { - if (!global.Promise) - global.Promise = Promise; - } - function polyfillString(String) { - maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]); - maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]); - } - function polyfillArray(Array, Symbol) { - maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values]); - if (Symbol && Symbol.iterator) { - Object.defineProperty(Array.prototype, Symbol.iterator, { - value: values, - configurable: true, - enumerable: false, - writable: true - }); - } - } - function polyfill(global) { - polyfillPromise(global); - polyfillString(global.String); - polyfillArray(global.Array, global.Symbol); - } - polyfill(this); - var setupGlobals = $traceurRuntime.setupGlobals; - $traceurRuntime.setupGlobals = function(global) { - setupGlobals(global); - polyfill(global); - }; - return {}; -}); -System.register("traceur-runtime@0.0.25/src/runtime/polyfill-import", [], function() { - "use strict"; - var __moduleName = "traceur-runtime@0.0.25/src/runtime/polyfill-import"; - var $__11 = $traceurRuntime.getModuleImpl("traceur-runtime@0.0.25/src/runtime/polyfills/polyfills"); - return {}; -}); -System.get("traceur-runtime@0.0.25/src/runtime/polyfill-import" + ''); diff --git a/src/bin/core.js b/src/bin/core.js index 75ffb8a..7e7c988 100644 --- a/src/bin/core.js +++ b/src/bin/core.js @@ -5,21 +5,21 @@ let parser = new Parser(); export { init }; -function init() { - return isHarmonicProject() && +function init(sitePath) { + return isHarmonicProject(sitePath) && parser.start() - .then(parser.clean) - .then(parser.getConfig) - .then(parser.createPublicFolder) - .then(parser.compileCSS) - .then(parser.generatePages) - .then(parser.getFiles) - .then(parser.generatePosts) - .then(parser.generateRSS) - .then(parser.compileES6) - .then(parser.generateIndex) - .then(parser.generateTagsPages) - .then(parser.copyResources) + .then(parser.clean.bind(parser, sitePath)) + .then(parser.getConfig.bind(parser, sitePath)) + .then(parser.createPublicFolder.bind(parser, sitePath)) + .then(parser.compileCSS.bind(parser, sitePath)) + .then(parser.generatePages.bind(parser, sitePath)) + .then(parser.getFiles.bind(parser, sitePath)) + .then(parser.generatePosts.bind(parser, sitePath)) + .then(parser.generateRSS.bind(parser, sitePath)) + .then(parser.compileES6.bind(parser, sitePath)) + .then(parser.generateIndex.bind(parser, sitePath)) + .then(parser.generateTagsPages.bind(parser, sitePath)) + .then(parser.copyResources.bind(parser, sitePath)) .catch((e) => { console.log(e); console.log(e.stack); diff --git a/src/bin/helpers.js b/src/bin/helpers.js index ab1d57d..de57fab 100644 --- a/src/bin/helpers.js +++ b/src/bin/helpers.js @@ -1,4 +1,5 @@ let fs = require('fs'); +let path = require('path'); export { cliColor, isHarmonicProject, getConfig, titleToFilename }; @@ -14,11 +15,11 @@ function cliColor() { } // Check if harmonic.json file exists -function isHarmonicProject() { +function isHarmonicProject(sitePath = '.') { var clc = cliColor(); try { - getConfig(); + getConfig(sitePath); return true; } catch (e) { console.log( @@ -31,8 +32,8 @@ function isHarmonicProject() { } } -function getConfig() { - return JSON.parse(fs.readFileSync('./harmonic.json').toString()); +function getConfig(sitePath = '.') { + return JSON.parse(fs.readFileSync(path.join(sitePath, 'harmonic.json')).toString()); } function titleToFilename(title) { diff --git a/src/bin/parser.js b/src/bin/parser.js index 0623494..bc9c01e 100644 --- a/src/bin/parser.js +++ b/src/bin/parser.js @@ -1,12 +1,10 @@ /*jshint unused:false*/ -import { rootdir } from './config'; +import { rootdir, postspath as postsPath, pagespath as pagesPath } from './config'; import { cliColor, isHarmonicProject, getConfig, titleToFilename } from './helpers'; var Helper, Parser, fs = require('fs'), - postsPath = './src/posts/', path = require('path'), - pagesPath = './src/pages/', _ = require('underscore'), nunjucks = require('nunjucks'), ncp = require('ncp').ncp, @@ -15,22 +13,23 @@ var Helper, Parser, stylus = require('stylus'), less = require('less'), MkMeta = require('marked-metadata'), - traceur = require('traceur'), + to5 = require('gulp-6to5/node_modules/6to5'), clc = cliColor(); // Temporary // jscs:disable requireCamelCaseOrUpperCaseIdentifiers Helper = { - getPagesFiles: function() { + getPagesFiles: function(sitePath) { var config = GLOBAL.config, files = {}; config.i18n.languages.forEach(function(lang) { - if (!fs.existsSync(pagesPath + lang)) { - fs.mkdirSync(pagesPath + lang); + let langPath = path.join(sitePath, pagesPath, lang); + if (!fs.existsSync(langPath)) { + fs.mkdirSync(langPath); } else { - files[lang] = fs.readdirSync(pagesPath + lang); + files[lang] = fs.readdirSync(langPath); } }); @@ -52,7 +51,7 @@ Helper = { return newPosts; }, - parsePages: function(files) { + parsePages: function(sitePath, files) { var langs = Object.keys(files), curTemplate = GLOBAL.config.template, nunjucksEnv = GLOBAL.nunjucksEnv, @@ -66,11 +65,13 @@ Helper = { langs.forEach(function(lang) { files[lang].forEach(function(file) { var metadata, pagePermalink, _page, pageContent, pageHTMLFile, - page = fs.readFileSync(pagesPath + lang + '/' + file).toString(), - tplSrc = './src/templates/' + curTemplate + '/page.html', - pageTpl = fs.readFileSync(tplSrc), + pagePath = path.join(sitePath, pagesPath, lang, file), + page = fs.readFileSync(pagePath).toString(), + pageTpl = fs.readFileSync( + path.join(sitePath, 'src/templates', curTemplate, 'page.html') + ), pageTplNJ = nunjucks.compile(pageTpl.toString(), nunjucksEnv), - md = new MkMeta(pagesPath + lang + '/' + file), + md = new MkMeta(pagePath), pageSrc = '', filename = path.extname(file) === '.md' ? path.basename(file, '.md') : @@ -102,16 +103,16 @@ Helper = { // jscs:enable disallowSpaceBeforeBinaryOperators metadata.content = pageHTMLFile; - metadata.file = postsPath + file; + metadata.file = postsPath + file; // TODO check whether this needs sitePath metadata.filename = filename; metadata.link = '/' + filename + '.html'; metadata.date = new Date(metadata.date); - pageSrc = './public/' + pagePermalink + '/' + 'index.html'; + pageSrc = path.join(sitePath, 'public', pagePermalink, 'index.html'); GLOBAL.pages.push(metadata); writePromises.push(new Promise(function(resolve, reject) { - mkdirp('./public/' + pagePermalink, function(err) { + mkdirp(path.join(sitePath, 'public', pagePermalink), function(err) { if (err) { reject(err); return; @@ -154,20 +155,21 @@ Parser = function() { return Promise.resolve(); }; - this.clean = function() { + this.clean = function(sitePath) { console.log(clc.warn('Cleaning up...')); var rimraf = require('rimraf'); - rimraf.sync('./public'); + rimraf.sync(path.join(sitePath, 'public')); }; - this.createPublicFolder = function() { - if (!fs.existsSync('./public')) { - fs.mkdirSync('public'); + this.createPublicFolder = function(sitePath) { + let publicDirPath = path.join(sitePath, 'public'); + if (!fs.existsSync(publicDirPath)) { + fs.mkdirSync(publicDirPath); console.log(clc.info('Successfully generated public folder')); } }; - this.compileCSS = function() { + this.compileCSS = function(sitePath) { var compiler, currentCSSCompiler = GLOBAL.config.preprocessor || 'stylus'; @@ -176,7 +178,7 @@ Parser = function() { // Less less: function() { return new Promise(function(resolve, reject) { - var curTemplate = './src/templates/' + GLOBAL.config.template, + var curTemplate = path.join(sitePath, 'src/templates', GLOBAL.config.template), lessDir = curTemplate + '/resources/_less', cssDir = curTemplate + '/resources/css', verifyDirectory = function(filepath) { @@ -202,7 +204,7 @@ Parser = function() { parser; options.outputfile = options.filename.split('.less')[0] + '.css'; - options.outputDir = path.resolve(process.cwd(), options.outputDir) + '/'; + options.outputDir = path.resolve(sitePath, options.outputDir) + '/'; verifyDirectory(options.outputDir); parser = new less.Parser(options); @@ -233,7 +235,7 @@ Parser = function() { // Stylus stylus: function() { return new Promise(function(resolve, reject) { - var curTemplate = './src/templates/' + GLOBAL.config.template, + var curTemplate = path.join(sitePath, 'src/templates', GLOBAL.config.template), stylDir = curTemplate + '/resources/_stylus', cssDir = curTemplate + '/resources/css', code = fs.readFileSync(stylDir + '/index.styl', 'utf8'); @@ -258,11 +260,8 @@ Parser = function() { compiler[currentCSSCompiler](); }; - this.compileES6 = function(postsMetadata) { - var result = '', - traceurRuntime = - fs.readFileSync(rootdir + '/bin/client/traceur-runtime.js') - .toString(), + this.compileES6 = function(sitePath, postsMetadata) { + var result, config = GLOBAL.config, pages = GLOBAL.pages, harmonicClient = @@ -277,25 +276,19 @@ Parser = function() { .replace(/\/\*\{\{config\}\}\*\//, JSON.stringify(config)); // jscs:enable disallowSpaceBeforeBinaryOperators - result = traceur.compile(harmonicClient, { - filename: 'harmonic-client.js' - }); - - if (result.error) { - throw result.error; - } - - fs.writeFileSync('./public/harmonic.js', '//traceur runtime\n' + traceurRuntime + - '\n//harmonic code\n' + result.js); + result = to5.transform(harmonicClient); + fs.writeFileSync(path.join(sitePath, 'public/harmonic.js'), result.code); return postsMetadata; }; - this.generateTagsPages = function(postsMetadata) { + this.generateTagsPages = function(sitePath, postsMetadata) { var postsByTag = {}, curTemplate = GLOBAL.config.template, nunjucksEnv = GLOBAL.nunjucksEnv, - tagTemplate = fs.readFileSync('./src/templates/' + curTemplate + '/index.html'), + tagTemplate = fs.readFileSync( + path.join(sitePath, 'src/templates', curTemplate, 'index.html') + ), tagTemplateNJ = nunjucks.compile(tagTemplate.toString(), nunjucksEnv), tagPath = null, lang, i, tags, y, tag, tagContent, @@ -330,13 +323,13 @@ Parser = function() { // If is the default language, generate in the root path if (config.i18n.default === lang) { - tagPath = './public/categories/' + i; + tagPath = path.join(sitePath, 'public/categories', i); } else { - tagPath = './public/categories/' + lang + '/' + i; + tagPath = path.join(sitePath, 'public/categories', lang, i); } mkdirp.sync(tagPath); - fs.writeFileSync(tagPath + '/index.html', tagContent); + fs.writeFileSync(path.join(tagPath, 'index.html'), tagContent); console.log( clc.info('Successfully generated tag[' + i + '] archive html file') ); @@ -344,12 +337,14 @@ Parser = function() { } }; - this.generateIndex = function(postsMetadata) { + this.generateIndex = function(sitePath, postsMetadata) { var lang, _posts = null, curTemplate = GLOBAL.config.template, nunjucksEnv = GLOBAL.nunjucksEnv, - indexTemplate = fs.readFileSync('./src/templates/' + curTemplate + '/index.html'), + indexTemplate = fs.readFileSync( + path.join(sitePath, 'src/templates', curTemplate, 'index.html') + ), indexTemplateNJ = nunjucks.compile(indexTemplate.toString(), nunjucksEnv), indexContent = '', indexPath = null, @@ -367,22 +362,22 @@ Parser = function() { }); if (config.i18n.default === lang) { - indexPath = './public/'; + indexPath = path.join(sitePath, 'public'); } else { - indexPath = './public/' + lang; + indexPath = path.join(sitePath, 'public', lang); } mkdirp.sync(indexPath); - fs.writeFileSync(indexPath + '/index.html', indexContent); + fs.writeFileSync(path.join(indexPath, 'index.html'), indexContent); console.log(clc.info(lang + '/index file successfully created')); } return postsMetadata; }; - this.copyResources = function() { + this.copyResources = function(sitePath) { var imagesP, resourcesP; imagesP = new Promise(function(resolve, reject) { - ncp('./src/img', './public/img', function(err) { + ncp(path.join(sitePath, 'src/img'), path.join(sitePath, 'public/img'), function(err) { if (err) { reject(err); return; @@ -392,8 +387,8 @@ Parser = function() { }); resourcesP = new Promise(function(resolve, reject) { - var curTemplate = './src/templates/' + GLOBAL.config.template; - ncp(curTemplate + '/resources', './public', function(err) { + var curTemplate = path.join(sitePath, 'src/templates', GLOBAL.config.template); + ncp(path.join(curTemplate, 'resources'), path.join(sitePath, 'public'), function(err) { if (err) { reject(err); return; @@ -408,19 +403,21 @@ Parser = function() { }); }; - this.generatePages = function() { + this.generatePages = function(sitePath) { return Promise.resolve() - .then(Helper.getPagesFiles) - .then(Helper.parsePages); + .then(Helper.getPagesFiles.bind(Helper, sitePath)) + .then(Helper.parsePages.bind(Helper, sitePath)); }; - this.generatePosts = function(files) { + this.generatePosts = function(sitePath, files) { var langs = Object.keys(files), config = GLOBAL.config, posts = {}, currentDate = new Date(), curTemplate = config.template, - postsTemplate = fs.readFileSync('./src/templates/' + curTemplate + '/post.html'), + postsTemplate = fs.readFileSync( + path.join(sitePath, 'src/templates', curTemplate, 'post.html') + ), nunjucksEnv = GLOBAL.nunjucksEnv, postsTemplateNJ = nunjucks.compile(postsTemplate.toString(), nunjucksEnv), tokens = [ @@ -433,7 +430,7 @@ Parser = function() { files[lang].forEach(function(file) { var metadata, post, postCropped, filename, checkDate, postPath, categories, _post, postHTMLFile, postDate, month, year, options, - md = new MkMeta(postsPath + lang + '/' + file); + md = new MkMeta(path.join(sitePath, postsPath, lang, file)); md.defineTokens(tokens[0], tokens[1]); metadata = Helper.normalizeMetaData(md.metadata()); @@ -519,14 +516,14 @@ Parser = function() { } writePromises.push(new Promise(function(resolve, reject) { - mkdirp('./public/' + postPath, function(err) { + mkdirp(path.join(sitePath, 'public', postPath), function(err) { if (err) { reject(err); return; } // write post html file - fs.writeFile('./public/' + postPath + '/index.html', postHTMLFile, - function(err) { + fs.writeFile(path.join(sitePath, 'public', postPath, 'index.html'), + postHTMLFile, function(err) { if (err) { reject(err); return; @@ -553,38 +550,36 @@ Parser = function() { }); }; - this.getFiles = function() { + this.getFiles = function(sitePath) { var config = GLOBAL.config, - langs = config.i18n.languages, - langsLen = langs.length, - i = 0, files = {}; - for (i; i < langsLen; i += 1) { - files[langs[i]] = fs.readdirSync(postsPath + langs[i]); - } + config.i18n.languages.forEach(function(lang) { + files[lang] = fs.readdirSync(path.join(sitePath, postsPath, lang)); + }); return files; }; - this.getConfig = function() { - var config = getConfig(); + this.getConfig = function(sitePath) { + var config = getConfig(sitePath); + // TODO replace try with fs.exists check so that invalid JSON does not fail silently try { - _.extend(config, JSON.parse( - fs.readFileSync('./src/templates/' + config.template + '/harmonic.json').toString() - )); + _.extend(config, JSON.parse(fs.readFileSync( + path.join(sitePath, 'src/templates', config.template, 'harmonic.json') + ).toString())); } catch (e) {} GLOBAL.config = config; GLOBAL.nunjucksEnv = new nunjucks.Environment( - new nunjucks.FileSystemLoader('./src/templates/' + config.template) + new nunjucks.FileSystemLoader(path.join(sitePath, 'src/templates', config.template)) ); return config; }; - this.generateRSS = function(postsMetadata) { + this.generateRSS = function(sitePath, postsMetadata) { var _posts = null, nunjucksEnv = GLOBAL.nunjucksEnv, rssTemplate = fs.readFileSync(__dirname + '/resources/rss.xml'), @@ -607,10 +602,10 @@ Parser = function() { } if (config.i18n.default === lang) { - rssPath = './public/'; + rssPath = path.join(sitePath, 'public'); rssLink = GLOBAL.config.domain + '/rss.xml'; } else { - rssPath = './public/' + lang; + rssPath = path.join(sitePath, 'public', lang); rssLink = GLOBAL.config.domain + '/' + lang + '/rss.xml'; } diff --git a/src/test/main.js b/src/test/main.js index 2ced91c..9411650 100644 --- a/src/test/main.js +++ b/src/test/main.js @@ -18,12 +18,9 @@ require('should'); before(function() { rimraf.sync(testDir); mkdirp.sync(testDir); - process.chdir(testDir); }); after(function() { - // need to chdir out of testDir before removing it (at least in Windows) - process.chdir(__dirname); rimraf.sync(testDir); }); @@ -44,7 +41,7 @@ describe('CLI', function() { }); it('should init a new Harmonic site', function(done) { - var harmonic = spawn('node', [harmonicBin, 'init']); + var harmonic = spawn('node', [harmonicBin, 'init', testDir]); harmonic.stdin.setEncoding('utf8'); harmonic.stdout.setEncoding('utf8'); @@ -57,13 +54,13 @@ describe('CLI', function() { }); harmonic.on('close', function() { - helpers.isHarmonicProject().should.be.true; + helpers.isHarmonicProject(testDir).should.be.true; done(); }); }); it('should build the Harmonic site', function(done) { - var harmonic = spawn('node', [harmonicBin, 'build']); + var harmonic = spawn('node', [harmonicBin, 'build', testDir]); harmonic.stdin.setEncoding('utf8'); harmonic.stdout.setEncoding('utf8'); @@ -75,39 +72,40 @@ describe('CLI', function() { it('should create and build a new post', function(done) { var localconfig = require('../bin/config.js'), - config = helpers.getConfig(), + config = helpers.getConfig(testDir), langs = config.i18n.languages, title = 'new_post test', fileName = helpers.titleToFilename(title), - harmonic = spawn('node', [harmonicBin, 'new_post', title]); + harmonic = spawn('node', [harmonicBin, 'new_post', title, testDir]); harmonic.stdin.setEncoding('utf8'); harmonic.stdout.setEncoding('utf8'); new Promise(function(resolve) { harmonic.on('close', function() { langs.forEach(function(lang) { - fs.readFileSync(path.join(localconfig.postspath, lang, fileName)).toString() - .should.containEql(title); + fs.readFileSync( + path.join(testDir, localconfig.postspath, lang, fileName) + ).toString().should.containEql(title); }); resolve(); }); }).then(function() { - var harmonicBuild = spawn('node', [harmonicBin, 'build']); + var harmonicBuild = spawn('node', [harmonicBin, 'build', testDir]); harmonicBuild.stdin.setEncoding('utf8'); harmonicBuild.stdout.setEncoding('utf8'); return new Promise(function(resolve) { harmonicBuild.on('close', function() { var date = new Date(), - year = date.getFullYear(), + year = String(date.getFullYear()), month = ('0' + (date.getMonth() + 1)).slice(-2), // [BUG] https://github.com/jscs-dev/node-jscs/issues/735 // jscs:disable disallowSpaceBeforeBinaryOperators slug = fileName.replace(/\.md$/, ''); // jscs:enable disallowSpaceBeforeBinaryOperators langs.forEach(function(lang) { - var langSegment = lang === config.i18n.default ? '' : lang + '/'; - fs.readFileSync('public/' + langSegment + year + '/' + month + '/' + - slug + '/index.html').toString().should.containEql(title); + var langSegment = lang === config.i18n.default ? '.' : lang; + fs.readFileSync(path.join(testDir, 'public', langSegment, year, month, + slug, 'index.html')).toString().should.containEql(title); }); resolve(); }); @@ -122,13 +120,11 @@ describe('CLI', function() { describe('helpers', function() { it('.isHarmonicProject() should return whether the CWD is a Harmonic site', function() { - process.chdir(__dirname); disableStdout(); - var isHarmonicProject = helpers.isHarmonicProject(); + var isHarmonicProject = helpers.isHarmonicProject(__dirname); enableStdout(); isHarmonicProject.should.be.false; - process.chdir(testDir); - helpers.isHarmonicProject().should.be.true; + helpers.isHarmonicProject(testDir).should.be.true; }); it('.titleToFilename() should transform a post/page title into a filename', function() { @@ -139,13 +135,15 @@ describe('helpers', function() { describe('parser', function() { it('.getConfig() should merge the template\'s config into the main config', function() { - var config = helpers.getConfig(), - templateConfigPath = 'src/templates/' + config.template + '/harmonic.json', + var config = helpers.getConfig(testDir), + templateConfigPath = path.join( + testDir, 'src/templates', config.template, 'harmonic.json' + ), templateConfig = { customData: 'test' }, mergedConfig; fs.writeFileSync(templateConfigPath, JSON.stringify(templateConfig)); - mergedConfig = parser.getConfig(); + mergedConfig = parser.getConfig(testDir); mergedConfig.should.containDeep(templateConfig); mergedConfig.should.eql(_.extend({}, config, templateConfig)); });