-
Notifications
You must be signed in to change notification settings - Fork 10
/
Gruntfile.js
366 lines (326 loc) · 14.5 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
/*
Copyright (c) 2023 The Gamepad Navigator Authors
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-lab/gamepad-navigator/raw/main/AUTHORS.md.
Licensed under the BSD 3-Clause License. You may not use this file except in
compliance with this License.
You may obtain a copy of the BSD 3-Clause License at
https://github.com/fluid-lab/gamepad-navigator/blob/main/LICENSE
*/
/* eslint-env node */
"use strict";
var fetch = require("node-fetch");
require("dotenv").config({ path: ".gruntfile.env" });
var path = require("path"),
fs = require("fs");
module.exports = function (grunt) {
grunt.config.init({
usebanner: {
options: {
licenseBanner: grunt.file.read("templates/LICENSE-banner.txt"),
currentMarkdownBanner: /^(<!--)\s[\w\W]+?(-->)\s\s/m,
currentJsAndJson5Banner: /^\/\*\sCopyright \(c\)[\w\W]+?\s\*\/\s\s/m
},
jsAndJson5: {
options: {
replace: "<%= usebanner.options.currentJsAndJson5Banner %>",
banner: "/*\n<%= usebanner.options.licenseBanner %>*/\n"
},
files: {
src: ["./src/js/**/*.js", "tests/js/**/*.js", "./*.js", "./*.json5", "tests/**/*.json5"]
}
},
markdown: {
options: {
replace: "<%= usebanner.options.currentMarkdownBanner %>",
banner: "<!--\n<%= usebanner.options.licenseBanner %>-->\n"
},
files: {
src: ["./*.md", "tests/**/*.md", "docs/**/*.md"]
}
}
},
clean: {
previousBuild: {
src: ["dist/"]
},
zip: {
src: ["*.zip"]
}
},
copy: {
infusion: {
expand: true,
flatten: true,
src: "node_modules/infusion/dist/infusion-all.js",
dest: "dist/js/lib/infusion/"
},
ally: {
expand: true,
flatten: true,
src: "node_modules/ally.js/ally.min.js",
dest: "dist/js/lib/ally/"
},
oskCss: {
expand: true,
flatten: true,
src: "node_modules/fluid-osk/src/css/*",
dest: "dist/css/lib/fluid-osk"
},
oskJs: {
expand: true,
flatten: true,
src: "node_modules/fluid-osk/src/js/*",
dest: "dist/js/lib/fluid-osk"
},
source: {
expand: true,
cwd: "src",
src: "**",
dest: "dist/"
}
},
packageJSON: grunt.file.readJSON("package.json"),
updateVersion: {
options: { jsonFiles: ["package.json", "src/manifest.json"] }
},
jsonprettify: {
options: { space: 4 },
all: { src: ["package.json", "src/manifest.json"] }
},
compress: {
dist: {
options: { archive: "build_v<%= packageJSON.version %>.zip" },
files: [{
expand: true,
cwd: "dist/",
src: "**/*"
}]
}
},
prompt: {
newRelease: {
options: {
questions: [{
config: "githubRelease.options.tag_name",
type: "input",
default: "v<%= packageJSON.version %>",
message: "Tag version:"
}, {
config: "githubRelease.options.name",
type: "input",
default: "v<%= packageJSON.version %>",
message: "Release title:"
}, {
config: "githubRelease.options.body",
type: "input",
message: "Tag description:",
suffix: "Can be changed anytime on GitHub"
}, {
config: "githubRelease.options.prerelease",
type: "confirm",
message: "Pre-release:"
}, {
config: "githubRelease.options.draft",
type: "confirm",
default: false,
message: "Draft:"
}]
}
}
},
githubRelease: {
options: {
repo: "fluid-lab/gamepad-navigator",
asset: "build_v<%= packageJSON.version %>.zip"
}
}
});
grunt.registerTask("updateVersion", "Update the manifest.json and package.json version.", function () {
// Reference to the function triggered when the asynchronous task is completed.
var done = this.async();
// Obtain the list of JSON files to be updated.
var jsonFiles = this.options().jsonFiles;
// Check the version increment type and whether the release is "standard".
var specIndexToIncrease = null,
isStandard = grunt.option.flags().includes("--standard");
if (grunt.option.flags().includes("--major")) {
specIndexToIncrease = 0;
}
else if (grunt.option.flags().includes("--minor")) {
specIndexToIncrease = 1;
}
else if (grunt.option.flags().includes("--patch")) {
specIndexToIncrease = 2;
}
// Scan the JSON files provided as options.
fluid.each(jsonFiles, function (jsonFile) {
// Verify that the file exists.
if (!grunt.file.exists(jsonFile)) {
grunt.log.error(jsonFile + " is not a valid file.");
return;
}
var currentVersion = grunt.file.readJSON(jsonFile).version,
versionNumber = currentVersion.split("-", 1)[0],
versionSpecs = fluid.transform(versionNumber.split("."), function (versionString) {
return parseInt(versionString);
});
// Update the version number if update-type flag is supplied.
if (specIndexToIncrease) {
versionSpecs[specIndexToIncrease]++;
for (var index = specIndexToIncrease + 1; index < 3; index++) {
versionSpecs[index] = 0;
}
}
var newVersionNumber = versionSpecs.join(".").toString(),
newVersion = newVersionNumber;
if (!isStandard && path.basename(jsonFile) !== "manifest.json") {
newVersion = newVersion + "-dev";
}
// Update the JSON file with the latest version.
var jsonFileData = grunt.file.readJSON(jsonFile);
jsonFileData.version = newVersion;
grunt.file.write(jsonFile, JSON.stringify(jsonFileData));
});
// Prettify the concatenated JSON files.
grunt.task.run("jsonprettify");
done();
});
/**
* TODO: Create a grunt plugin replacing the current "githubRelease" task.
* (might be of interest to the community)
*/
grunt.registerTask("githubRelease", "Task for automated GitHub releases.", function () {
// Reference to the function triggered when the asynchronous task is completed.
var done = this.async();
// Verify that the authentication token has been supplied correctly.
if (!process.env.GITHUB_ACCESS_TOKEN) {
grunt.log.error("GitHub access token cannot be found.");
return;
}
grunt.log.subhead("Connecting...");
var apiUrl = "https://api.github.com",
uploadUrl = "https://uploads.github.com";
var taskOptions = this.options(),
repo = taskOptions.repo,
responseStatus = null;
var releaseUrl = apiUrl + "/repos/" + repo + "/releases";
fetch(releaseUrl, { headers: { "Authorization": "Token " + process.env.GITHUB_ACCESS_TOKEN } })
.then(function (response) {
responseStatus = response.status;
// Verify that the repository is accessible.
if (responseStatus !== 200) {
if (responseStatus === 404) {
throw new Error("Could not find the repository: https://github.com/" + taskOptions.owner + "/" + taskOptions.repo);
}
else {
throw new Error("Could not connect to the repository.");
}
}
grunt.log.ok("The connection has been established.");
// Create a release if the repository is accessible.
grunt.log.subhead("Creating new release \"" + taskOptions.tag_name + "\" on GitHub...");
createRelease(uploadReleaseAsset, taskOptions);
})
.catch(function (errorMessage) { // eslint-disable-line
grunt.log.error(errorMessage);
// Indicate that the task has completed due to failure.
done();
});
// Creates a release in the repository.
var createRelease = function (callback, taskOptions) {
var requestData = {
method: "POST",
headers: { "Authorization": "Token " + process.env.GITHUB_ACCESS_TOKEN },
body: JSON.stringify({
tag_name: taskOptions.tag_name,
name: taskOptions.name,
body: taskOptions.body,
draft: taskOptions.draft,
prerelease: taskOptions.prerelease
})
};
var createReleaseStatus = null;
fetch(releaseUrl, requestData)
.then(function (response) {
createReleaseStatus = response.status;
return response.json();
})
.then(function (responseData) {
// Announce failure if the release could not be created.
if (createReleaseStatus !== 201) {
if (createReleaseStatus === 422 && responseData.errors[0].code === "already_exists") {
throw new Error("A release with the tag \"" + taskOptions.tag_name + "\" already exists.");
}
else {
throw new Error("The release could not be created.");
}
}
// Update the user that the release has been created.
grunt.log.ok("The release has been created at " + responseData.html_url);
// Start uploading the asset file to the created release.
grunt.log.subhead("Scanning and uploading asset file \"" + taskOptions.asset + "\"...");
callback(responseData.id, taskOptions);
})
.catch(function (createReleaseError) { // eslint-disable-line
grunt.log.error(createReleaseError);
// Indicate that the task has completed due to failure.
done();
});
};
// Uploads the asset file to the newly-created release.
var uploadReleaseAsset = function (releaseId, taskOptions) {
// Check if the asset file exists.
if (!grunt.file.exists(taskOptions.asset)) {
throw new Error("The asset file \"" + taskOptions.asset + "\" does not exist.");
}
// Check if the file is in "zip" format.
if (!taskOptions.asset.includes(".zip")) {
throw new Error("The asset\"" + taskOptions.asset + "\" is not a \"zip\" file.");
}
// Obtain characteristics of the asset file.
fs.stat(taskOptions.asset, function (error, stats) {
// Read the "zip" file from the system.
var assetStream = fs.createReadStream(taskOptions.asset);
// Set the URL and the request parameters for asset upload.
var assetUploadUrl = uploadUrl + "/repos/" + repo + "/releases/" + releaseId + "/assets?name=" + path.basename(taskOptions.asset),
assetRequestData = {
method: "POST",
headers: {
"content-type": "application/zip",
"content-length": stats.size,
"Authorization": "Token " + process.env.GITHUB_ACCESS_TOKEN
},
body: assetStream
};
// Upload the asset file.
fetch(assetUploadUrl, assetRequestData)
.then(function (response) {
// Register failure in the "Upload Asset" process.
if (response.status !== 201) {
throw new Error("The asset file \"" + taskOptions.asset + "\" could not be uploaded.");
}
// Indicate that the task has completed.
grunt.log.ok("The asset file \"" + taskOptions.asset + "\" has been uploaded.");
done();
})
.catch(function (assetUploadError) { // eslint-disable-line
grunt.log.error(assetUploadError);
// Indicate that the task has completed due to failure.
done();
});
});
};
});
grunt.loadNpmTasks("grunt-banner");
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks("grunt-contrib-copy");
grunt.loadNpmTasks("grunt-contrib-compress");
grunt.loadNpmTasks("grunt-prompt");
grunt.loadNpmTasks("grunt-json-prettify");
grunt.registerTask("banner", "Add copyright banner at the top of files.", ["usebanner"]);
grunt.registerTask("build", "Build an unpacked extension.", ["clean", "copy"]);
grunt.registerTask("archive", "Generate an zip package of the extension.", ["build", "compress"]);
grunt.registerTask("release", "Create a new release on GitHub and upload the extension's zip file.", ["archive", "prompt", "githubRelease"]);
grunt.registerTask("default", ["banner", "build"]);
};