diff options
Diffstat (limited to 'lib')
-rw-r--r-- | lib/configuration.js | 32 | ||||
-rw-r--r-- | lib/conrefs_loader.js | 3 | ||||
-rw-r--r-- | lib/generator.js | 4 | ||||
-rw-r--r-- | lib/generators/ebook.js | 20 | ||||
-rw-r--r-- | lib/generators/json.js | 4 | ||||
-rw-r--r-- | lib/generators/website.js | 35 | ||||
-rw-r--r-- | lib/plugin.js | 8 | ||||
-rw-r--r-- | lib/pluginslist.js | 34 | ||||
-rw-r--r-- | lib/utils/batch.js | 8 | ||||
-rw-r--r-- | lib/utils/fs.js | 32 | ||||
-rw-r--r-- | lib/utils/git.js | 8 | ||||
-rw-r--r-- | lib/utils/i18n.js | 22 | ||||
-rw-r--r-- | lib/utils/images.js | 12 | ||||
-rw-r--r-- | lib/utils/links.js | 8 | ||||
-rw-r--r-- | lib/utils/logger.js | 18 | ||||
-rw-r--r-- | lib/utils/navigation.js | 6 | ||||
-rw-r--r-- | lib/utils/page.js | 75 | ||||
-rw-r--r-- | lib/utils/path.js | 23 | ||||
-rw-r--r-- | lib/utils/progress.js | 2 | ||||
-rw-r--r-- | lib/utils/server.js | 32 | ||||
-rw-r--r-- | lib/utils/string.js | 4 | ||||
-rw-r--r-- | lib/utils/watch.js | 12 |
22 files changed, 192 insertions, 210 deletions
diff --git a/lib/configuration.js b/lib/configuration.js index acff1c1..34d6351 100644 --- a/lib/configuration.js +++ b/lib/configuration.js @@ -1,14 +1,13 @@ var _ = require("lodash"); var Q = require("q"); var path = require("path"); -var semver = require('semver'); +var semver = require("semver"); -var pkg = require('../package.json'); -var fs = require("./utils/fs"); +var pkg = require("../package.json"); var i18n = require("./utils/i18n"); // Default plugins added to each books -var defaultsPlugins = ['highlight']; +var defaultsPlugins = ["highlight"]; // Normalize a list of plugins to use function normalizePluginsList(plugins) { @@ -24,9 +23,9 @@ function normalizePluginsList(plugins) { var parts = plugin.split("@"); return { - 'name': parts[0], - 'version': parts[1] // optional - } + "name": parts[0], + "version": parts[1] // optional + }; }); // List plugins to remove @@ -42,7 +41,7 @@ function normalizePluginsList(plugins) { // Merge with defaults plugins = _.chain(plugins) .concat(_.map(defaultsPlugins, function(plugin) { - return { 'name': plugin } + return { "name": plugin }; })) .uniq() .value(); @@ -55,11 +54,6 @@ function normalizePluginsList(plugins) { return plugins; } -// Normalize a list of plugin name to use -function normalizePluginsNames(plugins) { - return _.pluck(normalizePluginsList(plugins), "name"); -}; - var Configuration = function(book, options) { var that = this; @@ -96,7 +90,7 @@ Configuration.prototype.load = function() { return Q() .then(function() { - var configPath, config; + var configPath, _config; try { configPath = require.resolve( @@ -109,7 +103,7 @@ Configuration.prototype.load = function() { _config = require(configPath); that.options = _.merge( that.options, - _.omit(_config, 'configFile', 'defaultsPlugins', 'generator', 'extension') + _.omit(_config, "configFile", "defaultsPlugins", "generator", "extension") ); } catch(err) { @@ -121,7 +115,7 @@ Configuration.prototype.load = function() { if (!semver.satisfies(pkg.version, that.options.gitbook)) { throw "GitBook version doesn't satisfy version required by the book: "+that.options.gitbook; } - if (that.options.gitbook != '*' && !semver.satisfies(semver.inc(pkg.version, 'patch'), that.options.gitbook)) { + if (that.options.gitbook != "*" && !semver.satisfies(semver.inc(pkg.version, "patch"), that.options.gitbook)) { that.book.log.warn.ln("gitbook version specified in your book.json might be too strict for future patches, \""+(_.first(pkg.version.split("."))+".x.x")+"\" is more adequate"); } @@ -163,7 +157,7 @@ Configuration.prototype.get = function(key, def) { // Default configuration Configuration.DEFAULT = { - // Options that can't be extend + // Options that can"t be extend "configFile": "book", "generator": "website", "extension": null, @@ -213,9 +207,9 @@ Configuration.DEFAULT = { "variables": {}, // Set another theme with your own layout - // It's recommended to use plugins or add more options for default theme, though + // It"s recommended to use plugins or add more options for default theme, though // See https://github.com/GitbookIO/gitbook/issues/209 - "theme": path.resolve(__dirname, '../theme'), + "theme": path.resolve(__dirname, "../theme"), // Links in template (null: default, false: remove, string: new value) "links": { diff --git a/lib/conrefs_loader.js b/lib/conrefs_loader.js index 72dce8a..a6c2049 100644 --- a/lib/conrefs_loader.js +++ b/lib/conrefs_loader.js @@ -1,4 +1,3 @@ -var Q = require("q"); var path = require("path"); var nunjucks = require("nunjucks"); @@ -29,7 +28,7 @@ var BookLoader = nunjucks.Loader.extend({ return { src: source.toString(), path: filepath - } + }; }); }) .nodeify(callback); diff --git a/lib/generator.js b/lib/generator.js index 407afa5..fca5b3c 100644 --- a/lib/generator.js +++ b/lib/generator.js @@ -3,8 +3,6 @@ var path = require("path"); var Q = require("q"); var fs = require("./utils/fs"); -var Plugin = require("./plugin"); - var BaseGenerator = function(book) { this.book = book; @@ -65,7 +63,7 @@ BaseGenerator.prototype.copyCover = function() { fs.copy(path.join(that.book.parentRoot(), "cover_small.jpg"), path.join(that.options.output, "cover_small.jpg")) ]); }) - .fail(function(err) { + .fail(function() { return Q(); }); }; diff --git a/lib/generators/ebook.js b/lib/generators/ebook.js index cdb667c..e6a33d3 100644 --- a/lib/generators/ebook.js +++ b/lib/generators/ebook.js @@ -2,7 +2,7 @@ var util = require("util"); var path = require("path"); var Q = require("q"); var _ = require("lodash"); -var exec = require('child_process').exec; +var exec = require("child_process").exec; var fs = require("../utils/fs"); var stringUtils = require("../utils/string"); @@ -26,9 +26,9 @@ var Generator = function(book, format) { util.inherits(Generator, BaseGenerator); Generator.prototype.prepareTemplates = function() { - this.templates["page"] = this.book.plugins.template("ebook:page") || path.resolve(this.options.theme, 'templates/ebook/page.html'); - this.templates["summary"] = this.book.plugins.template("ebook:summary") || path.resolve(this.options.theme, 'templates/ebook/summary.html'); - this.templates["glossary"] = this.book.plugins.template("ebook:glossary") || path.resolve(this.options.theme, 'templates/ebook/glossary.html'); + this.templates.page = this.book.plugins.template("ebook:page") || path.resolve(this.options.theme, "templates/ebook/page.html"); + this.templates.summary = this.book.plugins.template("ebook:summary") || path.resolve(this.options.theme, "templates/ebook/summary.html"); + this.templates.glossary = this.book.plugins.template("ebook:glossary") || path.resolve(this.options.theme, "templates/ebook/glossary.html"); return Q(); }; @@ -38,7 +38,7 @@ Generator.prototype.writeSummary = function() { var that = this; that.book.log.info.ln("write SUMMARY.html"); - return this._writeTemplate(this.templates["summary"], {}, path.join(this.options.output, "SUMMARY.html")); + return this._writeTemplate(this.templates.summary, {}, path.join(this.options.output, "SUMMARY.html")); }; Generator.prototype.finish = function() { @@ -52,12 +52,12 @@ Generator.prototype.finish = function() { .then(function() { if (!that.ebookFormat) return Q(); - var d = Q.defer(); - if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) { that.options.cover = path.join(that.options.output, "cover.jpg"); } + var d = Q.defer(); + var _options = { "--cover": that.options.cover, "--title": that.options.title, @@ -108,7 +108,7 @@ Generator.prototype.finish = function() { that.book.log.info("start conversion to", that.ebookFormat, "...."); - var child = exec(command, function (error, stdout, stderr) { + var child = exec(command, function (error, stdout) { if (error) { that.book.log.info.fail(); @@ -124,11 +124,11 @@ Generator.prototype.finish = function() { d.resolve(); }); - child.stdout.on('data', function (data) { + child.stdout.on("data", function (data) { that.book.log.debug(data); }); - child.stderr.on('data', function (data) { + child.stderr.on("data", function (data) { that.book.log.debug(data); }); diff --git a/lib/generators/json.js b/lib/generators/json.js index 6c9439d..446ef0d 100644 --- a/lib/generators/json.js +++ b/lib/generators/json.js @@ -13,7 +13,7 @@ var Generator = function() { util.inherits(Generator, BaseGenerator); // Ignore some methods -Generator.prototype.transferFile = function(input) { }; +Generator.prototype.transferFile = function() { }; // Convert an input file Generator.prototype.convertFile = function(input) { @@ -44,7 +44,7 @@ Generator.prototype.finish = function() { // Write README.json Generator.prototype.writeReadme = function() { var that = this; - var mainlang, langs; + var mainLang, langs, readme; return Q() .then(function() { diff --git a/lib/generators/website.js b/lib/generators/website.js index 675092f..4bde473 100644 --- a/lib/generators/website.js +++ b/lib/generators/website.js @@ -10,7 +10,6 @@ var FilterExtension = require("nunjucks-filter")(nunjucks); var fs = require("../utils/fs"); var BaseGenerator = require("../generator"); var links = require("../utils/links"); -var pageUtil = require("../utils/page"); var i18n = require("../utils/i18n"); var pkg = require("../../package.json"); @@ -64,9 +63,9 @@ Generator.prototype.prepareStyles = function() { // Prepare templates Generator.prototype.prepareTemplates = function() { - this.templates["page"] = this.book.plugins.template("site:page") || path.resolve(this.options.theme, 'templates/website/page.html'); - this.templates["langs"] = this.book.plugins.template("site:langs") || path.resolve(this.options.theme, 'templates/website/langs.html'); - this.templates["glossary"] = this.book.plugins.template("site:glossary") || path.resolve(this.options.theme, 'templates/website/glossary.html'); + this.templates.page = this.book.plugins.template("site:page") || path.resolve(this.options.theme, "templates/website/page.html"); + this.templates.langs = this.book.plugins.template("site:langs") || path.resolve(this.options.theme, "templates/website/langs.html"); + this.templates.glossary = this.book.plugins.template("site:glossary") || path.resolve(this.options.theme, "templates/website/glossary.html"); return Q(); }; @@ -98,13 +97,13 @@ Generator.prototype.prepareTemplateEngine = function() { // Add filter that.env.addFilter("contentLink", that.book.contentLink.bind(that.book)); - that.env.addFilter('lvl', function(lvl) { + that.env.addFilter("lvl", function(lvl) { return lvl.split(".").length; }); // Add extension - that.env.addExtension('AutoEscapeExtension', new AutoEscapeExtension(that.env)); - that.env.addExtension('FilterExtension', new FilterExtension(that.env)); + that.env.addExtension("AutoEscapeExtension", new AutoEscapeExtension(that.env)); + that.env.addExtension("FilterExtension", new FilterExtension(that.env)); }); }; @@ -114,7 +113,7 @@ Generator.prototype.finish = function() { .then(this.copyCover) .then(this.writeGlossary) .then(this.writeSearchIndex) - .then(this.writeLangsIndex) + .then(this.writeLangsIndex); }; // Convert an input file @@ -135,11 +134,11 @@ Generator.prototype.convertFile = function(input) { var output = path.join(that.options.output, relativeOutput); var basePath = path.relative(path.dirname(output), that.options.output) || "."; - if (process.platform === 'win32') basePath = basePath.replace(/\\/g, '/'); + if (process.platform === "win32") basePath = basePath.replace(/\\/g, "/"); that.book.log.debug.ln("write parsed file", page.path, "to", relativeOutput); - return that._writeTemplate(that.templates["page"], { + return that._writeTemplate(that.templates.page, { progress: page.progress, _input: page.path, @@ -153,27 +152,23 @@ Generator.prototype.convertFile = function(input) { // Write the index for langs Generator.prototype.writeLangsIndex = function() { - var that = this; if (!this.book.langs.length) return Q(); - return this._writeTemplate(this.templates["langs"], { + + return this._writeTemplate(this.templates.langs, { langs: this.book.langs }, path.join(this.options.output, "index.html")); }; // Write glossary Generator.prototype.writeGlossary = function() { - var that = this; - // No glossary - if (this.book.glossary.length == 0) return Q(); + if (this.book.glossary.length === 0) return Q(); - return this._writeTemplate(this.templates["glossary"], {}, path.join(this.options.output, "GLOSSARY.html")); + return this._writeTemplate(this.templates.glossary, {}, path.join(this.options.output, "GLOSSARY.html")); }; // Write the search index Generator.prototype.writeSearchIndex = function() { - var that = this; - return fs.writeFile( path.join(this.options.output, "search_index.json"), JSON.stringify(this.book.searchIndex) @@ -207,7 +202,7 @@ Generator.prototype._writeTemplate = function(tpl, options, output, interpolate) interpolate = interpolate || _.identity; return Q() - .then(function(sections) { + .then(function() { return that.env.render( tpl, _.extend({ @@ -239,7 +234,7 @@ Generator.prototype._writeTemplate = function(tpl, options, output, interpolate) basePath: ".", staticBase: path.join(".", "gitbook"), - '__': that.book.i18n.bind(that.book) + "__": that.book.i18n.bind(that.book) }, options) ); }) diff --git a/lib/plugin.js b/lib/plugin.js index 364aec8..5e1c427 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -4,7 +4,7 @@ var semver = require("semver"); var path = require("path"); var url = require("url"); var fs = require("./utils/fs"); -var resolve = require('resolve'); +var resolve = require("resolve"); var pkg = require("../package.json"); @@ -34,7 +34,7 @@ var Plugin = function(book, name) { Plugin.RESOURCES = ["js", "css"]; Plugin.HOOKS = [ "init", "finish", "finish:before", "page", "page:before" -] +]; // Load from a name Plugin.prototype.load = function(name, baseDir) { @@ -77,7 +77,7 @@ Plugin.prototype._getResources = function(base) { var book = this.infos[base]; // Compatibility with version 1.x.x - if (base == "website") book = book || this.infos["book"]; + if (base == "website") book = book || this.infos.book; // Nothing specified, fallback to default if (!book) { @@ -168,7 +168,7 @@ Plugin.prototype.copyAssets = function(out, base) { var that = this; return this.getResources(base) - .get('assets') + .get("assets") .then(function(assets) { // Assets are undefined if(!assets) return false; diff --git a/lib/pluginslist.js b/lib/pluginslist.js index 37dbd41..ec9f4c8 100644 --- a/lib/pluginslist.js +++ b/lib/pluginslist.js @@ -1,14 +1,14 @@ var _ = require("lodash"); var Q = require("q"); -var npmi = require('npmi'); -var npm = require('npm'); -var semver = require('semver'); +var npmi = require("npmi"); +var npm = require("npm"); +var semver = require("semver"); var Plugin = require("./plugin"); var pkg = require("../package.json"); var initNPM = _.memoize(function() { - return Q.nfcall(npm.load, { silent: true, loglevel: 'silent' }); + return Q.nfcall(npm.load, { silent: true, loglevel: "silent" }); }); @@ -53,7 +53,7 @@ PluginsList.prototype.count = function() { }; // Add and load a plugin -PluginsList.prototype.load = function(plugin, options) { +PluginsList.prototype.load = function(plugin) { var that = this; if (_.isArray(plugin)) { @@ -103,7 +103,7 @@ PluginsList.prototype.load = function(plugin, options) { namespace.html[tag] = namespace.html[tag] || []; namespace.html[tag].push(value); }); - }) + }); }); }, Q()); }; @@ -146,7 +146,7 @@ PluginsList.prototype.resources = function(namespace) { // Install plugins from a book PluginsList.prototype.install = function() { var that = this; - var defaultsPlugins = _.pluck(that.book.options.defaultsPlugins) + var defaultsPlugins = _.pluck(that.book.options.defaultsPlugins); // Remove defaults (no need to install) var plugins = _.filter(that.book.options.plugins, function(plugin) { @@ -176,8 +176,8 @@ PluginsList.prototype.install = function() { .map(function(v) { return { version: v[0], - gitbook: (v[1].engines || {})["gitbook"] - } + gitbook: (v[1].engines || {}).gitbook + }; }) .filter(function(v) { return v.gitbook && semver.satisfies(pkg.version, v.gitbook); @@ -199,13 +199,13 @@ PluginsList.prototype.install = function() { that.book.log.info.ln("install plugin", plugin.name, "from npm ("+fullname+") with version", version); return Q.nfcall(npmi, { - 'name': fullname, - 'version': version, - 'path': that.book.root, - 'npmLoad': { - 'loglevel': 'silent', - 'loaded': true, - 'prefix': that.book.root + "name": fullname, + "version": version, + "path": that.book.root, + "npmLoad": { + "loglevel": "silent", + "loaded": true, + "prefix": that.book.root } }); }) @@ -216,6 +216,4 @@ PluginsList.prototype.install = function() { }, Q()); }; - - module.exports = PluginsList; diff --git a/lib/utils/batch.js b/lib/utils/batch.js index bd3b80f..9069766 100644 --- a/lib/utils/batch.js +++ b/lib/utils/batch.js @@ -3,12 +3,12 @@ var _ = require("lodash"); // Execute a method for all element function execEach(items, options) { - if (_.size(items) == 0) return Q(); + if (_.size(items) === 0) return Q(); var concurrents = 0, d = Q.defer(), pending = []; options = _.defaults(options || {}, { max: 100, - fn: function(item) {} + fn: function() {} }); @@ -29,7 +29,7 @@ function execEach(items, options) { // Next pending var next = pending.shift(); - if (concurrents == 0 && !next) { + if (concurrents === 0 && !next) { d.resolve(); } else if (next) { startItem.apply(null, next); @@ -38,7 +38,7 @@ function execEach(items, options) { .fail(function(err) { pending = []; d.reject(err); - }) + }); } _.each(items, startItem); diff --git a/lib/utils/fs.js b/lib/utils/fs.js index 176a215..0a9d846 100644 --- a/lib/utils/fs.js +++ b/lib/utils/fs.js @@ -9,10 +9,10 @@ var Ignore = require("fstream-ignore"); var fsUtils = { tmp: { file: function(opt) { - return Q.nfcall(tmp.file.bind(tmp), opt).get(0) + return Q.nfcall(tmp.file.bind(tmp), opt).get(0); }, dir: function() { - return Q.nfcall(tmp.dir.bind(tmp)).get(0) + return Q.nfcall(tmp.dir.bind(tmp)).get(0); } }, list: listFiles, @@ -34,14 +34,14 @@ var fsUtils = { readFileSync: fs.readFileSync.bind(fs), clean: cleanFolder, getUniqueFilename: getUniqueFilename, -} +}; // Write a file function writeFile(filename, data, options) { var d = Q.defer(); try { - fs.writeFileSync(filename, data, options) + fs.writeFileSync(filename, data, options); } catch(err) { d.reject(err); } @@ -57,14 +57,14 @@ function writeStream(filename, st) { var wstream = fs.createWriteStream(filename); - wstream.on('finish', function () { + wstream.on("finish", function () { d.resolve(); }); - wstream.on('error', function (err) { + wstream.on("error", function (err) { d.reject(err); }); - st.on('error', function(err) { + st.on("error", function(err) { d.reject(err); }); @@ -115,20 +115,20 @@ function listFiles(root, options) { }); // Add extra rules to ignore common folders - ig.addIgnoreRules(options.ignoreRules, '__custom_stuff'); + ig.addIgnoreRules(options.ignoreRules, "__custom_stuff"); // Push each file to our list - ig.on('child', function (c) { + ig.on("child", function (c) { files.push( - c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? '/' : '') + c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? "/" : "") ); }); - ig.on('end', function() { + ig.on("end", function() { // Normalize paths on Windows - if(process.platform === 'win32') { + if(process.platform === "win32") { return d.resolve(files.map(function(file) { - return file.replace(/\\/g, '/'); + return file.replace(/\\/g, "/"); })); } @@ -136,7 +136,7 @@ function listFiles(root, options) { return d.resolve(files); }); - ig.on('error', d.reject); + ig.on("error", d.reject); return d.promise; } @@ -150,8 +150,8 @@ function cleanFolder(root) { ignoreFiles: [], ignoreRules: [ // Skip Git and SVN stuff - '.git/', - '.svn/' + ".git/", + ".svn/" ] }) .then(function(files) { diff --git a/lib/utils/git.js b/lib/utils/git.js index 6eb9681..e93c8f2 100644 --- a/lib/utils/git.js +++ b/lib/utils/git.js @@ -1,7 +1,5 @@ var Q = require("q"); var _ = require("lodash"); -var url = require("url"); -var tmp = require("tmp"); var path = require("path"); var crc = require("crc"); var exec = Q.denodeify(require("child_process").exec); @@ -102,11 +100,11 @@ function resolveFileFromGit(giturl) { // Resolve relative path return path.resolve(repo, giturl.filepath); }); -}; +} // Return root of git repo from a filepath function resolveGitRoot(filepath) { - var relativeToGit, repoId + var relativeToGit, repoId; // No git repo cloned, or file is not in a git repository if (!GIT_TMP || !pathUtil.isInRoot(GIT_TMP, filepath)) return null; @@ -118,7 +116,7 @@ function resolveGitRoot(filepath) { // Return an absolute file return path.resolve(GIT_TMP, repoId); -}; +} module.exports = { diff --git a/lib/utils/i18n.js b/lib/utils/i18n.js index c3253b7..f6001f9 100644 --- a/lib/utils/i18n.js +++ b/lib/utils/i18n.js @@ -4,7 +4,7 @@ var fs = require("fs"); var i18n = require("i18n"); -var I18N_PATH = path.resolve(__dirname, "../../theme/i18n/") +var I18N_PATH = path.resolve(__dirname, "../../theme/i18n/"); var DEFAULT_LANGUAGE = "en"; var LOCALES = _.map(fs.readdirSync(I18N_PATH), function(lang) { return path.basename(lang, ".json"); @@ -17,7 +17,7 @@ i18n.configure({ updateFiles: false }); -var compareLocales = function(lang, locale) { +function compareLocales(lang, locale) { var langMain = _.first(lang.split("-")); var langSecond = _.last(lang.split("-")); @@ -28,7 +28,7 @@ var compareLocales = function(lang, locale) { if (localeMain == langMain) return 50; if (localeSecond == langSecond) return 20; return 0; -}; +} var normalizeLanguage = _.memoize(function(lang) { var language = _.chain(LOCALES) @@ -37,7 +37,7 @@ var normalizeLanguage = _.memoize(function(lang) { return { locale: locale, score: compareLocales(lang, locale) - } + }; }) .filter(function(lang) { return lang.score > 0; @@ -49,25 +49,25 @@ var normalizeLanguage = _.memoize(function(lang) { return language || lang; }); -var translate = function(locale, phrase) { +function translate(locale, phrase) { var args = Array.prototype.slice.call(arguments, 2); return i18n.__.apply({}, [{ locale: locale, phrase: phrase }].concat(args)); -}; +} -var getCatalog = function(locale) { +function getCatalog(locale) { locale = normalizeLanguage(locale); return i18n.getCatalog(locale); -}; +} -var getLocales = function() { +function getLocales() { return LOCALES; -}; +} -var hasLocale = function(locale) { +function hasLocale(locale) { return _.contains(LOCALES, locale); } diff --git a/lib/utils/images.js b/lib/utils/images.js index 3bc650a..a82b0a1 100644 --- a/lib/utils/images.js +++ b/lib/utils/images.js @@ -1,9 +1,7 @@ var _ = require("lodash"); var Q = require("q"); var fs = require("./fs"); -var spawn = require('spawn-cmd').spawn; - -var links = require("./links"); +var spawn = require("spawn-cmd").spawn; // Convert a svg file var convertSVG = function(source, dest, options) { @@ -14,16 +12,16 @@ var convertSVG = function(source, dest, options) { }); - //var command = shellescape(['svgexport', source, dest]); - var child = spawn('svgexport', [source, dest]); + //var command = shellescape(["svgexport", source, dest]); + var child = spawn("svgexport", [source, dest]); child.on("error", function(error) { - if (error.code == "ENOENT") error = new Error("Need to install 'svgexport' using 'npm install svgexport -g'"); + if (error.code == "ENOENT") error = new Error("Need to install \"svgexport\" using \"npm install svgexport -g\""); return d.reject(error); }); child.on("close", function(code) { - if (code == 0 && fs.existsSync(dest)) { + if (code === 0 && fs.existsSync(dest)) { d.resolve(); } else { d.reject(new Error("Error converting "+source+" into "+dest)); diff --git a/lib/utils/links.js b/lib/utils/links.js index 61cdc9a..589e0d7 100644 --- a/lib/utils/links.js +++ b/lib/utils/links.js @@ -1,5 +1,5 @@ -var url = require('url'); -var path = require('path'); +var url = require("url"); +var path = require("path"); // Is the link an external link var isExternal = function(href) { @@ -33,7 +33,7 @@ var isAnchor = function(href) { // Normalize a path to be a link var normalizeLink = function(s) { - return s.replace(/\\/g, '/'); + return s.replace(/\\/g, "/"); }; // Relative to absolute path @@ -43,7 +43,7 @@ var normalizeLink = function(s) { var toAbsolute = function(_href, dir, outdir) { if (isExternal(_href)) return _href; - // Path '_href' inside the base folder + // Path "_href" inside the base folder var hrefInRoot = path.normalize(path.join(dir, _href)); if (_href[0] == "/") hrefInRoot = path.normalize(_href.slice(1)); diff --git a/lib/utils/logger.js b/lib/utils/logger.js index 5c1da8c..db3d90e 100644 --- a/lib/utils/logger.js +++ b/lib/utils/logger.js @@ -1,6 +1,6 @@ -var _ = require('lodash'); -var util = require('util'); -var color = require('bash-color'); +var _ = require("lodash"); +var util = require("util"); +var color = require("bash-color"); var LEVELS = { DEBUG: 0, @@ -19,7 +19,7 @@ var COLORS = { module.exports = function(_write, logLevel) { var logger = {}; - var lastChar = '\n'; + var lastChar = "\n"; if (_.isString(logLevel)) logLevel = LEVELS[logLevel.toUpperCase()]; // Write a simple message @@ -47,14 +47,14 @@ module.exports = function(_write, logLevel) { var args = Array.prototype.slice.apply(arguments, [1]); var msg = logger.format.apply(logger, args); - if (lastChar == '\n') { + if (lastChar == "\n") { msg = COLORS[levelKey](levelKey.toLowerCase()+":")+" "+msg; } return logger.write(msg); }; logger.logLn = function() { - if (lastChar != '\n') logger.write("\n"); + if (lastChar != "\n") logger.write("\n"); var args = Array.prototype.slice.apply(arguments); args.push("\n"); @@ -66,7 +66,7 @@ module.exports = function(_write, logLevel) { var args = Array.prototype.slice.apply(arguments, [1]); var msg = logger.format.apply(logger, args); if (arguments.length > 1) { - logger.logLn(level, color.green('>> ') + msg.trim().replace(/\n/g, color.green('\n>> '))); + logger.logLn(level, color.green(">> ") + msg.trim().replace(/\n/g, color.green("\n>> "))); } else { logger.log(level, color.green("OK"), "\n"); } @@ -77,7 +77,7 @@ module.exports = function(_write, logLevel) { return logger.log(level, color.red("ERROR")+"\n"); }; - _.each(_.omit(LEVELS, 'DISABLED'), function(level, levelKey) { + _.each(_.omit(LEVELS, "DISABLED"), function(level, levelKey) { levelKey = levelKey.toLowerCase(); logger[levelKey] = _.partial(logger.log, level); @@ -93,7 +93,7 @@ module.exports = function(_write, logLevel) { logger[levelKey].fail(); throw err; }); - } + }; }); return logger; diff --git a/lib/utils/navigation.js b/lib/utils/navigation.js index d825c2c..d07eb35 100644 --- a/lib/utils/navigation.js +++ b/lib/utils/navigation.js @@ -1,9 +1,9 @@ -var _ = require('lodash'); +var _ = require("lodash"); // Cleans up an article/chapter object -// remove 'articles' attributes +// remove "articles" attributes function clean(obj) { - return obj && _.omit(obj, ['articles']); + return obj && _.omit(obj, ["articles"]); } function flattenChapters(chapters) { diff --git a/lib/utils/page.js b/lib/utils/page.js index 5b4eca8..a17c6a2 100644 --- a/lib/utils/page.js +++ b/lib/utils/page.js @@ -1,18 +1,18 @@ -var Q = require('q'); -var _ = require('lodash'); -var url = require('url'); -var path = require('path'); -var cheerio = require('cheerio'); -var domSerializer = require('dom-serializer'); -var request = require('request'); +var Q = require("q"); +var _ = require("lodash"); +var url = require("url"); +var path = require("path"); +var cheerio = require("cheerio"); +var domSerializer = require("dom-serializer"); +var request = require("request"); var crc = require("crc"); -var links = require('./links'); -var imgUtils = require('./images'); -var fs = require('./fs'); -var batch = require('./batch'); +var links = require("./links"); +var imgUtils = require("./images"); +var fs = require("./fs"); +var batch = require("./batch"); -var parsableExtensions = require('gitbook-parsers').extensions; +var parsableExtensions = require("gitbook-parsers").extensions; // Render a cheerio dom as html var renderDom = function($, dom, options) { @@ -40,7 +40,8 @@ function replaceText($, el, search, replace, text_only ) { if ( node ) { // Loop over all childNodes. - do { + while (node) { + // Only process text nodes. if ( node.nodeType === 3 ) { @@ -58,7 +59,7 @@ function replaceText($, el, search, replace, text_only ) { // robust way. $(node).before( new_val ); - // Don't remove the node yet, or the loop will lose its place. + // Don"t remove the node yet, or the loop will lose its place. remove.push( node ); } else { // The new value contains no HTML, so it can be set in this @@ -68,17 +69,18 @@ function replaceText($, el, search, replace, text_only ) { } } - } while ( node = node.nextSibling ); + node = node.nextSibling; + } } // Time to remove those elements! - remove.length && $(remove).remove(); + if (remove.length) $(remove).remove(); }); -}; +} function pregQuote( str ) { - return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1"); -}; + return (str+"").replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1"); +} // Adapt an html snippet to be relative to a base folder @@ -107,15 +109,16 @@ function normalizeHtml(src, options) { // Generate filename dest = "/"+fs.getUniqueFilename(outputRoot, dest); - svgContent[dest] = '<?xml version="1.0" encoding="UTF-8"?>'+content; + svgContent[dest] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+content; $(this).replaceWith($("<img>").attr("src", dest)); }); } // Find images to normalize $("img").each(function() { - var origin = undefined; + var origin; var src = $(this).attr("src"); + if (!src) return; var isExternal = links.isExternal(src); @@ -150,7 +153,7 @@ function normalizeHtml(src, options) { dest = links.join(path.dirname(srcAbs), path.basename(srcAbs, ext)+".png"); dest = dest[0] == "/"? dest.slice(1) : dest; - // Get a name that doesn't exists + // Get a name that doesn"t exists dest = fs.getUniqueFilename(outputRoot, dest); options.book.log.debug.ln("detect invalid image (will be converted to png):", srcAbs); @@ -205,9 +208,9 @@ function normalizeHtml(src, options) { // If md/adoc/rst files is not in summary // or for ebook, signal all files that are outside the summary - else if (_.contains(parsableExtensions, path.extname(absolutePath)) - || _.contains(['epub', 'pdf', 'mobi'], options.book.options.generator)) { - options.book.log.warn.ln("page", options.input, "contains an hyperlink to resource outside spine '"+href+"'"); + else if (_.contains(parsableExtensions, path.extname(absolutePath)) || + _.contains(["epub", "pdf", "mobi"], options.book.options.generator)) { + options.book.log.warn.ln("page", options.input, "contains an hyperlink to resource outside spine \""+href+"\""); } // Transform as absolute @@ -241,7 +244,7 @@ function normalizeHtml(src, options) { .value(); var source = $(this).text(); - var html = options.book.template.applyBlock('code', { + var html = options.book.template.applyBlock("code", { body: source, kwargs: { language: lang @@ -255,8 +258,9 @@ function normalizeHtml(src, options) { var glossary = _.sortBy(options.glossary, function(term) { return -term.name.length; }); + _.each(glossary, function(term) { - var r = new RegExp( "\\b(" + pregQuote(term.name.toLowerCase()) + ")\\b" , 'gi' ); + var r = new RegExp( "\\b(" + pregQuote(term.name.toLowerCase()) + ")\\b" , "gi" ); var includedInFiles = false; $("*").each(function() { @@ -270,7 +274,7 @@ function normalizeHtml(src, options) { term.files = term.files || []; term.files.push(options.navigation[options.input]); } - return "<a href='"+links.toAbsolute("/GLOSSARY.html", options.base, options.output)+"#"+term.id+"' class='glossary-term' title='"+_.escape(term.description)+"'>"+match+"</a>"; + return "<a href=\""+links.toAbsolute("/GLOSSARY.html", options.base, options.output) + "#" + term.id+"\" class=\"glossary-term\" title=\""+_.escape(term.description)+"\">"+match+"</a>"; }); }); }); @@ -279,7 +283,7 @@ function normalizeHtml(src, options) { html: renderDom($), images: toConvert }; -}; +} // Convert svg images to png function convertImages(images, options) { @@ -304,7 +308,7 @@ function convertImages(images, options) { .fail(function(err) { if (!_.isError(err)) err = new Error(err); - err.message = 'Fail downloading '+image.origin+': '+err.message; + err.message = "Fail downloading "+image.origin+": "+err.message; throw err; }); }) @@ -327,8 +331,7 @@ function convertImages(images, options) { .then(function() { options.book.log.debug.ok(images.length+" images converted with success"); }); -}; - +} // Adapt page content to be relative to a base folder function normalizePage(sections, options) { @@ -361,7 +364,7 @@ function normalizePage(sections, options) { sections = _.map(sections, function(section) { if (section.type != "normal") return section; - var out = normalizeHtml(section.content, options);; + var out = normalizeHtml(section.content, options); toConvert = toConvert.concat(out.images); section.content = out.html; @@ -370,11 +373,11 @@ function normalizePage(sections, options) { return Q() .then(function() { - toConvert = _.uniq(toConvert, 'source'); + toConvert = _.uniq(toConvert, "source"); return convertImages(toConvert, options); }) .thenResolve(sections); -}; +} // Extract text from sections function extractText(sections) { @@ -388,7 +391,7 @@ function extractText(sections) { return prev; }, ""); -}; +} module.exports = { normalize: normalizePage, diff --git a/lib/utils/path.js b/lib/utils/path.js index d5b98f7..5285896 100644 --- a/lib/utils/path.js +++ b/lib/utils/path.js @@ -1,5 +1,5 @@ var _ = require("lodash"); -var path = require('path'); +var path = require("path"); // Return true if file path is inside a folder function isInRoot(root, filename) { @@ -10,28 +10,29 @@ function isInRoot(root, filename) { // Resolve paths in a specific folder // Throw error if file is outside this folder function resolveInRoot(root) { - var input = _.chain(arguments) + var input, result, err; + + input = _.chain(arguments) .toArray() .slice(1) - .reduce(function(current, p, i) { - // Handle path relative to book root ('/README.md') - if (p[0] == '/' || p[0] == '\\') return p.slice(1); + .reduce(function(current, p) { + // Handle path relative to book root ("/README.md") + if (p[0] == "/" || p[0] == "\\") return p.slice(1); return current? path.join(current, p) : path.normalize(p); - }, '') + }, "") .value(); - var result = path.resolve(root, input); + result = path.resolve(root, input); if (!isInRoot(root, result)) { - err = new Error("EACCESS: '" + result + "' not in '" + root + "'"); + err = new Error("EACCESS: \"" + result + "\" not in \"" + root + "\""); err.code = "EACCESS"; throw err; } - return result -}; - + return result; +} module.exports = { isInRoot: isInRoot, diff --git a/lib/utils/progress.js b/lib/utils/progress.js index 9669d86..78821ad 100644 --- a/lib/utils/progress.js +++ b/lib/utils/progress.js @@ -1,7 +1,7 @@ var _ = require("lodash"); // Returns from a navigation and a current file, a snapshot of current detailed state -var calculProgress = function(navigation, current) { +function calculProgress(navigation, current) { var n = _.size(navigation); var percent = 0, prevPercent = 0, currentChapter = null; var done = true; diff --git a/lib/utils/server.js b/lib/utils/server.js index 2b97fe8..1d6822f 100644 --- a/lib/utils/server.js +++ b/lib/utils/server.js @@ -1,11 +1,9 @@ -var Q = require('q'); -var _ = require('lodash'); - -var events = require('events'); -var http = require('http'); -var send = require('send'); -var util = require('util'); -var url = require('url'); +var Q = require("q"); +var events = require("events"); +var http = require("http"); +var send = require("send"); +var util = require("util"); +var url = require("url"); var Server = function() { this.running = null; @@ -17,7 +15,7 @@ util.inherits(Server, events.EventEmitter); // Return true if the server is running Server.prototype.isRunning = function() { - return this.running != null; + return !!this.running; }; // Stop the server @@ -57,25 +55,25 @@ Server.prototype.start = function(dir, port) { res.end(err.message); } - // Redirect to directory's index.html + // Redirect to directory"s index.html function redirect() { res.statusCode = 301; - res.setHeader('Location', req.url + '/'); - res.end('Redirecting to ' + req.url + '/'); + res.setHeader("Location", req.url + "/"); + res.end("Redirecting to " + req.url + "/"); } // Send file send(req, url.parse(req.url).pathname) .root(dir) - .on('error', error) - .on('directory', redirect) + .on("error", error) + .on("directory", redirect) .pipe(res); }); - that.running.on('connection', function (socket) { + that.running.on("connection", function (socket) { that.sockets.push(socket); socket.setTimeout(4000); - socket.on('close', function () { + socket.on("close", function () { that.sockets.splice(that.sockets.indexOf(socket), 1); }); }); @@ -91,6 +89,6 @@ Server.prototype.start = function(dir, port) { return d.promise; }); -} +}; module.exports = Server; diff --git a/lib/utils/string.js b/lib/utils/string.js index 72a9ca0..caa2364 100644 --- a/lib/utils/string.js +++ b/lib/utils/string.js @@ -1,7 +1,7 @@ var _ = require("lodash"); function escapeShellArg(arg) { - var ret = ''; + var ret = ""; ret = arg.replace(/"/g, '\\"'); @@ -11,7 +11,7 @@ function escapeShellArg(arg) { function optionsToShellArgs(options) { return _.chain(options) .map(function(value, key) { - if (value == null || value === false) return null; + if (value === null || value === undefined || value === false) return null; if (value === true) return key; return key+"="+escapeShellArg(value); }) diff --git a/lib/utils/watch.js b/lib/utils/watch.js index 3e73e47..4d1a752 100644 --- a/lib/utils/watch.js +++ b/lib/utils/watch.js @@ -1,9 +1,9 @@ -var Q = require('q'); -var _ = require('lodash'); -var path = require('path'); -var chokidar = require('chokidar'); +var Q = require("q"); +var _ = require("lodash"); +var path = require("path"); +var chokidar = require("chokidar"); -var parsers = require('gitbook-parsers') +var parsers = require("gitbook-parsers"); function watch(dir) { var d = Q.defer(); @@ -19,7 +19,7 @@ function watch(dir) { var watcher = chokidar.watch(toWatch, { cwd: dir, - ignored: '_book/**', + ignored: "_book/**", ignoreInitial: true }); |