Repository navigation
Expand file tree
/
Copy pathpackagerify.js
More file actions
220 lines (200 loc) · 7.63 KB
/
Copy pathpackagerify.js
File metadata and controls
220 lines (200 loc) · 7.63 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/**
* Created by statyan on 25.04.16.
*/
var fs = require('fs');
var path = require('path');
var chokidar = require('chokidar');
/**
*
* @param options is object {
* packageName: string, usually reversed domain name of your organization. For example: 'com.google'
* packagesFileDir: string, path to folder where 'packages.js' would be generated
* watchSourceDirs: string or array of strings, paths *relative to packagesFileDir*
* }
*/
function Packagerify(options) {
// Check options
if (!options.watchSourceDirs) {
throw new Error('Packagerify required option "watchSourceDirs" is not defined');
}
if (!options.packagesFileDir) {
throw new Error('Packagerify required option "packagesFileDir" is not defined');
}
if (!options.packageName || (options.packageName.indexOf('.') < 0)) {
throw new Error('Packagerify package name must consist at least of two dot-separeated parts. For exapmle: "com.yourpackagename".');
}
var watchSourceDirs = options.watchSourceDirs;
if (typeof watchSourceDirs != 'object') {
watchSourceDirs = [watchSourceDirs];
}
// init packagerify object
this.packageName = options.packageName;
this.generatedPackagesFileDir = options.packagesFileDir;
this.watchSourceDirs = watchSourceDirs.map(function (item) {
return path.resolve(options.packagesFileDir, item);
});
this.packageObjectRoot = {};
this.packageObjectInjectionPoint = buildPackageObject(this.packageObjectRoot, this.packageName);
console.log('Starting Packagerify');
console.log('Process files in watched directories');
var that = this;
this.isReady = false;
console.log('Initialize file watcher');
var watcher = chokidar.watch(this.watchSourceDirs, {
persistent: true,
ignored: options.ignored,
});
watcher.on('all', function (event, modulePath) {
switch (event) {
case 'add':
that.fileWatcherFunction('add', modulePath);
break;
case 'unlink':
that.fileWatcherFunction('removeModule', modulePath);
break;
}
});
watcher.on('ready', function () {
that.isReady = true;
that.serialize();
console.log('Packagerify is running!');
});
watcher.on('unlinkDir', function (modulePath) {
that.fileWatcherFunction('removePackage', modulePath);
})
}
module.exports = Packagerify;
Packagerify.prototype.processModulePath = function (action, modulePath) {
var watchDirectory = this.watchSourceDirs.find(function (directory) {
return (modulePath.indexOf(directory) == 0);
});
if (!watchDirectory) {
throw 'Path is not in packagerify watched directory: ' + modulePath;
}
if ((action != 'removePackage') && (path.extname(modulePath) != '.js')) {
return;
}
// build relative to watched directory path. This path will be a package path
modulePath = path.relative(path.dirname(watchDirectory), modulePath);
modulePath = modulePath.substring(modulePath.indexOf(path.sep) + 1);
switch (action) {
case 'add':
this.addModuleToPackageObject(watchDirectory, modulePath);
break;
case 'removeModule':
this.removeModuleFromPackageObject(watchDirectory, modulePath, false);
break;
case 'removePackage':
this.removeModuleFromPackageObject(watchDirectory, modulePath, true);
break;
}
}
Packagerify.prototype.addModuleToPackageObject = function (watchedDirectory, modulePath) {
var packageParts = modulePath.split(path.sep);
var requirePath = path.relative(this.generatedPackagesFileDir, watchedDirectory);
requirePath = path.join(requirePath, modulePath);
// Build property tree branch for current module and put it to packageInjectionPoint
packageParts.reduce(function (previousItem, currentItem, index, array) {
if (index < array.length - 1) {
if (!previousItem.hasOwnProperty(currentItem)) {
previousItem[currentItem] = {};
}
} else {
currentItem = path.basename(currentItem, '.js');
if (previousItem.hasOwnProperty(currentItem)) {
delete previousItem[currentItem];
}
// generate property name which will be replaced after JSON.stringify
previousItem['propertyNameForReplace' + currentItem] = 'get ' + currentItem + '() {'
+ 'return require(\'./' + requirePath + '\')'
+ '}';
console.log('Adding module: ' + modulePath);
}
return previousItem[currentItem];
},
this.packageObjectInjectionPoint
);
}
Packagerify.prototype.removeModuleFromPackageObject = function (watchedDirectory, modulePath, isDirectory) {
var packageParts = modulePath.split(path.sep);
var packageNode = this.packageObjectInjectionPoint;
for (var i = 0; i < packageParts.length; i++) {
var part = packageParts[i];
if (i < packageParts.length - 1) {
packageNode = packageNode[part];
if (!packageNode) {
break;
}
continue;
}
var propName;
if (isDirectory) {
propName = part;
} else {
propName = 'propertyNameForReplace' + path.basename(part, '.js');
}
delete packageNode[propName];
if (isDirectory) {
console.log('Removing package: ' + modulePath);
} else {
console.log('Removing module: ' + modulePath);
}
}
}
var injectPackageFunc = function injectPackage(packageObject, packageName) {
var injectTarget = null;
try {
injectTarget = global;
} catch (e) {
console.log(e);
}
if (!injectTarget) {
try {
injectTarget = window;
} catch (e) {
console.log(e);
}
if (!injectTarget) {
console.log('Global namespace is not defined');
return;
}
}
var packageNameParts = packageName.split('.');
var packageItem = packageObject;
for (var i in packageNameParts) {
var part = packageNameParts[i];
if (!injectTarget.hasOwnProperty(part)) {
injectTarget[part] = packageItem[part];
return;
}
injectTarget = injectTarget[part];
packageItem = packageItem[part];
}
throw new Error('Package ' + packageName + ' already loaded to global namespace. Check your packages and it names.');
}
Packagerify.prototype.serialize = function () {
if (!this.isReady) {
return;
}
var packagesContent = '"use strict"\n'
+ 'var packages = ' + JSON.stringify(this.packageObjectRoot, null, 4).replace(/"/g, '') + '\n\n\n'
+ "injectPackage(packages, '" + this.packageName + "');\n"
+ 'module.exports = packages;';
packagesContent = packagesContent.replace(/propertyNameForReplace.*?: /g, '');
packagesContent += '\n\n\n' + injectPackageFunc.toString();
fs.writeFileSync(path.resolve(this.generatedPackagesFileDir, 'packages.js'), packagesContent);
}
Packagerify.prototype.fileWatcherFunction = function (action, modulePath) {
this.processModulePath(action, modulePath);
this.serialize();
}
/*********
UTILS
**********/
function buildPackageObject(packageObjectRoot, packageName) {
var packageParts = packageName.split('.');
return packageParts.reduce(function (previousValue, currentValue, index, array) {
previousValue[currentValue] = {};
return previousValue[currentValue];
}, packageObjectRoot);
}