-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGruntfile.js
388 lines (324 loc) · 9.24 KB
/
Gruntfile.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
module.exports = function(grunt) {
/**
* @typedef {function} grunt.option
* @typedef {function} grunt.initConfig
*/
/** possible build :
*
* > build files to prepare pushing on App Script
* grunt build --target=dev
* grunt build --target=prod
*
* grunt build_push --target=prod
*
*//**/
// define target and config to run the task with
const TARGET = grunt.option('target') || 'dev';
/**
* Load config file directly
*
* @type {{
* clasp: {
* scriptId: string
* },
* script_manifest: {},
* context: {}
* }}
*/
let CONFIG;
//<editor-fold desc="# Prepare CONFIG object">
{
try {
CONFIG = require(`./build/config/${TARGET}_config`);
}
catch(e){
grunt['fail'].fatal(`\x1b[31mERROR: "\x1b[0m\x1b[41m\x1b[30m${TARGET}\x1b[31m\x1b[0m\x1b[31m" is not a valid target build\x1b[0m`);
// not needed, grunt.fail.fatal already exits
return false;
}
// Stringify non-string key in .context
let context = JSON.parse(JSON.stringify(CONFIG.context));
for (let key in context){
if (typeof context[key] === 'string') continue;
context[key] = JSON.stringify(context[key]);
}
CONFIG.context = context;
}
//</editor-fold>
// init config object
grunt.initConfig({
// task
clean: {
'build': {
files: [
{
expand: true,
cwd: 'build/src/', // build source folder
src: [
'**/*' // Wipe everything
]
}
]
}
},
copy:{
'build': {
files: [{
expand: true,
cwd: 'src/',
src: [
'**/*.gs',
'**/*.js',
'**/*.html',
'appsscript.json',
],
dest: 'build/src/',
flatten: false,
filter: 'isFile',
'rename': (dest, src) => dest + src.replace(/\.gs\.js$/, '.js'),
}]
},
'dependencies': {
get files(){
if (this._cachedFiles) return this._cachedFiles;
// custom task to copy the package dependencies to build output
let files = [];
let {dependencies} = require('./package');
// Allows access to saved packages information
this.options.process = this.options.process.bind(this.options);
// for every dependency package, build src and dest rules
for (let pkgName in dependencies){
// retrieve installed package version
let {version} = require(`./node_modules/${pkgName}/package`);
// save package info
this.options._pkg[pkgName] = {
name: pkgName,
version: version,
};
files.push({
expand: true,
cwd: `node_modules/${pkgName}/src/`,
src: [
'**/*.gs',
'**/*.js',
],
dest: `build/src/lib/${pkgName}/`,
flatten: false, // set flatten to false once we use clasp folder name
filter: 'isFile',
'rename': (dest, src) => dest + src.replace(/\.gs\.js$/, '.js'),
});
}
// Save files to only process them once (they should not change in between calls)
this._cachedFiles = files;
return files;
},
options: {
_pkg: {},
/**
* Add header with library information
*
* @param {string} content
* @param {string} srcPath
*/
process: function (content, srcPath) {
// find pkg
let [/*res*/, pkg] = /^node_modules\/(.+?)\/src\//.exec(srcPath) || [];
if (!pkg) return content;
let {name, version} = this._pkg[pkg];
let header = `/**
* package: ${name}
* version: ${version}
*/`;
return `${header}\n\n${content}`;
}
}
}
},
jsonPatch: {
'build': {
srcFolder: 'build/src/',
destFolder: 'build/src/',
files: [
{
src: '.clasp.json',
dest: '.clasp.json',
data: CONFIG.clasp,
},
{
src: 'appsscript.json',
dest: 'appsscript.json',
data: CONFIG.script_manifest || {},
},
],
},
},
preprocess: {
'js': {
options: {
context : CONFIG.context,
type: 'js',
},
files: [{
expand: true,
cwd: 'build/src/',
src: [
'**/*.js',
'**/*.js.html',
],
dest: 'build/src/',
}],
},
},
clasp: {
'push': {
runDir: 'build/src',
command: 'push',
},
'version': {
runDir: 'build/src',
command: 'version',
},
},
});
// load tasks
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-preprocess');
/**
* custom task to patch *.json or multiple *.json
*/
grunt.registerMultiTask('jsonPatch', 'Update properties in *.json file or multiple json files', function(){
// Check if there are files to patch
if (!this || !this.data || (!this.files && (!this.data.src || !this.data.dest))) return;
let srcFolder = this.data['srcFolder'] || '';
let destFolder = this.data['destFolder'] || '';
/**
* Load a <src> JSON file, patch it with <data>, save it to <target>
*
* @param {string} src
* @param {string} target
* @param {Object} data
*/
function updateJsonFile(src, target, data) {
let config = {};
// read config file
try { config = grunt.file.readJSON(srcFolder + src) }
catch (e) {}
// update the provided parameters
for (let key in data) {
let path = key.split('/'),
configDrillDown = config;
for (let i = 0; i < path.length - 1; i++) {
// in case the path doesn't exist, create it. ONLY create object
if (configDrillDown[path[i]] === undefined) {
// Add array element at the end
if (Array.isArray(configDrillDown) && path[i] === '-1') {
path[i] = configDrillDown.push({}) - 1;
}
// Create Array of (-1) is used and object is empty (newly created)
else if (Object.keys(configDrillDown).length === 0 && path[i] === '-1') {
configDrillDown = [{}];
path[i] = 0;
}
else {
configDrillDown[path[i]] = {};
}
}
configDrillDown = configDrillDown[path[i]];
}
let i = path.length - 1;
if (configDrillDown[path[i]] === undefined) {
// Add array element at the end
if (Array.isArray(configDrillDown) && path[i] === '-1') {
path[i] = configDrillDown.push({}) - 1;
}
// Create Array of (-1) is used and object is empty (newly created)
else if (Object.keys(configDrillDown).length === 0 && path[i] === '-1') {
configDrillDown = [{}];
path[i] = 0;
}
}
configDrillDown[path[i]] = data[key];
}
// write updated config
grunt.file.write(destFolder + target, JSON.stringify(config, null, '\t'));
}
// Init files object
let files = this.data.files || [{
src: this.files[0].src[0],
dest: this.files[0].dest,
data: this.data.data
}];
// Patch every JSON files
files.forEach(({src, dest, data}) => updateJsonFile(src, dest, data));
});
/**
* Use clasp
*/
grunt.registerMultiTask('clasp', 'push content in script, and create a version', function(){
const child_process = require('child_process');
/**
* @type {{
* command: string,
* runDir: string
* }}
*/
let param = this.data;
function clasp(cmd){
let res = child_process.execSync(`clasp ${cmd}`, {
cwd: __dirname +'/'+ param.runDir
});
// Get string res
return res.toString();
}
switch (param.command){
case 'push':
// Push
console.log('Pushing files to the script');
let pushRes = clasp('push');
// Check result
let resPush = /Pushed\s(\d+)\sfiles\./.exec(pushRes);
if (!resPush) throw 'Error while pushing files to AppsScript';
console.log(`Pushed files: ${resPush[1]}`);
break;
case 'version':
// create a new version
console.log('Creating new script version');
let versionRes = clasp('version');
// Check result and get version num
let resVers = /version\s(\d+)/.exec(versionRes);
if (!resVers) throw 'Error while creating new version';
let versionNum = +resVers[1];
console.log('New version num: ' + versionNum);
// Update version value:
!CONFIG.publishing && (CONFIG['publishing'] = {});
CONFIG.publishing.version = versionNum;
break;
}
});
// NEVER name the task as the configurator object
// the default task can be run just by typing "grunt" on the command line
// USE THIS when multiple tasks must be chained
grunt.registerTask('build', [
'clean:build',
'copy:build',
'preprocess:js',
'jsonPatch:build',
'copy:dependencies',
]);
grunt.registerTask('push', [
'clasp:push',
]);
grunt.registerTask('build_push', [
'build',
'push',
]);
// define default task (for grunt alone)
grunt.registerTask('default', ['build']);
/**
* NOTES:
*
* - Beware of comments in JSON files, no comments can exists in JSON processed by config task
*
*/
};