forked from mozilla/webdev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
380 lines (341 loc) · 11.3 KB
/
gulpfile.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
var argv = require('yargs').argv;
var async = require('async');
var babel = require('gulp-babel');
var del = require('del');
var deploy = require('gulp-gh-pages');
var dotenv = require('dotenv');
var fs = require('fs');
var GitHubApi = require("github");
var gitRev = require('git-rev');
var gulp = require('gulp');
var gutil = require('gulp-util');
var jsonschema = require('jsonschema');
var myth = require('gulp-myth');
var nunjucksRender = require('gulp-nunjucks-render');
var plumber = require('gulp-plumber');
var ProgressBar = require('progress');
var request = require('request');
var serve = require('gulp-serve');
var util = require('util');
var CONTRIBUTE_JSON_URL = 'https://raw.githubusercontent.com/%s/%s/master/contribute.json';
var CONTRIBUTE_JSON_SCHEMA = 'https://raw.githubusercontent.com/mozilla/contribute.json/master/schema.json';
// Set up Github API connection if necessary.
dotenv.load();
var github = new GitHubApi({
version: '3.0.0',
});
if (process.env.GITHUB_USERNAME && process.env.GITHUB_PASSWORD) {
github.authenticate({
type: 'basic',
username: process.env.GITHUB_USERNAME,
password: process.env.GITHUB_PASSWORD,
});
}
/**
* Run a local development server. The site is re-generated
* automatically when changes are made.
*/
gulp.task('serve', ['build'], function() {
var watcher = gulp.watch('./src/**/*', ['build']);
watcher.on('change', function(event) {
gutil.log(gutil.colors.cyan('Change detected, rebuilding.'));
});
// Wish I had a better way of doing this.
return serve({
root: 'build',
port: 8000,
})();
});
/**
* Build a projects.json file annotated with data pulled from Github and other
* sources.
*/
gulp.task('build.projectdata', function(callback) {
// Ensure the build directory exists.
try {
fs.mkdirSync('build');
} catch (err) {}
// If the list has been updated in the past 24 hours, don't bother updating.
// Unless we're being forced to, that is.
if (!argv.force) {
try {
var oldProjects = JSON.parse(fs.readFileSync('build/projects.json'));
var lastUpdated = new Date(oldProjects.lastUpdated);
if (lastUpdated - Date.now() < (24 * 60 * 60 * 1000)) {
gutil.log(gutil.colors.yellow('Projects are up-to-date, skipping re-generation.'));
return callback();
}
} catch (err) {
// Any failure in checking the old projects means we need to
// regenerate anyway.
}
}
var projects = loadProjects();
projects.lastUpdated = Date.now();
// Annnotate the projects with extra data and s
async.each(allProjects(projects), annotateProject, function(err) {
if (err) {
console.error('Error annotating projects.');
console.error(err);
callback(err);
} else {
fs.writeFileSync('build/projects.json', JSON.stringify(projects));
callback();
}
});
});
/**
* Build HTML files by running them through nunjucks.
*/
gulp.task('build.templates', ['build.projectdata'], function() {
nunjucksRender.nunjucks.configure(['src']);
var projects = JSON.parse(fs.readFileSync('build/projects.json'));
var githubProjects = allProjects(projects, function(p) {return p.github;});
githubProjects.sort(function(a, b) {
return b.github.stars - a.github.stars;
});
var ctx = {
projects: githubProjects,
thisYear: new Date().getFullYear(),
now: new Date(),
};
return gulp.src('./src/index.html')
.pipe(plumber())
.pipe(nunjucksRender(ctx))
.pipe(gulp.dest('./build'));
});
/**
* Copy other files over to the build directory.
*/
gulp.task('build.static', function() {
return gulp.src(['./src/font/**/*',
'./src/img/**/*',
'./src/js/lib/**/*'],
{base: './src'})
.pipe(gulp.dest('./build'));
});
/**
* Build CSS files by running them through myth.
*/
gulp.task('build.css', function() {
return gulp.src('./src/css/*.css')
.pipe(plumber())
.pipe(myth())
.pipe(gulp.dest('./build/css'));
});
/**
* Build JS files by running them through Babel.
*/
gulp.task('build.js', function() {
return gulp.src('./src/js/*.js')
.pipe(plumber())
.pipe(babel())
.pipe(gulp.dest('./build/js'));
});
/**
* Full build of the static site.
*/
gulp.task('build', ['build.templates', 'build.css', 'build.js', 'build.static']);
gulp.task('clean', function(cb) {
del('build/**/*', cb);
});
/**
* Build the site, commit it to the gh-pages branch, and push to origin.
*/
gulp.task('deploy', ['build'], function(cb) {
gitRev.long(function(rev) {
gulp.src('./build/**/*')
.pipe(deploy({
message: 'Building from commit ' + rev,
}))
.on('end', cb);
});
});
/**
* Download and validate contribute.json files for all the projects in
* projects.json.
*/
gulp.task('validate_contribute_json', function(gulpCallback) {
var projects = allProjects(loadProjects());
var bar = new ProgressBar(':bar', {total: projects.length});
var passed = [];
var failed = [];
var skipped = [];
// Sort projects by name.
projects.sort(function(a, b) {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});
async.each(projects, function(project, eachCallback) {
if (!project.github) {
skipped.push({project: project, reason: 'No Github repo.'});
bar.tick();
return eachCallback();
}
getContributeJSON(project, function(contributeJSON, error) {
if (error) {
failed.push({
project: project,
reason: error
});
bar.tick();
eachCallback();
} else {
validateContributeJSON(contributeJSON, function(result) {
if (result.errors.length > 0) {
failed.push({
project: project,
reason: 'Failed validation.',
validationResult: result,
});
bar.tick();
eachCallback();
} else {
passed.push(project);
bar.tick();
eachCallback();
}
});
}
});
}, function() {
gutil.log(gutil.colors.green('== Passed =='));
passed.forEach(function(project) {
gutil.log(' ' + gutil.colors.underline(project.name));
});
gutil.log(gutil.colors.red('== Failed =='));
failed.forEach(function(result) {
gutil.log(' ' + gutil.colors.underline(result.project.name));
gutil.log(' ' + result.reason);
if (result.validationResult) {
gutil.log(result.validationResult.errors);
}
});
gutil.log(gutil.colors.yellow('== Skipped =='));
skipped.forEach(function(result) {
gutil.log(' ' + gutil.colors.underline(result.project.name));
gutil.log(' ' + result.reason);
});
});
});
function getContributeJSON(project, callback) {
if (!project.github) {
callback(null, 'No Github repo.');
}
var url = util.format(CONTRIBUTE_JSON_URL, project.github.user,
project.github.repository);
request(url, function(error, response, body) {
if (error) {
callback(null, 'Error downloading contribute.json: ' + error);
} else if (response.statusCode != 200) {
callback(null, 'Bad response code: ' + response.statusCode);
} else {
try {
var contributeJSON = JSON.parse(body);
callback(contributeJSON, null);
} catch (error) {
callback(null, 'Error parsing contribute.json: ' + error);
}
}
});
}
var _contributeSchema = null;
function getContributeSchema(callback) {
if (!_contributeSchema) {
request(CONTRIBUTE_JSON_SCHEMA, function(error, response, body) {
// TODO: Handle errors fetching this.
_contributeSchema = JSON.parse(body);
callback(_contributeSchema);
});
} else {
callback(_contributeSchema);
}
}
function validateContributeJSON(contributeJSON, callback) {
getContributeSchema(function(contributeSchema) {
callback(jsonschema.validate(contributeJSON, contributeSchema));
});
}
/**
* Return a list of every individual project from the categorized lists in
* projects.json.
*/
function allProjects(projects, filter) {
var _allProjects = [];
['websites', 'libraries', 'apps', 'other'].forEach(function(category) {
projects[category].forEach(function(project) {
if (filter && !filter(project)) return;
_allProjects.push(project);
});
});
return _allProjects;
}
/**
* Load projects.json.
*/
function loadProjects() {
return JSON.parse(fs.readFileSync('projects.json'));
}
/**
* Annotate a project with extra metadata, such as repo info pulled from the
* Github API.
*/
function annotateProject(project, callback) {
project.searchData = [project.name];
if (project.repos) {
project.link = project.repos[0];
} else if (project.see_also) {
project.link = project.see_also[0];
}
// If we have info about the Github repo, we can get the Github metadata as
// well as the contribute.json file.
if (project.github) {
async.series([
annotateProjectGithub.bind(null, project),
annotateProjectContributeJSON.bind(null, project),
], function() {
if (project.description) {
project.searchData.push(project.description);
}
project.searchData = project.searchData.join(',').toLowerCase();
callback();
});
} else {
callback();
}
}
/**
* Annotate a project with info from the Github API.
*/
function annotateProjectGithub(project, callback) {
github.repos.get({
user: project.github.user,
repo: project.github.repository,
}, function(err, result) {
if (err) {
callback(err, project);
} else {
project.github.description = result.description;
project.description = result.description;
project.github.stars = result.stargazers_count;
project.github.forks = result.forks_count;
callback(null, project);
}
});
}
/**
* Annotate a project with info from its contribute.json file.
*/
function annotateProjectContributeJSON(project, callback) {
getContributeJSON(project, function(contributeJSON, error) {
if (error) {
callback(error, project);
} else {
project.contributeJSON = contributeJSON;
project.description = contributeJSON.description || project.description;
if (contributeJSON.keywords) {
project.searchData = project.searchData.concat(contributeJSON.keywords);
}
callback(null, project);
}
});
}