2017-02-15 13:03:33 +00:00
|
|
|
import { tmpdir } from 'os'
|
|
|
|
import { join } from 'path'
|
2017-01-11 20:16:18 +00:00
|
|
|
import fs from 'mz/fs'
|
|
|
|
import uuid from 'uuid'
|
2017-02-15 13:03:33 +00:00
|
|
|
import del from 'del'
|
2016-10-17 01:54:36 +00:00
|
|
|
import webpack from './webpack'
|
2017-02-14 23:14:30 +00:00
|
|
|
import replaceCurrentBuild from './replace'
|
2016-10-06 11:05:52 +00:00
|
|
|
|
|
|
|
export default async function build (dir) {
|
2017-02-15 13:03:33 +00:00
|
|
|
const buildDir = join(tmpdir(), uuid.v4())
|
|
|
|
const compiler = await webpack(dir, { buildDir })
|
2016-10-09 09:25:38 +00:00
|
|
|
|
2017-02-15 13:03:33 +00:00
|
|
|
try {
|
|
|
|
await runCompiler(compiler)
|
|
|
|
await writeBuildId(buildDir)
|
|
|
|
} catch (err) {
|
|
|
|
console.error(`> Failed to build on ${buildDir}`)
|
|
|
|
throw err
|
|
|
|
}
|
2017-02-14 23:14:30 +00:00
|
|
|
|
2017-02-15 13:03:33 +00:00
|
|
|
await replaceCurrentBuild(dir, buildDir)
|
|
|
|
|
|
|
|
// no need to wait
|
2017-02-15 16:31:21 +00:00
|
|
|
del(buildDir, { force: true })
|
2016-12-16 18:42:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function runCompiler (compiler) {
|
2016-10-17 01:54:36 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
compiler.run((err, stats) => {
|
|
|
|
if (err) return reject(err)
|
2016-10-06 11:05:52 +00:00
|
|
|
|
2016-10-17 01:54:36 +00:00
|
|
|
const jsonStats = stats.toJson()
|
|
|
|
if (jsonStats.errors.length > 0) {
|
|
|
|
const error = new Error(jsonStats.errors[0])
|
|
|
|
error.errors = jsonStats.errors
|
|
|
|
error.warnings = jsonStats.warnings
|
|
|
|
return reject(error)
|
|
|
|
}
|
2016-10-06 11:05:52 +00:00
|
|
|
|
2016-10-17 01:54:36 +00:00
|
|
|
resolve()
|
|
|
|
})
|
|
|
|
})
|
2016-10-06 11:05:52 +00:00
|
|
|
}
|
2017-01-11 20:16:18 +00:00
|
|
|
|
2017-02-15 13:03:33 +00:00
|
|
|
async function writeBuildId (dir) {
|
|
|
|
const buildIdPath = join(dir, '.next', 'BUILD_ID')
|
2017-01-11 20:16:18 +00:00
|
|
|
const buildId = uuid.v4()
|
|
|
|
await fs.writeFile(buildIdPath, buildId, 'utf8')
|
|
|
|
}
|