-
Notifications
You must be signed in to change notification settings - Fork 3
/
logger.js
119 lines (103 loc) · 2.76 KB
/
logger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
'use strict';
// ***************************************************
// Colorful and friendly console plugin for Usync
// ***************************************************
let chalk = require('chalk')
/**
* Add current time prefix the content
* @param content
*/
function addTimeNowPrefix(content) {
let time = new Date().toLocaleTimeString()
return `${chalk.gray(time)} ${content}`
}
/**
* Get indent by count
* @param depth
* @returns {string}
*/
function getIndentByCount(depth) {
let indent = ''
while (depth > 0) {
indent += ' '
depth--
}
return indent
}
/**
* Get Depth
* @param task
* @returns {number}
*/
function getDepth(task) {
return task.$parent ? task.$parent.depth : 0
}
/**
* A recursive function to define
* @param parent
* @param child
* @param Usync
*/
function setDepth(parent, child, Usync) {
let _setDepth = (parent, child) => {
if (child instanceof Usync) {
child.depth = parent.depth + 1;
child.defferd.forEach(nextChild => {
_setDepth(child, nextChild)
})
}
}
_setDepth(parent, child)
}
/**
* Install function
* @param Usync
* @param opts
*/
module.exports = function install(Usync, opts) {
// Object.assign was supported from Node 4.8.3
opts = Object.assign({
indent: false,
time: false
}, opts)
let taskStartLog = function () {
return `Starting ${chalk.cyan(this.$current.name)} ...`
}
let taskEndLog = function () {
return `${chalk.red('Finished')} ${chalk.cyan(this.$current.name)} after ${chalk.magenta((this.$current.endTime - this.$current.startTime) + 'ms')}`
}
let hooks = {}
if (opts.indent) {
hooks.init = function (app) {
app.depth = 0
}
hooks.beforeUse = function (app, task) {
setDepth(app, task, Usync)
}
let oldTaskStartLog = taskStartLog
let oldEaskEndLog = taskEndLog
taskStartLog = function () {
return getIndentByCount(getDepth(this.$current)) + oldTaskStartLog.call(this)
}
taskEndLog = function () {
return getIndentByCount(getDepth(this.$current)) + oldEaskEndLog.call(this)
}
}
if (opts.time) {
let oldTaskStartLog = taskStartLog
let oldEaskEndLog = taskEndLog
taskStartLog = function () {
return addTimeNowPrefix(oldTaskStartLog.call(this))
}
taskEndLog = function () {
return addTimeNowPrefix(oldEaskEndLog.call(this))
}
}
hooks.taskStart = function (root) {
console.log(taskStartLog.call(root))
}
hooks.taskEnd = function (root) {
console.log(taskEndLog.call(root))
}
Usync.extend(hooks)
}