1 |
|
2 |
|
3 | var exec = require('child_process').exec;
|
4 | var utils = require('./utils');
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | module.exports = exports = function (proto) {
|
22 | function compare(orig, compareTo, options, cb) {
|
23 | orig = utils.escape(orig);
|
24 | compareTo = utils.escape(compareTo);
|
25 |
|
26 | var isImageMagick = this._options && this._options.imageMagick;
|
27 |
|
28 | var bin = isImageMagick ? '' : 'gm ';
|
29 | var execCmd = bin + 'compare -metric mse ' + orig + ' ' + compareTo;
|
30 | var tolerance = 0.4
|
31 |
|
32 | if (typeof options === 'object') {
|
33 | if (options.file) {
|
34 | if (typeof options.file !== 'string') {
|
35 | throw new TypeError('The path for the diff output is invalid');
|
36 | }
|
37 |
|
38 | var highlightColorOption = options.highlightColor
|
39 | ? ' -highlight-color ' + options.highlightColor + ' '
|
40 | : ' ';
|
41 | var highlightStyleOption = options.highlightStyle
|
42 | ? ' -highlight-style ' + options.highlightStyle + ' '
|
43 | : ' ';
|
44 | var diffFilename = utils.escape(options.file);
|
45 |
|
46 | var diffOpt = isImageMagick ? diffFilename : ('-file ' + diffFilename);
|
47 | execCmd += highlightColorOption + highlightStyleOption + ' ' + diffOpt;
|
48 | }
|
49 |
|
50 | if (options.tolerance) {
|
51 | if (typeof options.tolerance !== 'number') {
|
52 | throw new TypeError('The tolerance value should be a number');
|
53 | }
|
54 | tolerance = options.tolerance;
|
55 | }
|
56 | } else {
|
57 |
|
58 | isImageMagick && (execCmd += ' null:');
|
59 |
|
60 | if (typeof options == 'function') {
|
61 | cb = options;
|
62 | } else {
|
63 | tolerance = options
|
64 | }
|
65 | }
|
66 |
|
67 | exec(execCmd, function (err, stdout, stderr) {
|
68 |
|
69 | if (isImageMagick) {
|
70 | if (!err) {
|
71 | return cb(null, 0 <= tolerance, 0, stdout);
|
72 | }
|
73 | if (err.code === 1) {
|
74 | err = null;
|
75 | stdout = stderr;
|
76 | }
|
77 | }
|
78 | if (err) {
|
79 | return cb(err);
|
80 | }
|
81 |
|
82 |
|
83 | var regex = isImageMagick ? /\((\d+\.?[\d\-\+e]*)\)/m : /Total: (\d+\.?\d*)/m;
|
84 | var match = regex.exec(stdout);
|
85 | if (!match) {
|
86 | err = new Error('Unable to parse output.\nGot ' + stdout);
|
87 | return cb(err);
|
88 | }
|
89 |
|
90 | var equality = parseFloat(match[1]);
|
91 | cb(null, equality <= tolerance, equality, stdout);
|
92 | });
|
93 | }
|
94 |
|
95 | if (proto) {
|
96 | proto.compare = compare;
|
97 | }
|
98 | return compare;
|
99 | };
|
100 |
|