-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
apply-action.js
94 lines (87 loc) · 3.02 KB
/
apply-action.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
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* @copyright 2017 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const glob = require("glob")
//------------------------------------------------------------------------------
// Exports
//------------------------------------------------------------------------------
/**
* Apply the given action to every file which matches to the given pattern.
*
* @param {string} pattern - The pattern to find files.
* @param {object} options - The option object.
* @param {boolean} [options.includeEmptyDirs=false] - The flag to include empty directories to copy.
* @param {boolean} [options.dereference=false] - The flag to dereference symbolic links.
* @param {function(string):void} action - The action function to apply.
* @returns {Promise<void>} The promise which will go fulfilled after done.
* @private
*/
module.exports = function applyAction(pattern, options, action) {
return new Promise((resolve, reject) => {
let count = 0
let done = false
let lastError = null
/**
* Calls the callback function if done.
* @returns {void}
*/
function next() {
if (done && count === 0) {
if (lastError == null) {
resolve()
} else {
reject(lastError)
}
}
}
const globOptions = {
nodir: !options.includeEmptyDirs,
silent: true,
follow: Boolean(options.dereference),
nosort: true,
}
try {
new glob.Glob(pattern, globOptions)
.on("match", sourcePath => {
if (lastError != null) {
return
}
count += 1
try {
action(sourcePath).then(
() => {
count -= 1
next()
},
error => {
count -= 1
lastError = lastError || error
next()
}
)
} catch (error) {
count -= 1
lastError = lastError || error
next()
}
})
.on("end", () => {
done = true
next()
})
.on("error", error => {
done = true
lastError = lastError || error
next()
})
} catch (error) {
reject(error)
}
})
}