-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.babel.js
260 lines (227 loc) · 7.59 KB
/
gulpfile.babel.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
import config from './config.json'
import gulp from 'gulp'
import file from 'gulp-file'
import gutil from 'gulp-util'
import s3 from 'gulp-s3-upload';
import sass from 'gulp-sass'
import size from 'gulp-size'
import sourcemaps from 'gulp-sourcemaps'
import template from 'gulp-template'
import browserSync from 'browser-sync'
import buffer from 'vinyl-buffer'
import del from 'del'
import fs from 'fs'
import inquirer from 'inquirer'
import rollup from 'rollup-stream'
import rp from 'request-promise-native'
import runSequence from 'run-sequence'
import source from 'vinyl-source-stream'
const browser = browserSync.create();
const buildDir = '.build';
const cdnUrl = 'https://interactive.guim.co.uk';
const isDeploy = gutil.env._.indexOf('deploy') > -1;
const version = `v/${Date.now()}`;
const s3Path = `atoms/${config.path}`;
const s3VersionPath = `${s3Path}/${version}`;
const path = isDeploy ? `${cdnUrl}/${s3VersionPath}` : '.';
// hack to use .babelrc environments without env var, would be nice to
// be able to pass "client" env through to babel
const babelrc = JSON.parse(fs.readFileSync('.babelrc'));
const presets = (babelrc.presets || []).concat(babelrc.env.client.presets);
const plugins = (babelrc.plugins || []).concat(babelrc.env.client.plugins);
const rollupPlugins = [
require('rollup-plugin-json')(),
require('rollup-plugin-string')({
'include': '**/*.html'
}),
require('rollup-plugin-node-resolve')({
'jsnext': true, 'browser': true
}),
require('rollup-plugin-commonjs')({
'include': ['node_modules/**']
}),
require('rollup-plugin-babel')({
'exclude': 'node_modules/**',
'babelrc': false,
presets, plugins
}),
isDeploy && require('rollup-plugin-uglify')()
];
function logError(plugin, err) {
console.error(new gutil.PluginError(plugin, err.message).toString());
if (err instanceof SyntaxError) {
console.error(err.codeFrame);
}
}
function buildJS(filename) {
return () => {
return rollup({
'entry': `./src/js/${filename}`,
'sourceMap': true,
'plugins': rollupPlugins,
'format': 'iife'
})
.on('error', function (err) {
logError('rollup', err);
this.emit('end');
})
.pipe(source(filename, './src/js'))
.pipe(buffer())
.pipe(template({path}))
.pipe(sourcemaps.init({'loadMaps': true}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(buildDir));
}
}
function s3Upload(cacheControl, keyPrefix) {
return s3()({
'Bucket': 'gdn-cdn',
'ACL': 'public-read',
'CacheControl': cacheControl,
'keyTransform': fn => `${keyPrefix}/${fn}`
});
}
function requireUncached(module) {
delete require.cache[require.resolve(module)];
return require(module);
}
function readOpt(fn) {
try {
return fs.readFileSync(fn);
} catch (err) {
return '';
}
}
gulp.task('clean', () => del(buildDir));
gulp.task('build:css', () => {
return gulp.src('src/css/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
'outputStyle': isDeploy ? 'compressed' : 'expanded'
}).on('error', sass.logError))
.pipe(sourcemaps.write('.'))
.pipe(template({path}))
.pipe(gulp.dest(buildDir))
.pipe(browser.stream({'match': '**/*.css'}));
});
gulp.task('build:js.main', buildJS('main.js'));
gulp.task('build:js.app', buildJS('app.js'));
gulp.task('build:js', ['build:js.main', 'build:js.app']);
gulp.task('build:html', cb => {
try {
let render = requireUncached('./src/render.js').render;
Promise.resolve(render()).then(html => {
file('main.html', html, {'src': true})
.pipe(template({path}))
.pipe(gulp.dest(buildDir))
.on('end', cb);
}).catch(err => {
logError('render.js', err);
cb();
});
} catch (err) {
logError('render.js', err);
cb();
}
});
gulp.task('build:assets', () => {
return gulp.src('src/assets/**/*').pipe(gulp.dest(`${buildDir}/assets`));
});
gulp.task('_build', ['clean'], cb => {
runSequence(['build:css', 'build:js', 'build:html', 'build:assets'], cb);
});
// TODO: less hacky build/_build?
gulp.task('build', ['_build'], () => {
return gulp.src(`${buildDir}/**/!(*.map)`)
.pipe(size({'gzip': true, 'showFiles': true}))
});
gulp.task('deploy', ['build'], cb => {
if(s3Path === "atoms/2016/05/blah") {
console.error("ERROR: You need to change the deploy path from its default value")
return;
}
inquirer.prompt({
type: 'list',
name: 'env',
message: 'Where would you like to deploy to?',
choices: ['preview', 'live']
}).then(res => {
let isLive = res.env === 'live';
gulp.src(`${buildDir}/**/*`)
.pipe(s3Upload('max-age=31536000', s3VersionPath))
.on('end', () => {
gulp.src('config.json')
.pipe(file('preview', version))
.pipe(isLive ? file('live', version) : gutil.noop())
.pipe(s3Upload('max-age=30', s3Path))
.on('end', cb);
});
});
});
gulp.task('deploylive', ['build'], cb => {
if(s3Path === "atoms/2016/05/blah") {
console.error("ERROR: You need to change the deploy path from its default value")
return;
}
gulp.src(`${buildDir}/**/*`)
.pipe(s3Upload('max-age=31536000', s3VersionPath))
.on('end', () => {
gulp.src('config.json')
.pipe(file('preview', version))
.pipe(file('live', version))
.pipe(s3Upload('max-age=30', s3Path))
.on('end', cb);
});
});
gulp.task('deploypreview', ['build'], cb => {
if(s3Path === "atoms/2016/05/blah") {
console.error("ERROR: You need to change the deploy path from its default value")
return;
}
gulp.src(`${buildDir}/**/*`)
.pipe(s3Upload('max-age=31536000', s3VersionPath))
.on('end', () => {
gulp.src('config.json')
.pipe(file('preview', version))
.pipe(s3Upload('max-age=30', s3Path))
.on('end', cb);
});
});
gulp.task('local', ['build'], () => {
return gulp.src('harness/*')
.pipe(template({
'css': readOpt(`${buildDir}/main.css`),
'html': readOpt(`${buildDir}/main.html`),
'js': readOpt(`${buildDir}/main.js`)
}))
.pipe(gulp.dest(buildDir));
});
gulp.task('default', ['local'], () => {
gulp.watch('src/**/*', ['local']).on('change', evt => {
console.log();
gutil.log(gutil.colors.yellow(`${evt.path} was ${evt.type}`));
});
browser.init({
'server': {'baseDir': buildDir},
'port': 8000
});
});
gulp.task('url', () => {
gutil.log(gutil.colors.green(`Atom URL: https://content.guardianapis.com/atom/interactive/interactives/${config.path}`));
});
gulp.task('log', () => {
function log(type) {
let url = `${cdnUrl}/atoms/${config.path}/${type}.log?${Date.now()}`;
return rp(url).then(log => {
gutil.log(gutil.colors.green(`Got ${type} log:`));
console.log(log);
}).catch(err => {
if (err.statusCode === 404) {
gutil.log(gutil.colors.yellow(`No ${type} log, have you ever deployed?`));
} else {
throw err;
}
});
}
return Promise.all([log('live'), log('preview')]);
});