-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathhelpers.js
More file actions
415 lines (354 loc) · 15 KB
/
helpers.js
File metadata and controls
415 lines (354 loc) · 15 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
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 _ = require('underscore');
const fs = require('fs-extra');
const path = require('path');
// extends grunt.file.expand with { order: cb(filePaths) }
require('grunt-file-order');
const Framework = require('./helpers/Framework');
module.exports = function(grunt) {
const convertSlashes = /\\/g;
// grunt tasks
grunt.registerTask('_log-server', 'Logs out user-defined build variables', function() {
grunt.log.ok(`Starting server in '${grunt.config('outputdir')}' using port ${grunt.config('connect.server.options.port')}`);
});
grunt.registerTask('_log-vars', 'Logs out user-defined build variables', function() {
const includes = grunt.config('includes');
const excludes = grunt.config('excludes');
const productionExcludes = grunt.config('productionExcludes');
if (includes && excludes) {
grunt.fail.fatal('Cannot specify includes and excludes. Please check your config.json configuration.');
}
if (includes) {
const count = includes.length;
grunt.log.writeln('The following will be included in the build:');
for (let i = 0; i < count; i++) { grunt.log.writeln('- ' + includes[i]); }
grunt.log.writeln('');
}
if (excludes) {
const count = excludes.length;
grunt.log.writeln('The following will be excluded from the build:');
for (let i = 0; i < count; i++) { grunt.log.writeln('- ' + excludes[i]); }
grunt.log.writeln('');
}
if (productionExcludes) {
const count = productionExcludes.length;
grunt.log.writeln('The following will be excluded from the build in production:');
for (let i = 0; i < count; i++) { grunt.log.writeln('- ' + productionExcludes[i]); }
grunt.log.writeln('');
}
grunt.log.ok(`Using source at '${grunt.config('sourcedir')}'`);
grunt.log.ok(`Building to '${grunt.config('outputdir')}'`);
if (grunt.config('theme') !== '**') grunt.log.ok(`Using theme '${grunt.config('theme')}'`);
if (grunt.config('menu') !== '**') grunt.log.ok(`Using menu ${grunt.config('menu')}'`);
if (grunt.config('languages') !== '**') grunt.log.ok(`The following languages will be included in the build '${grunt.config('languages')}'`);
});
// privates
const generateIncludedRegExp = function() {
const includes = grunt.config('includes') || [];
const pluginTypes = exports.defaults.pluginTypes;
// Return a more specific plugin regExp including src path.
const re = _.map(includes, function(plugin) {
return _.map(pluginTypes, function(type) {
// eslint-disable-next-line no-useless-escape
return exports.defaults.sourcedir + type + '\/' + plugin + '\/';
}).join('|');
}).join('|');
// eslint-disable-next-line no-useless-escape
const core = exports.defaults.sourcedir + 'core\/';
return new RegExp(core + '|' + re, 'i');
};
const generateNestedIncludedRegExp = function() {
const includes = grunt.config('includes') || [];
const folderRegEx = 'less/plugins';
// Return a more specific plugin regExp including src path.
const re = _.map(includes, function(plugin) {
// eslint-disable-next-line no-useless-escape
return exports.defaults.sourcedir + '([^\/]*)\/([^\/]*)\/' + folderRegEx + '\/' + plugin + '\/';
}).join('|');
return new RegExp(re, 'i');
};
const generateExcludedRegExp = function() {
const excludes = grunt.config('excludes') || [];
if (grunt.config('type') === 'production') {
const productionExcludes = grunt.config('productionExcludes') || [];
excludes.push(...productionExcludes);
}
const pluginTypes = exports.defaults.pluginTypes;
// Return a more specific plugin regExp including src path.
const re = _.map(excludes, function(plugin) {
return _.map(pluginTypes, function(type) {
// eslint-disable-next-line no-useless-escape
return exports.defaults.sourcedir + type + '\/' + plugin + '\/';
}).join('|');
}).join('|');
return new RegExp(re, 'i');
};
const generateScriptSafeRegExp = function() {
const includes = grunt.config('scriptSafe') || [];
let re = '';
const count = includes.length;
for (let i = 0; i < count; i++) {
// eslint-disable-next-line no-useless-escape
re += '\/' + includes[i].toLowerCase() + '\/';
if (i < includes.length - 1) re += '|';
}
return new RegExp(re, 'i');
};
const appendSlash = function(dir) {
if (dir) {
const lastChar = dir.substring(dir.length - 1, dir.length);
if (lastChar !== path.sep) return dir + path.sep;
}
};
// eslint-disable-next-line no-unused-vars
const includedProcess = function(content, filepath) {
if (!exports.isPathIncluded(filepath)) return '';
else return content;
};
const getIncludedRegExp = function() {
const configValue = grunt.config('includedRegExp');
return configValue || grunt.config('includedRegExp', generateIncludedRegExp());
};
const getNestedIncludedRegExp = function() {
const configValue = grunt.config('nestedIncludedRegExp');
return configValue || grunt.config('nestedIncludedRegExp', generateNestedIncludedRegExp());
};
const getExcludedRegExp = function() {
const configValue = grunt.config('excludedRegExp');
return configValue || grunt.config('excludedRegExp', generateExcludedRegExp());
};
const getScriptSafeRegExp = function() {
const configValue = grunt.config('scriptSafeRegExp');
return configValue || grunt.config('scriptSafeRegExp', generateScriptSafeRegExp());
};
// exported
const exports = {
defaults: {
sourcedir: 'src/',
outputdir: 'build/',
coursedir: 'course',
configdir: null,
cachepath: null,
jsonext: 'json',
theme: '**',
menu: '**',
languages: '**',
includes: [
],
pluginTypes: [
'components',
'extensions',
'menu',
'theme'
],
scriptSafe: [
'adapt-contrib-xapi',
'adapt-contrib-spoor'
]
},
getIncludes: function(buildIncludes, configData) {
const dependencies = [];
// Iterate over the plugin types.
for (let i = 0; i < exports.defaults.pluginTypes.length; i++) {
const pluginTypeDir = path.join(configData.sourcedir, exports.defaults.pluginTypes[i]);
// grab a list of the installed (and included) plugins for this type
const plugins = _.intersection(fs.readdirSync(pluginTypeDir), buildIncludes);
for (let j = 0; j < plugins.length; j++) {
try {
const bowerJson = grunt.file.readJSON(path.join(pluginTypeDir, plugins[j], 'bower.json'));
for (const key in bowerJson.dependencies) {
if (!_.contains(buildIncludes, key)) dependencies.push(key);
}
} catch (error) {
grunt.log.error(error);
}
}
}
return [].concat(exports.defaults.includes, buildIncludes, dependencies);
},
generateConfigData: function({
rootDir = __dirname.split(path.sep).slice(0, -1).join(path.sep)
} = {}) {
const localConfigPath = exports.getLocalConfig();
const localConfig = localConfigPath
? fs.readJSONSync(localConfigPath)
: {};
const defaults = Object.assign({}, exports.defaults, localConfig);
const root = rootDir;
const adaptJSON = fs.readJSONSync(`${root}/adapt.json`);
const sourcedir = appendSlash(grunt.option('sourcedir')) || defaults.sourcedir;
const outputdir = appendSlash(grunt.option('outputdir')) || defaults.outputdir;
const cachepath = grunt.option('cachepath') || null;
const tempdir = outputdir + '.temp/';
const jsonext = grunt.option('jsonext') || adaptJSON.jsonext || defaults.jsonext;
const coursedir = grunt.option('coursedir') || adaptJSON.coursedir || defaults.coursedir;
let languageFolders = '';
if (grunt.option('languages') && grunt.option('languages').split(',').length > 1) {
languageFolders = '{' + grunt.option('languages') + '}';
} else {
languageFolders = grunt.option('languages');
}
// Selectively load the course.json ('outputdir' passed by server-build)
const configDir = grunt.option('outputdir') ? outputdir : defaults.configdir ?? sourcedir;
// add root path if necessary, and point to course/config.json
const configPath = path.join(path.resolve(root, configDir), coursedir, 'config.' + jsonext);
let buildConfig = {};
try {
buildConfig = grunt.file.readJSON(configPath).build || {};
} catch (error) {}
const isDevelopmentBuild = process.argv.some(arg => (arg === 'dev' || arg.includes(':dev') || arg.includes('--dev')));
const cacheAge = isNaN(grunt.option('cacheage'))
? 7 * 24 * 60 * 60 * 1000 // one week
: parseInt(grunt.option('cacheage'));
const data = {
type: isDevelopmentBuild ? 'development' : 'production',
root,
sourcedir,
outputdir,
configdir: configDir,
coursedir,
cachepath,
tempdir,
jsonext,
trackingIdType: grunt.option('trackingidtype') || 'block',
theme: grunt.option('theme') || defaults.theme,
menu: grunt.option('menu') || defaults.menu,
languages: languageFolders || defaults.languages,
scriptSafe: defaults.scriptSafe,
strictMode: false,
targets: buildConfig.targets || '',
cacheAge,
timestamp: isDevelopmentBuild ? 0 : Date.now()
};
if (buildConfig.jsonext) data.jsonext = buildConfig.jsonext;
if (buildConfig.includes?.length) data.includes = exports.getIncludes(buildConfig.includes, data);
if (buildConfig.excludes?.length) data.excludes = buildConfig.excludes;
if (buildConfig.productionExcludes?.length) data.productionExcludes = buildConfig.productionExcludes;
if (buildConfig.scriptSafe) {
data.scriptSafe = buildConfig.scriptSafe.split(',').map(function(item) {
return item.trim();
});
}
if (Object.hasOwn(buildConfig, 'strictMode')) data.strictMode = buildConfig.strictMode;
const framework = new Framework({
rootPath: data.root,
outputPath: data.outputdir,
sourcePath: data.sourcedir,
courseDir: data.coursedir,
includedFilter: exports.includedFilter,
jsonext: data.jsonext,
trackingIdType: data.trackingIdType,
useOutputData: Boolean(grunt.option('outputdir')),
log: grunt.log.ok,
warn: grunt.log.error
});
framework.load();
data.availableLanguageNames = [];
try {
data.availableLanguageNames = framework.getData().languageNames;
} catch (err) {}
return data;
},
/*
* Uses the parent folder name (menu, theme, components, extensions).
* Also caches a list of the installed plugins
* assumption: all folders are plugins
*/
getInstalledPluginsByType: function(type) {
const pluginDir = grunt.config('sourcedir') + type + '/';
if (!grunt.file.isDir(pluginDir)) return []; // fail silently
// return all sub-folders, and save for later
return grunt.option(type, grunt.file.expand({
filter: 'isDirectory',
cwd: pluginDir
}, '*'));
},
isPluginInstalled: function(pluginName) {
const types = ['components', 'extensions', 'theme', 'menu'];
for (let i = 0, len = types.length; i < len; i++) {
const plugins = grunt.option(types[i]) || this.getInstalledPluginsByType(types[i]);
if (plugins.indexOf(pluginName) !== -1) return true;
}
return false;
},
isPathIncluded: function(pluginPath) {
pluginPath = pluginPath.replace(convertSlashes, '/');
const includes = grunt.config('includes');
const excludes = grunt.config('excludes') || (grunt.config('type') === 'production' && grunt.config('productionExcludes'));
// carry on as normal if no includes/excludes
if (!includes && !excludes) return true;
// Very basic check to see if the file path string contains any
// of the included list of plugin string names.
const isIncluded = includes && pluginPath.search(getIncludedRegExp()) !== -1;
const isExcluded = excludes && pluginPath.search(getExcludedRegExp()) !== -1;
// Exclude any plugins that don't match any part of the full file path string.
if (isExcluded || isIncluded === false) {
return false;
}
// Check the LESS plugins folder exists.
// The LESS 'plugins' folder doesn't exist, so add the file,
// as the plugin has already been found in the previous check.
const nestedPluginsPath = !!pluginPath.match(/(?:.)+(?:\/less\/plugins)/g);
if (!nestedPluginsPath) {
return true;
}
// The LESS 'plugins' folder exists, so check that any plugins in this folder are allowed.
const hasPluginSubDirectory = !!pluginPath.match(getNestedIncludedRegExp());
if (hasPluginSubDirectory) {
return true;
}
// File might be in the included plugin/less/plugins directory,
// but the naming convention or directory structure is not correct.
return false;
},
isPluginScriptSafe: function(pluginPath) {
pluginPath = pluginPath.replace(convertSlashes, '/');
const includes = grunt.config('scriptSafe');
const isExplicitlyDefined = (includes && pluginPath.search(getScriptSafeRegExp()) !== -1);
const isIncluded = grunt.option('allowscripts') || includes[0] === '*' || isExplicitlyDefined;
return isIncluded;
},
includedFilter: function(filepath) {
return exports.isPathIncluded(filepath);
},
scriptSafeFilter: function(filepath) {
return exports.isPluginScriptSafe(filepath);
},
/** @returns {Framework} */
getFramework: function({
useOutputData = Boolean(grunt.option('outputdir')),
rootDir = process.cwd()
} = {}) {
const buildConfig = exports.generateConfigData({ rootDir });
const framework = new Framework({
rootPath: buildConfig.root,
outputPath: buildConfig.outputdir,
sourcePath: buildConfig.sourcedir,
courseDir: buildConfig.coursedir,
includedFilter: exports.includedFilter,
jsonext: buildConfig.jsonext,
trackingIdType: buildConfig.trackingIdType,
useOutputData,
log: grunt.log.ok,
warn: grunt.log.error
});
framework.load();
return framework;
},
getLocalConfig: function() {
if (Object.hasOwn(this, '_localConfigPath')) return this._localConfigPath;
const fileName = '.adaptrc.json';
let currentDir = path.resolve(process.cwd()).replace(convertSlashes, '/');
while (currentDir.split('/').filter(Boolean).length > 0) {
const filePath = `${currentDir}/${fileName}`;
if (fs.existsSync(filePath)) {
grunt.log.ok(`Using: ${filePath}`);
this._localConfigPath = filePath;
return filePath;
}
currentDir = currentDir.split('/').slice(0, -1).join('/');
}
return (this._localConfigPath = null);
}
};
return exports;
};