Skip to content

Commit

Permalink
Refactor the code according to the Code Style
Browse files Browse the repository at this point in the history
  • Loading branch information
eGavr committed Aug 19, 2014
1 parent aca52fc commit b999c42
Show file tree
Hide file tree
Showing 7 changed files with 73 additions and 85 deletions.
32 changes: 17 additions & 15 deletions lib/cli.js
Expand Up @@ -12,10 +12,11 @@ module.exports = require('coa').Cmd()
.opt()
.name('version')
.title('Shows the version number')
/*jshint -W024 */
.short('v').long('version')
.flag()
.only()
.act(function() {
.act(function () {
var p = require('../package.json');
return p.name + ' ' + p.version;
})
Expand All @@ -30,7 +31,8 @@ module.exports = require('coa').Cmd()
.title('The number of characters around the diff (default: 40)')
.long('chars-around-diff')
.def(40)
.val(function(val) {
.val(function (val) {
/*jshint es3:false */
return parseInt(val);
})
.end()
Expand All @@ -44,21 +46,21 @@ module.exports = require('coa').Cmd()
.title('Path to the 2-nd HTML file')
.req()
.end()
.act(function(opts, args) {
.act(function (opts, args) {
return vow.all([
vfs.read(path.resolve(args.path1), 'utf-8'),
vfs.read(path.resolve(args.path2), 'utf-8'),
opts.config ? vfs.read(path.resolve(opts.config)) : undefined
]).spread(function (html1, html2, config) {
config = config ? JSON.parse(config) : {};
vfs.read(path.resolve(args.path1), 'utf-8'),
vfs.read(path.resolve(args.path2), 'utf-8'),
opts.config ? vfs.read(path.resolve(opts.config)) : undefined
]).spread(function (html1, html2, config) {
config = config ? JSON.parse(config) : {};

var options = utils.defaults(config),
loggerOptions = {
charsAroundDiff: opts.charsAroundDiff
},
htmlDiffer = new HtmlDiffer(options);
var options = utils.defaults(config),
loggerOptions = {
charsAroundDiff: opts.charsAroundDiff
},
htmlDiffer = new HtmlDiffer(options);

diffLogger.log(htmlDiffer.diffHtml(html1, html2), loggerOptions);
});
diffLogger.log(htmlDiffer.diffHtml(html1, html2), loggerOptions);
});
})
.run(process.argv.slice(2));
8 changes: 4 additions & 4 deletions lib/diff-logger.js
Expand Up @@ -24,15 +24,15 @@ function getDiffText(diff, options) {
charsAroundDiff = 40;
}

if (diff.length === 1 && !diff[0].added && !diff[0].removed) return output;
if (diff.length === 1 && !diff[0].added && !diff[0].removed) { return output; }

diff.forEach(function(part) {
diff.forEach(function (part) {
var index = diff.indexOf(part),
partValue = part.value,
color = 'grey';

if (part.added) color = 'green';
if (part.removed) color = 'red';
if (part.added) { color = 'green'; }
if (part.removed) { color = 'red'; }

if (color !== 'grey') {
output += (!index ? '\n' : '') + partValue.inverse[color];
Expand Down
41 changes: 18 additions & 23 deletions lib/index.js
Expand Up @@ -8,15 +8,14 @@ var utils = require('./utils'),
/**
* Converts the HTML document to the AST Tree
* @param {String} HTMLDoc
* @param {Object} options
* @returns {AST}
*/
function htmlToAST(HTMLDoc) {
var parser,
parserHandler;

parserHandler = new htmlParser.DomHandler(function(err) {
if (err) console.log(err);
parserHandler = new htmlParser.DomHandler(function (err) {
if (err) { console.log(err); }
});

parser = new htmlParser.Parser(parserHandler);
Expand All @@ -34,9 +33,8 @@ function htmlToAST(HTMLDoc) {
function modifyASTTree(tree, options) {
var delComments = [];

_.forEach(tree, function(node) {
_.forEach(tree, function (node) {
if (options.ignoreWhitespaces && node.type === 'text') {

node.data = node.data
.replace(/(\n|\r|\t|\v|\f)+/g, '')
.replace(/\s+/g, ' ')
Expand All @@ -52,31 +50,30 @@ function modifyASTTree(tree, options) {
}

if (node.hasOwnProperty('attribs')) {
var attrs = utils.sortObj(node['attribs']);
var attrs = utils.sortObj(node.attribs);

if (attrs.hasOwnProperty('class')) {
attrs['class'] = utils.sortCssClasses(attrs['class']);
}

_.forEach(options.compareHtmlAttrsAsJSON, function(attr) {
_.forEach(options.compareHtmlAttrsAsJSON, function (attr) {
var attrValue,
isFunction = (attr === 'onclick' || attr === 'ondblclick'); // @FIXME: should be configurable

if (attrs.hasOwnProperty(attr)) {

attrValue = utils.parseAttr(attrs[attr].replace(/"/g, '"'), isFunction);
attrValue = utils.sortObj(attrValue);
attrValue = JSON.stringify(attrValue);

attrs[attr] = (isFunction ? 'return ' : '') + attrValue.replace(/"/g, '"')
attrs[attr] = (isFunction ? 'return ' : '') + attrValue.replace(/"/g, '"');
}
});

_.forEach(options.ignoreHtmlAttrs, function(attr) {
_.forEach(options.ignoreHtmlAttrs, function (attr) {
attrs.hasOwnProperty(attr) && (attrs[attr] = '');
});

node['attribs'] = attrs;
node.attribs = attrs;
}

if (node.hasOwnProperty('children')) {
Expand All @@ -93,19 +90,18 @@ function modifyASTTree(tree, options) {

/**
*
* @param [options]
* @param {Object} [options]
* @param {String[]} [options.ignoreHtmlAttrs]
* @param {String[]} [options.compareHtmlAttrsAsJSON]
* @param {Boolean} [options.verbose]
* @param {Boolean} [options.ignoreWhitespaces=true]
* @param {Boolean} [options.bem=false]
* @constructor
*/
var HtmlDiff = function(options) {
var HtmlDiff = function (options) {
this.options = utils.defaults(options);
};

var Diff = diff.Diff;
},
Diff = diff.Diff;

HtmlDiff.prototype = Diff.prototype;

Expand All @@ -114,7 +110,7 @@ HtmlDiff.prototype = Diff.prototype;
* @param {String} value
* @returns {Array}
*/
HtmlDiff.prototype.tokenize = function(value) {
HtmlDiff.prototype.tokenize = function (value) {
var options = this.options,
ASTTree = htmlToAST(value, options);

Expand All @@ -132,18 +128,18 @@ HtmlDiff.prototype.tokenize = function(value) {

/**
*
* @param [options]
* @param {Object} [options]
* @param {String[]} [options.ignoreHtmlAttrs]
* @param {String[]} [options.compareHtmlAttrsAsJSON]
* @param {Boolean} [options.verbose]
* @param {Boolean} [options.ignoreWhitespaces=true]
* @param {Boolean} [options.bem=false]
* @constructor
*/
var HtmlDiffer = function(options) {
var HtmlDiffer = function (options) {
options = utils.defaults(options);

if (options['bem']) {
if (options.bem) {
options.ignoreHtmlAttrs = ['id', 'for'];
options.compareHtmlAttrsAsJSON = ['data-bem', 'onclick', 'ondblclick'];
}
Expand All @@ -158,7 +154,7 @@ var HtmlDiffer = function(options) {
* @param {Object} [options]
* @returns {Diff}
*/
HtmlDiffer.prototype.diffHtml = function(html1, html2, options) {
HtmlDiffer.prototype.diffHtml = function (html1, html2, options) {
if (options) {
console.warn('WARNING! The third param of \'diffHtml\' method is deprecated!'.bold.red);
}
Expand All @@ -177,7 +173,7 @@ HtmlDiffer.prototype.diffHtml = function(html1, html2, options) {
* @param {Object} [options]
* @returns {Boolean}
*/
HtmlDiffer.prototype.isEqual = function(html1, html2, options) {
HtmlDiffer.prototype.isEqual = function (html1, html2, options) {
if (options) {
console.warn('WARNING! The third param of \'isEqual\' method is deprecated!'.bold.red);
}
Expand Down Expand Up @@ -211,7 +207,6 @@ function bemDiff(html1, html2) {
logger.log(htmlDiffer.diff(html1, html2), loggerOptions);
}


var htmlDiffer = new HtmlDiffer();

module.exports = {
Expand Down
31 changes: 20 additions & 11 deletions lib/utils.js
Expand Up @@ -7,55 +7,57 @@ require('colors');
* @param {Object} obj
* @returns {Object}
*/
exports.sortObj = function sortObj(obj) {
function sortObj(obj) {
var keys = _.keys(obj).sort(),
sortedObj = {};

_.forEach(keys, function(key) {
_.forEach(keys, function (key) {
var objValue = obj[key];

if(_.isPlainObject(objValue)) {
if (_.isPlainObject(objValue)) {
objValue = sortObj(objValue);
}

sortedObj[key] = objValue;
});

return sortedObj;
};
}

/**
* Parses the given JSON in HTML attribute
* @param {String} val
* @param {Boolean} [isClick]
* @returns {Object}
*/
exports.parseAttr = function(val, isClick) {
function parseAttr(val, isClick) {
if (isClick) {
/*jshint evil: true */
var fn = Function(val);

return fn ? fn() : {};
}

return JSON.parse(val);
};
}

/**
* Sorts the given CSS class attribute
* @param {String} cssClasses
* @returns {String}
*/
exports.sortCssClasses = function(cssClasses) {
function sortCssClasses(cssClasses) {
var classList = (cssClasses || '').split(' ');

return _.filter(classList).sort().join(' ');
};
}

/**
*
* @param options
* Sets options
* @param {Object} options
* @returns {Object}
*/
exports.defaults = function(options) {
function defaults(options) {
if (options && options.hasOwnProperty('ignoreWhitespace')) {
console.log('WARNING! Option \'ignoreWhitespace\' is deprecated, please, use \'ignoreWhitespaces\''.bold.red);
options.ignoreWhitespaces = options.ignoreWhitespace;
Expand All @@ -72,4 +74,11 @@ exports.defaults = function(options) {

bem: false
});
}

module.exports = {
sortObj: sortObj,
parseAttr: parseAttr,
sortCssClasses: sortCssClasses,
defaults: defaults
};
21 changes: 5 additions & 16 deletions test/diffHtml.js
@@ -1,27 +1,16 @@
var fs = require('fs'),
HtmlDiffer = require('../lib/index').HtmlDiffer;

function readFiles(f1, f2) {
var files = {};

files.html1 = fs.readFileSync('test/fixtures/' + f1, 'utf-8');
files.html2 = fs.readFileSync('test/fixtures/' + f2, 'utf-8');

return files;
}
var HtmlDiffer = require('../lib/index').HtmlDiffer;

describe('\'diffHtml\'', function () {

it('must set options', function () {
var htmlDiffer = new HtmlDiffer({ ignoreHtmlAttrs: ['id', 'for'], ignoreWhitespaces: true }),
files = readFiles('3.html', '_3.html'),
first = '<label for="random">label for input</label><input id="random">',
second = '<label for="sfsdfksdf">label for input</label><input id="sfsdfksdf">',
res = [ {
value: '<html><head><title>Test</title></head><body><label for="">label for input</label><input id=""></body></html>',
value: '<label for="">label for input</label><input id="">',
added: undefined,
removed: undefined
} ];

htmlDiffer.diffHtml(files.html1, files.html2).must.be.eql(res);
htmlDiffer.diffHtml(first, second).must.be.eql(res);
});

});

0 comments on commit b999c42

Please sign in to comment.