-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
107 lines (96 loc) · 2.75 KB
/
index.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
'use strict';
var RSVP = require('rsvp'),
fs = require('fs'),
path = require('path');
/**
* Walk the input tree, calling visitor#visit for every file in the path.
*
* `vistor.visit` can return nothing, or a promise if it's behaving asynchronously.
*
* @param inputTree - path - relative path do the source dir
* @param visitor - an object
* @return {TreeTraverser}
* @constructor
* @alias module:index
*/
function TreeTraverser(inputTree, visitor) {
if (!(this instanceof TreeTraverser)) return new TreeTraverser(inputTree, visitor);
this.inputTree = inputTree;
this.visitor = visitor;
}
/**
*
* Read the directory, and stat the files it contains. Returns a promise
* that will be resolved with the result of statFiles
*
* @param srcDir {string} the directory to read
* @return {RSVP.Promise}
*/
TreeTraverser.prototype.readDir = function (srcDir) {
var self = this;
//make a promise to read the directory.
return new RSVP.Promise(function (resolve, reject) {
fs.readdir(srcDir, function (err, files) {
//Resolve with all files or err
if (err) { reject(err); }
else {
resolve(self.statFiles(srcDir, files));
}
});
});
};
/**
* Stat all the files in `parentPath`, calling `readDir` for directories,
* and deferring to the visitor for plain files.
* The resulting promise will be resolved with an array of promises.
*
* @param parentPath {string} the parent directory for the files
* @param files {array} the list of files in the directory
* @return {RSVP.Promise}
*/
TreeTraverser.prototype.statFiles = function statFiles(parentPath, files) {
var self = this;
//make a promise to stat all files, which is resolved
return RSVP.all(files.map(function (file) {
//when each file is statted
return new RSVP.Promise(function (resolve, reject) {
var filePath = path.join(parentPath, file);
//read the file
fs.lstat(filePath, function (err, stat) {
if (err) { reject(err)}
else {
if (stat.isDirectory()) {
//and resolve it with the promise to read the directory
resolve(self.readDir(filePath))
} else {
//or a visit to the filepath
resolve(self.visitor.visit(filePath));
}
}
});
});
}));
};
/**
* Implementation of Brocolli's required `read` method for a tree
*
* Read the input tree, then read read the src dir
*
* @param readTree
* @return {RSVP.Promise}
*/
TreeTraverser.prototype.read = function (readTree) {
var self = this;
return readTree(self.inputTree)
.then(this.readDir.bind(this))
.then(function () {
return self.inputTree;
});
};
TreeTraverser.prototype.cleanup = function () {
};
/**
*
* @type {TreeTraverser}
*/
module.exports = TreeTraverser;