Skip to content

Commit 7116906

Browse files
TooTallNatethebigredgeek
authored andcommittedOct 11, 2017
refactor to make the common code be a setup function (#507)
This is so that we can make both a Node.js instance and web browser instance for when `--inspect` is used in Node.js.
1 parent f073e05 commit 7116906

File tree

4 files changed

+272
-275
lines changed

4 files changed

+272
-275
lines changed
 

‎src/browser.js

+17-23
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
/**
22
* This is the web browser implementation of `debug()`.
3-
*
4-
* Expose `debug()` as the module.
53
*/
64

7-
exports = module.exports = require('./debug');
85
exports.log = log;
96
exports.formatArgs = formatArgs;
107
exports.save = save;
@@ -66,19 +63,6 @@ function useColors() {
6663
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
6764
}
6865

69-
/**
70-
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
71-
*/
72-
73-
exports.formatters.j = function(v) {
74-
try {
75-
return JSON.stringify(v);
76-
} catch (err) {
77-
return '[UnexpectedJSONParseError]: ' + err.message;
78-
}
79-
};
80-
81-
8266
/**
8367
* Colorize log arguments if enabled.
8468
*
@@ -93,7 +77,7 @@ function formatArgs(args) {
9377
+ (useColors ? ' %c' : ' ')
9478
+ args[0]
9579
+ (useColors ? '%c ' : ' ')
96-
+ '+' + exports.humanize(this.diff);
80+
+ '+' + module.exports.humanize(this.diff);
9781

9882
if (!useColors) return;
9983

@@ -171,12 +155,6 @@ function load() {
171155
return r;
172156
}
173157

174-
/**
175-
* Enable namespaces listed in `localStorage.debug` initially.
176-
*/
177-
178-
exports.enable(load());
179-
180158
/**
181159
* Localstorage attempts to return the localstorage.
182160
*
@@ -193,3 +171,19 @@ function localstorage() {
193171
return window.localStorage;
194172
} catch (e) {}
195173
}
174+
175+
module.exports = require('./common')(exports);
176+
177+
var formatters = module.exports.formatters;
178+
179+
/**
180+
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
181+
*/
182+
183+
formatters.j = function(v) {
184+
try {
185+
return JSON.stringify(v);
186+
} catch (err) {
187+
return '[UnexpectedJSONParseError]: ' + err.message;
188+
}
189+
};

‎src/common.js

+235
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
2+
/**
3+
* This is the common logic for both the Node.js and web browser
4+
* implementations of `debug()`.
5+
*/
6+
7+
module.exports = function setup(env) {
8+
createDebug.debug = createDebug['default'] = createDebug;
9+
createDebug.coerce = coerce;
10+
createDebug.disable = disable;
11+
createDebug.enable = enable;
12+
createDebug.enabled = enabled;
13+
createDebug.humanize = require('ms');
14+
15+
Object.keys(env).forEach(function(key) {
16+
createDebug[key] = env[key];
17+
});
18+
19+
/**
20+
* Active `debug` instances.
21+
*/
22+
createDebug.instances = [];
23+
24+
/**
25+
* The currently active debug mode names, and names to skip.
26+
*/
27+
28+
createDebug.names = [];
29+
createDebug.skips = [];
30+
31+
/**
32+
* Map of special "%n" handling functions, for the debug "format" argument.
33+
*
34+
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
35+
*/
36+
37+
createDebug.formatters = {};
38+
39+
/**
40+
* Select a color.
41+
* @param {String} namespace
42+
* @return {Number}
43+
* @api private
44+
*/
45+
46+
function selectColor(namespace) {
47+
var hash = 0, i;
48+
49+
for (i in namespace) {
50+
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
51+
hash |= 0; // Convert to 32bit integer
52+
}
53+
54+
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
55+
}
56+
createDebug.selectColor = selectColor;
57+
58+
/**
59+
* Create a debugger with the given `namespace`.
60+
*
61+
* @param {String} namespace
62+
* @return {Function}
63+
* @api public
64+
*/
65+
66+
function createDebug(namespace) {
67+
var prevTime;
68+
69+
function debug() {
70+
// disabled?
71+
if (!debug.enabled) return;
72+
73+
var self = debug;
74+
75+
// set `diff` timestamp
76+
var curr = +new Date();
77+
var ms = curr - (prevTime || curr);
78+
self.diff = ms;
79+
self.prev = prevTime;
80+
self.curr = curr;
81+
prevTime = curr;
82+
83+
// turn the `arguments` into a proper Array
84+
var args = new Array(arguments.length);
85+
for (var i = 0; i < args.length; i++) {
86+
args[i] = arguments[i];
87+
}
88+
89+
args[0] = createDebug.coerce(args[0]);
90+
91+
if ('string' !== typeof args[0]) {
92+
// anything else let's inspect with %O
93+
args.unshift('%O');
94+
}
95+
96+
// apply any `formatters` transformations
97+
var index = 0;
98+
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
99+
// if we encounter an escaped % then don't increase the array index
100+
if (match === '%%') return match;
101+
index++;
102+
var formatter = createDebug.formatters[format];
103+
if ('function' === typeof formatter) {
104+
var val = args[index];
105+
match = formatter.call(self, val);
106+
107+
// now we need to remove `args[index]` since it's inlined in the `format`
108+
args.splice(index, 1);
109+
index--;
110+
}
111+
return match;
112+
});
113+
114+
// apply env-specific formatting (colors, etc.)
115+
createDebug.formatArgs.call(self, args);
116+
117+
var logFn = self.log || createDebug.log;
118+
logFn.apply(self, args);
119+
}
120+
121+
debug.namespace = namespace;
122+
debug.enabled = createDebug.enabled(namespace);
123+
debug.useColors = createDebug.useColors();
124+
debug.color = selectColor(namespace);
125+
debug.destroy = destroy;
126+
//debug.formatArgs = formatArgs;
127+
//debug.rawLog = rawLog;
128+
129+
// env-specific initialization logic for debug instances
130+
if ('function' === typeof createDebug.init) {
131+
createDebug.init(debug);
132+
}
133+
134+
createDebug.instances.push(debug);
135+
136+
return debug;
137+
}
138+
139+
function destroy () {
140+
var index = createDebug.instances.indexOf(this);
141+
if (index !== -1) {
142+
createDebug.instances.splice(index, 1);
143+
return true;
144+
} else {
145+
return false;
146+
}
147+
}
148+
149+
/**
150+
* Enables a debug mode by namespaces. This can include modes
151+
* separated by a colon and wildcards.
152+
*
153+
* @param {String} namespaces
154+
* @api public
155+
*/
156+
157+
function enable(namespaces) {
158+
createDebug.save(namespaces);
159+
160+
createDebug.names = [];
161+
createDebug.skips = [];
162+
163+
var i;
164+
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
165+
var len = split.length;
166+
167+
for (i = 0; i < len; i++) {
168+
if (!split[i]) continue; // ignore empty strings
169+
namespaces = split[i].replace(/\*/g, '.*?');
170+
if (namespaces[0] === '-') {
171+
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
172+
} else {
173+
createDebug.names.push(new RegExp('^' + namespaces + '$'));
174+
}
175+
}
176+
177+
for (i = 0; i < createDebug.instances.length; i++) {
178+
var instance = createDebug.instances[i];
179+
instance.enabled = createDebug.enabled(instance.namespace);
180+
}
181+
}
182+
183+
/**
184+
* Disable debug output.
185+
*
186+
* @api public
187+
*/
188+
189+
function disable() {
190+
createDebug.enable('');
191+
}
192+
193+
/**
194+
* Returns true if the given mode name is enabled, false otherwise.
195+
*
196+
* @param {String} name
197+
* @return {Boolean}
198+
* @api public
199+
*/
200+
201+
function enabled(name) {
202+
if (name[name.length - 1] === '*') {
203+
return true;
204+
}
205+
var i, len;
206+
for (i = 0, len = createDebug.skips.length; i < len; i++) {
207+
if (createDebug.skips[i].test(name)) {
208+
return false;
209+
}
210+
}
211+
for (i = 0, len = createDebug.names.length; i < len; i++) {
212+
if (createDebug.names[i].test(name)) {
213+
return true;
214+
}
215+
}
216+
return false;
217+
}
218+
219+
/**
220+
* Coerce `val`.
221+
*
222+
* @param {Mixed} val
223+
* @return {Mixed}
224+
* @api private
225+
*/
226+
227+
function coerce(val) {
228+
if (val instanceof Error) return val.stack || val.message;
229+
return val;
230+
}
231+
232+
createDebug.enable(createDebug.load());
233+
234+
return createDebug;
235+
}

‎src/debug.js

-225
This file was deleted.

‎src/node.js

+20-27
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,8 @@ var util = require('util');
77

88
/**
99
* This is the Node.js implementation of `debug()`.
10-
*
11-
* Expose `debug()` as the module.
1210
*/
1311

14-
exports = module.exports = require('./debug');
1512
exports.init = init;
1613
exports.log = log;
1714
exports.formatArgs = formatArgs;
@@ -76,27 +73,6 @@ function useColors() {
7673
: tty.isatty(process.stderr.fd);
7774
}
7875

79-
/**
80-
* Map %o to `util.inspect()`, all on a single line.
81-
*/
82-
83-
exports.formatters.o = function(v) {
84-
this.inspectOpts.colors = this.useColors;
85-
return util.inspect(v, this.inspectOpts)
86-
.split('\n').map(function(str) {
87-
return str.trim()
88-
}).join(' ');
89-
};
90-
91-
/**
92-
* Map %o to `util.inspect()`, allowing multiple lines if needed.
93-
*/
94-
95-
exports.formatters.O = function(v) {
96-
this.inspectOpts.colors = this.useColors;
97-
return util.inspect(v, this.inspectOpts);
98-
};
99-
10076
/**
10177
* Adds ANSI color escape codes if enabled.
10278
*
@@ -113,7 +89,7 @@ function formatArgs(args) {
11389
var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m';
11490

11591
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
116-
args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
92+
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001b[0m');
11793
} else {
11894
args[0] = getDate() + name + ' ' + args[0];
11995
}
@@ -179,8 +155,25 @@ function init (debug) {
179155
}
180156
}
181157

158+
module.exports = require('./common')(exports);
159+
160+
var formatters = module.exports.formatters;
161+
162+
/**
163+
* Map %o to `util.inspect()`, all on a single line.
164+
*/
165+
166+
formatters.o = function(v) {
167+
this.inspectOpts.colors = this.useColors;
168+
return util.inspect(v, this.inspectOpts)
169+
.replace(/\s*\n\s*/g, ' ');
170+
};
171+
182172
/**
183-
* Enable namespaces listed in `process.env.DEBUG` initially.
173+
* Map %O to `util.inspect()`, allowing multiple lines if needed.
184174
*/
185175

186-
exports.enable(load());
176+
formatters.O = function(v) {
177+
this.inspectOpts.colors = this.useColors;
178+
return util.inspect(v, this.inspectOpts);
179+
};

0 commit comments

Comments
 (0)
This conversation has been locked and limited to collaborators.