Permalink
Browse files

Separated core logic to lib

  • Loading branch information...
1 parent 15c9759 commit fa82f006b055a58e571ca412aa93ff728da823c8 @vkadam committed Oct 19, 2014
Showing with 204 additions and 175 deletions.
  1. +5 −5 Gruntfile.js
  2. +198 −0 lib/jsbeautifier.js
  3. +1 −170 tasks/jsbeautifier.js
View
@@ -4,7 +4,7 @@ module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
jshint: {
- files: ["package.json", "Gruntfile.js", "tasks/**/*.js", "test/**/*.js"],
+ files: ["package.json", "Gruntfile.js", "lib/**/*.js", "tasks/**/*.js", "test/**/*.js"],
options: {
jshintrc: true
}
@@ -101,10 +101,10 @@ module.exports = function(grunt) {
devUpdate: {
main: {
options: {
- updateType: 'force', //just report outdated packages
- reportUpdated: false, //don't report up-to-date packages
+ updateType: 'force',
+ reportUpdated: false,
packages: {
- devDependencies: true, //only check for devDependencies
+ devDependencies: true,
dependencies: true
}
}
@@ -115,7 +115,7 @@ module.exports = function(grunt) {
// Actually load this plugin"s task(s).
grunt.loadTasks("tasks");
- // By default, beautifiy, lint and run all tests.
+ // By default, beautify, lint and run all tests.
grunt.registerTask("test", ["jshint", "copy", "nodeunit", "clean"]);
grunt.registerTask("default", ["test", "jsbeautifier:default"]);
};
View
@@ -0,0 +1,198 @@
+"use strict";
+
+var path = require("path"),
+ grunt = require('grunt'),
+ jsBeautify = require("js-beautify"),
+ _ = require("lodash"),
+ stringUtils = require("underscore.string"),
+ JsBeautifierTask = function(task) {
+ // Store reference to original task
+ this.task = task;
+
+ // Merge task options with defaults
+ this.options = task.options(JsBeautifierTask.DEFAULT_OPTIONS);
+ };
+
+/**
+ * Default options that will be merged with options specified in
+ * the original task.
+ *
+ * @type {*}
+ */
+JsBeautifierTask.DEFAULT_OPTIONS = {
+ mode: "VERIFY_AND_WRITE",
+ dest: "",
+ js: {},
+ css: {},
+ html: {}
+};
+
+/**
+ * Static method for registering an instance of the task with Grunt.
+ *
+ * @param {*} grunt
+ */
+JsBeautifierTask.registerWithGrunt = function(grunt) {
+ grunt.registerMultiTask("jsbeautifier", "jsbeautifier.org for grunt", function() {
+ var task = new JsBeautifierTask(this);
+ task.run();
+ });
+};
+
+function getFileType(file, config) {
+ var fileType = null,
+ fileMapping = {
+ "js": config.js.fileTypes,
+ "css": config.css.fileTypes,
+ "html": config.html.fileTypes
+ };
+ _.forEach(fileMapping, function(extensions, type) {
+ fileType = type;
+ return -1 === _.findIndex(extensions, function(ext) {
+ return stringUtils.endsWith(file, ext);
+ });
+ });
+ return fileType;
+}
+
+function getBeautifierSetup(file, config) {
+ var fileType = getFileType(file, config);
+ switch (fileType) {
+ case "js":
+ return [jsBeautify.js, config.js, true];
+ case "css":
+ return [jsBeautify.css, config.css];
+ case "html":
+ return [jsBeautify.html, config.html];
+ default:
+ grunt.fail.warn("Cannot beautify " + file.cyan + " (only js, css and html files can be beautified)");
+ return null;
+ }
+}
+
+function beautify(file, config, actionHandler) {
+ var setup = getBeautifierSetup(file, config);
+ if (!setup) {
+ return;
+ }
+
+ var beautifier = setup[0],
+ beautifyConfig = setup[1],
+ addNewLine = setup[2];
+
+ var original = grunt.file.read(file);
+ grunt.verbose.write("Beautifying " + file.cyan + "...");
+ var result = beautifier(original, beautifyConfig);
+ // jsbeautifier would skip the line terminator for js files
+ if (addNewLine) {
+ result += "\n";
+ }
+ grunt.verbose.ok();
+ /*jshint eqeqeq: false */
+ if (original != result) {
+ actionHandler(file, result);
+ }
+}
+
+JsBeautifierTask.prototype.run = function() {
+ var options = this.options;
+
+ var fileCount = 0,
+ changedFileCount = 0,
+ unVerifiedFiles = [];
+
+ function verifyActionHandler(src) {
+ unVerifiedFiles.push(src);
+ }
+
+ function verifyAndWriteActionHandler(src, result) {
+ grunt.verbose.writeln(options.dest + src);
+ grunt.file.write(options.dest + src, result);
+ changedFileCount++;
+ }
+
+ function convertCamelCaseToUnderScore(config) {
+ var underscoreKey;
+ _.forEach([config.js, config.css, config.html], function(conf) {
+ _.forEach(conf, function(value, key) {
+ underscoreKey = stringUtils.underscored(key);
+ if ("fileTypes" !== key && key !== underscoreKey) {
+ conf[underscoreKey] = value;
+ delete conf[key];
+ }
+ });
+ });
+ }
+
+ function getConfig() {
+ var config,
+ jsBeautifyRc = options.config;
+ if (jsBeautifyRc) {
+ var baseConfig = grunt.file.readJSON(path.resolve(jsBeautifyRc));
+ config = {
+ js: {},
+ css: {},
+ html: {}
+ };
+ _.extend(config.js, baseConfig);
+ _.extend(config.css, baseConfig);
+ _.extend(config.html, baseConfig);
+ _.extend(config.js, baseConfig.js);
+ _.extend(config.css, baseConfig.css);
+ _.extend(config.html, baseConfig.html);
+ _.extend(config.js, options.js);
+ _.extend(config.css, options.css);
+ _.extend(config.html, options.html);
+ } else {
+ config = options;
+ }
+ config.js.fileTypes = _.union(config.js.fileTypes, [".js", ".json"]);
+ config.css.fileTypes = _.union(config.css.fileTypes, [".css"]);
+ config.html.fileTypes = _.union(config.html.fileTypes, [".html"]);
+
+ grunt.verbose.writeln("Beautify config before converting camelcase to underscore: " + JSON.stringify(config));
+
+ convertCamelCaseToUnderScore(config);
+
+ grunt.verbose.writeln("Using beautify config: " + JSON.stringify(config));
+ return config;
+ }
+
+ if (this.task.filesSrc && this.task.filesSrc.length > 0) {
+ if (!_.isEmpty(options.dest)) {
+ grunt.verbose.writeln("All beautified files will be stored under \"" + options.dest + "\" folder");
+ if (!stringUtils.endsWith(options.dest, "/")) {
+ options.dest += "/";
+ }
+ }
+ grunt.verbose.writeln("Beautifying using filesSrc with " + this.task.filesSrc.length.toString().cyan + " files...");
+
+ grunt.verbose.writeln("Using mode=\"" + options.mode + "\"...");
+ var actionHandler = "VERIFY_ONLY" === options.mode ? verifyActionHandler : verifyAndWriteActionHandler,
+ config = getConfig(),
+ done = this.task.async(),
+ q = grunt.util.async.queue(function(src, callback) {
+ if (grunt.file.isDir(src)) {
+ callback();
+ return;
+ }
+
+ beautify(src, config, actionHandler);
+ fileCount++;
+ callback();
+ }, 10);
+
+ q.drain = function() {
+ if (unVerifiedFiles.length) {
+ grunt.fail.warn("The following files are not beautified:\n" + unVerifiedFiles.join("\n").cyan + "\n");
+ }
+ grunt.log.write("Beautified " + fileCount.toString().cyan + " files, changed " + changedFileCount.toString().cyan + " files...");
+ grunt.log.ok();
+ done();
+ };
+
+ q.push(this.task.filesSrc);
+ }
+};
+
+module.exports = JsBeautifierTask;
Oops, something went wrong.

0 comments on commit fa82f00

Please sign in to comment.