-
Notifications
You must be signed in to change notification settings - Fork 23
/
builder.js
415 lines (370 loc) · 14.4 KB
/
builder.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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
const {promisify} = require("util");
const rimraf = promisify(require("rimraf"));
const log = require("@ui5/logger").getGroupLogger("builder:builder");
const resourceFactory = require("@ui5/fs").resourceFactory;
const MemAdapter = require("@ui5/fs").adapters.Memory;
const typeRepository = require("../types/typeRepository");
const taskRepository = require("../tasks/taskRepository");
const BuildContext = require("./BuildContext");
// Set of tasks for development
const devTasks = [
"replaceCopyright",
"replaceVersion",
"buildThemes"
];
/**
* Calculates the elapsed build time and returns a prettified output
*
* @private
* @param {Array} startTime Array provided by <code>process.hrtime()</code>
* @returns {string} Difference between now and the provided time array as formatted string
*/
function getElapsedTime(startTime) {
const prettyHrtime = require("pretty-hrtime");
const timeDiff = process.hrtime(startTime);
return prettyHrtime(timeDiff);
}
/**
* Creates the list of tasks to be executed by the build process
*
* Sets specific tasks to be disabled by default, these tasks need to be included explicitly.
* Based on the selected build mode (dev|selfContained|preload), different tasks are enabled.
* Tasks can be enabled or disabled. The wildcard <code>*</code> is also supported and affects all tasks.
*
* @private
* @param {object} parameters
* @param {boolean} parameters.dev Sets development mode, which only runs essential tasks
* @param {boolean} parameters.selfContained
* True if a the build should be self-contained or false for prelead build bundles
* @param {boolean} parameters.jsdoc True if a JSDoc build should be executed
* @param {Array} parameters.includedTasks Task list to be included from build
* @param {Array} parameters.excludedTasks Task list to be excluded from build
* @returns {Array} Return a task list for the builder
*/
function composeTaskList({dev, selfContained, jsdoc, includedTasks, excludedTasks}) {
const definedTasks = taskRepository.getAllTaskNames();
let selectedTasks = definedTasks.reduce((list, key) => {
list[key] = true;
return list;
}, {});
// Exclude non default tasks
selectedTasks.generateManifestBundle = false;
selectedTasks.generateStandaloneAppBundle = false;
selectedTasks.transformBootstrapHtml = false;
selectedTasks.generateJsdoc = false;
selectedTasks.executeJsdocSdkTransformation = false;
selectedTasks.generateCachebusterInfo = false;
selectedTasks.generateApiIndex = false;
selectedTasks.generateThemeDesignerResources = false;
// Disable generateResourcesJson due to performance.
// When executed it analyzes each module's AST and therefore
// takes up much time (~10% more)
selectedTasks.generateResourcesJson = false;
if (selfContained) {
// No preloads, bundle only
selectedTasks.generateComponentPreload = false;
selectedTasks.generateStandaloneAppBundle = true;
selectedTasks.transformBootstrapHtml = true;
selectedTasks.generateLibraryPreload = false;
}
// TODO 3.0: exclude generateVersionInfo if not --all is used
if (jsdoc) {
// Include JSDoc tasks
selectedTasks.generateJsdoc = true;
selectedTasks.executeJsdocSdkTransformation = true;
selectedTasks.generateApiIndex = true;
// Include theme build as required for SDK
selectedTasks.buildThemes = true;
// Exclude all tasks not relevant to JSDoc generation
selectedTasks.replaceCopyright = false;
selectedTasks.replaceVersion = false;
selectedTasks.generateComponentPreload = false;
selectedTasks.generateLibraryPreload = false;
selectedTasks.generateLibraryManifest = false;
selectedTasks.createDebugFiles = false;
selectedTasks.uglify = false;
selectedTasks.generateFlexChangesBundle = false;
selectedTasks.generateManifestBundle = false;
}
// Only run essential tasks in development mode, it is not desired to run time consuming tasks during development.
if (dev) {
// Overwrite all other tasks with noop promise
Object.keys(selectedTasks).forEach((key) => {
if (devTasks.indexOf(key) === -1) {
selectedTasks[key] = false;
}
});
}
// Exclude tasks
for (let i = 0; i < excludedTasks.length; i++) {
const taskName = excludedTasks[i];
if (taskName === "*") {
Object.keys(selectedTasks).forEach((sKey) => {
selectedTasks[sKey] = false;
});
break;
}
if (selectedTasks[taskName] === true) {
selectedTasks[taskName] = false;
} else if (typeof selectedTasks[taskName] === "undefined") {
log.warn(`Unable to exclude task '${taskName}': Task is unknown`);
}
}
// Include tasks
for (let i = 0; i < includedTasks.length; i++) {
const taskName = includedTasks[i];
if (taskName === "*") {
Object.keys(selectedTasks).forEach((sKey) => {
selectedTasks[sKey] = true;
});
break;
}
if (selectedTasks[taskName] === false) {
selectedTasks[taskName] = true;
} else if (typeof selectedTasks[taskName] === "undefined") {
log.warn(`Unable to include task '${taskName}': Task is unknown`);
}
}
// Filter only for tasks that will be executed
selectedTasks = Object.keys(selectedTasks).filter((task) => selectedTasks[task]);
return selectedTasks;
}
async function executeCleanupTasks(buildContext) {
log.info("Executing cleanup tasks...");
await buildContext.executeCleanupTasks();
}
function registerCleanupSigHooks(buildContext) {
function createListener(exitCode) {
return function() {
// Asynchronously cleanup resources, then exit
executeCleanupTasks(buildContext).then(() => {
process.exit(exitCode);
});
};
}
const processSignals = {
"SIGHUP": createListener(128 + 1),
"SIGINT": createListener(128 + 2),
"SIGTERM": createListener(128 + 15),
"SIGBREAK": createListener(128 + 21)
};
for (const signal of Object.keys(processSignals)) {
process.on(signal, processSignals[signal]);
}
// == TO BE DISCUSSED: Also cleanup for unhandled rejections and exceptions?
// Add additional events like signals since they are registered on the process
// event emitter in a similar fashion
// processSignals["unhandledRejection"] = createListener(1);
// process.once("unhandledRejection", processSignals["unhandledRejection"]);
// processSignals["uncaughtException"] = function(err, origin) {
// const fs = require("fs");
// fs.writeSync(
// process.stderr.fd,
// `Caught exception: ${err}\n` +
// `Exception origin: ${origin}`
// );
// createListener(1)();
// };
// process.once("uncaughtException", processSignals["uncaughtException"]);
return processSignals;
}
function deregisterCleanupSigHooks(signals) {
for (const signal of Object.keys(signals)) {
process.removeListener(signal, signals[signal]);
}
}
/**
* Builder
*
* @public
* @namespace
* @alias module:@ui5/builder.builder
*/
module.exports = {
/**
* Configures the project build and starts it.
*
* @public
* @param {object} parameters Parameters
* @param {object} parameters.tree Project tree as generated by the
* [@ui5/project.normalizer]{@link module:@ui5/project.normalizer}
* @param {string} parameters.destPath Target path
* @param {boolean} [parameters.cleanDest=false] Decides whether project should clean the target path before build
* @param {boolean} [parameters.buildDependencies=false] Decides whether project dependencies are built as well
* @param {Array.<string|RegExp>} [parameters.includedDependencies=[]]
* List of build dependencies to be included if buildDependencies is true
* @param {Array.<string|RegExp>} [parameters.excludedDependencies=[]]
* List of build dependencies to be excluded if buildDependencies is true.
* If the wildcard '*' is provided, only the included dependencies will be built.
* @param {boolean} [parameters.dev=false]
* Decides whether a development build should be activated (skips non-essential and time-intensive tasks)
* @param {boolean} [parameters.selfContained=false] Flag to activate self contained build
* @param {boolean} [parameters.jsdoc=false] Flag to activate JSDoc build
* @param {Array.<string>} [parameters.includedTasks=[]] List of tasks to be included
* @param {Array.<string>} [parameters.excludedTasks=[]] List of tasks to be excluded.
* If the wildcard '*' is provided, only the included tasks will be executed.
* @param {Array.<string>} [parameters.devExcludeProject=[]] List of projects to be excluded from development build
* @returns {Promise} Promise resolving to <code>undefined</code> once build has finished
*/
async build({
tree, destPath, cleanDest = false,
buildDependencies = false, includedDependencies = [], excludedDependencies = [],
dev = false, selfContained = false, jsdoc = false,
includedTasks = [], excludedTasks = [], devExcludeProject = []
}) {
const startTime = process.hrtime();
log.info(`Building project ${tree.metadata.name}` + (buildDependencies ? "" : " not") +
" including dependencies..." + (dev ? " [dev mode]" : ""));
log.verbose(`Building to ${destPath}...`);
const selectedTasks = composeTaskList({dev, selfContained, jsdoc, includedTasks, excludedTasks});
const fsTarget = resourceFactory.createAdapter({
fsBasePath: destPath,
virBasePath: "/"
});
const buildContext = new BuildContext({rootProject: tree});
const cleanupSigHooks = registerCleanupSigHooks(buildContext);
const projects = {}; // Unique project index to prevent building the same project multiple times
const projectWriters = {}; // Collection of memory adapters of already built libraries
function projectFilter(project) {
function projectMatchesAny(deps) {
return deps.some((dep) => dep instanceof RegExp ?
dep.test(project.metadata.name) : dep === project.metadata.name);
}
// if everything is included, this overrules exclude lists
if (includedDependencies.includes("*")) return true;
let test = !excludedDependencies.includes("*"); // exclude everything?
if (test && projectMatchesAny(excludedDependencies)) {
test = false;
}
if (!test && projectMatchesAny(includedDependencies)) {
test = true;
}
return test;
}
const projectCountMarker = {};
function projectCount(project, count = 0) {
if (buildDependencies) {
count = project.dependencies.filter(projectFilter).reduce((depCount, depProject) => {
return projectCount(depProject, depCount);
}, count);
}
if (!projectCountMarker[project.metadata.name]) {
count++;
projectCountMarker[project.metadata.name] = true;
}
return count;
}
const buildLogger = log.createTaskLogger("🛠 ", projectCount(tree));
function buildProject(project) {
let depPromise;
let projectTasks = selectedTasks;
// Build dependencies in sequence as it is far easier to detect issues and reduces
// side effects or other issues such as too many open files
if (buildDependencies) {
depPromise = project.dependencies.filter(projectFilter).reduce(function(p, depProject) {
return p.then(() => buildProject(depProject));
}, Promise.resolve());
} else {
depPromise = Promise.resolve();
}
// Build the project after all dependencies have been built
return depPromise.then(() => {
if (projects[project.metadata.name]) {
return Promise.resolve();
} else {
projects[project.metadata.name] = true;
}
buildLogger.startWork(`Building project ${project.metadata.name}`);
const projectType = typeRepository.getType(project.type);
const resourceCollections = resourceFactory.createCollectionsForTree(project, {
virtualReaders: projectWriters,
getVirtualBasePathPrefix: function({project, virBasePath}) {
if (project.type === "application" && project.metadata.namespace) {
return "/resources/" + project.metadata.namespace;
}
},
getProjectExcludes: function(project) {
if (project.builder && project.builder.resources) {
return project.builder.resources.excludes;
}
}
});
const writer = new MemAdapter({
virBasePath: "/"
});
// Store project writer as virtual reader for parent projects
// so they can access the build results of this project
projectWriters[project.metadata.name] = writer;
// TODO: Add getter for writer of DuplexColection
const workspace = resourceFactory.createWorkspace({
virBasePath: "/",
writer,
reader: resourceCollections.source,
name: project.metadata.name
});
const projectContext = buildContext.createProjectContext({
project, // TODO 2.0: Add project facade object/instance here
resources: {
workspace,
dependencies: resourceCollections.dependencies
}
});
const TaskUtil = require("../tasks/TaskUtil");
const taskUtil = new TaskUtil({
projectBuildContext: projectContext
});
if (dev && devExcludeProject.indexOf(project.metadata.name) !== -1) {
projectTasks = composeTaskList({dev: false, selfContained, includedTasks, excludedTasks});
}
return projectType.build({
resourceCollections: {
workspace,
dependencies: resourceCollections.dependencies
},
tasks: projectTasks,
project,
parentLogger: log,
taskUtil
}).then(() => {
log.verbose("Finished building project %s. Writing out files...", project.metadata.name);
buildLogger.completeWork(1);
return workspace.byGlob("/**/*.*").then((resources) => {
const tagCollection = projectContext.getResourceTagCollection();
return Promise.all(resources.map((resource) => {
if (tagCollection.getTag(resource, projectContext.STANDARD_TAGS.OmitFromBuildResult)) {
log.verbose(`Skipping write of resource tagged as "OmitFromBuildResult": ` +
resource.getPath());
return; // Skip target write for this resource
}
if (projectContext.isRootProject() && project.type === "application" &&
project.metadata.namespace) {
// Root-application projects only: Remove namespace prefix if given
resource.setPath(resource.getPath().replace(
new RegExp(`^/resources/${project.metadata.namespace}`), ""));
}
return fsTarget.write(resource);
}));
});
});
});
}
try {
if (cleanDest) {
await rimraf(destPath);
}
await buildProject(tree);
log.info(`Build succeeded in ${getElapsedTime(startTime)}`);
} catch (err) {
log.error(`Build failed in ${getElapsedTime(startTime)}`);
throw err;
} finally {
deregisterCleanupSigHooks(cleanupSigHooks);
await executeCleanupTasks(buildContext);
}
}
};
// Export local function for testing only
/* istanbul ignore else */
if (process.env.NODE_ENV === "test") {
module.exports._composeTaskList = composeTaskList;
}