-
Notifications
You must be signed in to change notification settings - Fork 394
/
gulpfile.js
335 lines (299 loc) · 9.46 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
/* eslint-disable import/no-commonjs, import/no-unassigned-import, max-nested-callbacks */
// Note: Node 8 compat, please!
require('hard-rejection/register')
const fs = require('fs')
const childProcess = require('child_process')
const path = require('path')
const {series, parallel, src, dest, watch} = require('gulp')
const newer = require('gulp-newer')
const babel = require('gulp-babel')
const gutil = require('gulp-util')
const changed = require('gulp-changed')
const filter = require('gulp-filter')
const plumber = require('gulp-plumber')
const ts = require('gulp-typescript')
const sourcemaps = require('gulp-sourcemaps')
const through = require('through2')
const chalk = require('chalk')
const globby = require('globby')
const mergeStream = require('merge-stream')
const backstop = require('backstopjs')
const waitPort = require('wait-port')
const kill = require('kill-port')
const {promisify} = require('util')
const stat = promisify(fs.stat)
const isWindows = /^win/.test(process.platform)
const compareModified = async (stream, sourceFile, targetPath) => {
const targetStat = await stat(targetPath)
if (sourceFile.stat && Math.floor(sourceFile.stat.mtimeMs) > Math.floor(targetStat.mtimeMs)) {
stream.push(sourceFile)
}
}
const tsPaths = globby.sync(['./packages/@sanity/*/tsconfig.json'])
const getTsProjects = () => tsPaths.map(conf => ts.createProject(conf))
const tsScripts = tsPaths.map(proj => `${path.dirname(proj)}/src/**/*.ts`)
const scripts = [
'./packages/@sanity/*/src/**/*.js',
'./packages/sanity-plugin-*/src/**/*.js',
'./packages/groq/src/**/*.js'
]
const assets = [
'./packages/@sanity/*/src/**/*',
'./packages/sanity-plugin-*/src/**/*',
'./packages/groq/src/**/*.js'
]
const srcOpts = {base: 'packages'}
const getProjectEnv = projectPath => {
const npmPath = path.join(projectPath, 'node_modules', '.bin')
/* eslint-disable no-process-env */
const paths = [npmPath].concat(process.env.PATH.split(path.delimiter)).filter(Boolean)
return Object.assign({}, process.env, {
PATH: paths.join(path.delimiter)
})
/* eslint-enable no-process-env */
}
let srcEx
let srcRootEx
let libFragment
if (path.win32 === path) {
srcEx = /(@sanity\\[^\\]+)\\src\\/
srcRootEx = /(groq|sanity-plugin-[^\\]+)\\src\\/
libFragment = '$1\\lib\\'
} else {
srcEx = new RegExp('(@sanity/[^/]+)/src/')
srcRootEx = /(groq|sanity-plugin-[^/]+)\/src\//
libFragment = '$1/lib/'
}
const logCompile = from => (file, enc, cb) => {
gutil.log(`[${from}] Compiling`, `'${chalk.cyan(file._path || file.path)}'...`)
cb(null, file)
}
const mapToDest = orgPath => {
const outPath = orgPath.replace(srcEx, libFragment).replace(srcRootEx, libFragment)
return outPath
}
const packagesPath = 'packages'
const fullPackagesPath = path.join(__dirname, packagesPath)
const pkgPath = (cwd, sourcePath) => path.relative(path.join(cwd, 'packages'), sourcePath)
const getLogErrorHandler = () => plumber({errorHandler: err => gutil.log(err.stack)})
const getNoopErrorHandler = () => through.obj((chunk, enc, cb) => cb(null, chunk))
const buildTypeScript = getTypeScriptBuilder(getNoopErrorHandler)
const watchJavaScript = series(buildJavaScript, function watchJavascriptRebuild() {
watch(scripts, watchJavaScriptRebuild)
})
const watchTypeScript = series(
getTypeScriptBuilder(getLogErrorHandler),
function watchTypescriptRebuild() {
watch(tsScripts, buildTypeScript)
}
)
exports.default = parallel(buildJavaScript, buildTypeScript)
exports.build = parallel(buildJavaScript, buildTypeScript)
exports.watchTypeScript = watchTypeScript
exports.watch = parallel(watchJavaScript, watchTypeScript, buildAssets)
function buildJavaScript() {
const assetFilter = filter(['**/*.js'], {restore: true})
return src(assets, srcOpts)
.pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
.pipe(assetFilter)
.pipe(
changed(packagesPath, {
transformPath: inp => mapToDest(inp),
hasChanged: compareModified
})
)
.pipe(through.obj(logCompile('JS')))
.pipe(babel())
.pipe(assetFilter.restore)
.pipe(
through.obj((file, enc, callback) => {
file._path = file.path
file.path = mapToDest(file.path)
callback(null, file)
})
)
.pipe(dest(packagesPath))
}
function watchJavaScriptRebuild() {
return src(scripts, srcOpts)
.pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
.pipe(
through.obj((file, enc, callback) => {
file._path = file.path
file.path = mapToDest(file.path)
callback(null, file)
})
)
.pipe(newer(packagesPath))
.pipe(through.obj(logCompile('JS')))
.pipe(babel())
.pipe(dest(packagesPath))
}
function getTypeScriptBuilder(getErrorHandler) {
return function buildTypescript() {
return mergeStream(
...getTsProjects().map(project => {
const source = project
.src()
.pipe(getErrorHandler())
.pipe(sourcemaps.init())
.pipe(project())
return mergeStream(
source.dts
.pipe(
changed(packagesPath, {
transformPath: inp => inp.replace(fullPackagesPath, project.options.outDir),
hasChanged: compareModified
})
)
.pipe(getErrorHandler())
.pipe(sourcemaps.write('.', {includeContent: false, sourceRoot: './'}))
.pipe(dest(project.options.outDir)),
source.js
.pipe(
changed(packagesPath, {
transformPath: inp => inp.replace(fullPackagesPath, project.options.outDir),
hasChanged: compareModified
})
)
.pipe(getErrorHandler())
.pipe(through.obj(logCompile('TS')))
.pipe(sourcemaps.write('.', {includeContent: false, sourceRoot: './'}))
.pipe(dest(project.options.outDir))
)
})
)
}
}
function buildAssets() {
return src(assets, srcOpts)
.pipe(filter(['**/*.*', '!**/*.js']))
.pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
.pipe(
through.obj((file, enc, callback) => {
file._path = file.path
file.path = mapToDest(file.path)
callback(null, file)
})
)
.pipe(newer(packagesPath))
.pipe(
through.obj((file, enc, callback) => {
gutil.log('Copying ', `'${chalk.green(pkgPath(file.cwd, file._path))}'...`)
callback(null, file)
})
)
.pipe(dest(packagesPath))
}
const STUDIOS = [
{name: 'test-studio', port: '3333'},
{name: 'movies-studio', port: '3334'},
{name: 'example-studio', port: '3335'},
{name: 'blog-studio', port: '3336'},
{name: 'ecommerce-studio', port: '3337'},
{name: 'clean-studio', port: '3338'},
{name: 'backstop-test-studio', port: '5000'}
]
STUDIOS.forEach(studio => {
exports[studio.name] = series(
parallel(buildJavaScript, buildTypeScript, buildAssets),
parallel(exports.watch, function runStudio(cb) {
const projectPath = path.join(__dirname, 'packages', studio.name)
const proc = childProcess.spawn(
'sanity',
['start', '--host', '0.0.0.0', '--port', studio.port],
{
shell: isWindows,
cwd: projectPath,
env: getProjectEnv(projectPath)
}
)
proc.stdout.pipe(process.stdout)
proc.stderr.pipe(process.stderr)
})
)
})
exports.storybook = series(
parallel(buildJavaScript, buildTypeScript, buildAssets),
parallel(exports.watch, function runStorybook(cb) {
const projectPath = path.join(__dirname, 'packages', 'storybook')
const proc = childProcess.spawn('npm', ['start'], {
shell: isWindows,
cwd: projectPath,
env: getProjectEnv(projectPath)
})
proc.stdout.pipe(process.stdout)
proc.stderr.pipe(process.stderr)
})
)
exports.backstop = function(cb) {
childProcess.exec('docker -v', err => {
if (err) {
throw new gutil.PluginError({
plugin: 'backstop',
message: gutil.colors.red('Please install Docker on your computer. https://www.docker.com/')
})
}
})
const params = {
host: 'localhost',
port: 5000,
timeout: 100 * 60 * 10
}
parallel(exports['backstop-test-studio'], async () => {
let open
try {
open = await waitPort(params)
} catch (err) {
kill(params.port)
throw new gutil.PluginError({
plugin: 'backstop',
message: `An unknown error occured while waiting for the port: ${err}`
})
}
if (!open) {
kill(params.port)
throw new gutil.PluginError({
plugin: 'backstop',
message: 'The backstop-studio did not start'
})
}
try {
await backstop('test', {
docker: true,
config: './test/backstop/backstop.js'
})
await kill(params.port)
gutil.log(gutil.colors.green('Backstop test success'))
// eslint-disable-next-line no-process-exit
process.exit(0)
} catch (err) {
kill(params.port)
throw new gutil.PluginError({
plugin: 'backstop',
message: 'Tests failed'
})
}
cb()
})()
}
exports['backstop:approve'] = cb => {
backstop('approve', {
docker: true,
config: './test/backstop/backstop.js'
})
}
exports['backstop:reference'] = async cb => {
try {
await backstop('reference', {
docker: true,
config: './test/backstop/backstop.js'
})
gutil.log(gutil.colors.green('References created'))
} catch (err) {
throw new gutil.PluginError({
plugin: 'backstop',
message: 'Making references failed'
})
}
}