-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathhelpers.js
More file actions
313 lines (270 loc) · 11.1 KB
/
helpers.js
File metadata and controls
313 lines (270 loc) · 11.1 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
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('adapt-project');
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')}'`);
});
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;
}
};
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: Date.now()
};
if (buildConfig.jsonext) data.jsonext = buildConfig.jsonext;
if (buildConfig.includes) data.includes = exports.getIncludes(buildConfig.includes, data);
if (buildConfig.excludes) data.excludes = buildConfig.excludes;
if (buildConfig.productionExcludes) 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,
jsonext: data.jsonext,
trackingIdType: data.trackingIdType,
useOutputData: Boolean(grunt.option('outputdir')),
usePackageJSON: false,
schemaVersion: '0.1.0',
specifiedMenus: data.menu === '**' ? null : [data.menu],
specifiedThemes: data.theme === '**' ? null : [data.theme],
log: grunt.log.ok,
warn: grunt.log.error
});
framework.load();
exports.includedFilter = framework.includedFilter;
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;
},
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;
},
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,
jsonext: buildConfig.jsonext,
trackingIdType: buildConfig.trackingIdType,
useOutputData,
usePackageJSON: false,
schemaVersion: '0.1.0',
specifiedMenus: buildConfig.menu === '**' ? null : [buildConfig.menu],
specifiedThemes: buildConfig.theme === '**' ? null : [buildConfig.theme],
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;
};