|
| 1 | +import { spawn } from 'child_process' |
| 2 | +import { createHash } from 'crypto' |
| 3 | +import dotenv from 'dotenv' |
| 4 | +import consola from 'consola' |
| 5 | +import { readFileSync, writeFileSync } from 'fs' |
| 6 | + |
| 7 | +dotenv.config() |
| 8 | + |
| 9 | +function hashEnv() { |
| 10 | + const sum = createHash('sha256') |
| 11 | + const env = Object.fromEntries(Object.entries(process.env).filter( |
| 12 | + ([key]) => !['HOSTNAME', 'PATH'].includes(key) |
| 13 | + )) |
| 14 | + console.log('env', env) |
| 15 | + sum.update(JSON.stringify(env)) |
| 16 | + return sum.digest('hex') |
| 17 | +} |
| 18 | + |
| 19 | +function readHash() { |
| 20 | + try { |
| 21 | + return readFileSync('.env.hash', 'utf8') |
| 22 | + } catch (err) { |
| 23 | + return '' |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +function buildNuxt() { |
| 28 | + return new Promise((resolve, reject) => { |
| 29 | + consola.info('Building Nuxt...') |
| 30 | + const building = spawn('yarn', ['build'], { env: process.env, shell: true }) |
| 31 | + |
| 32 | + building.stdout.on('data', (data) => { |
| 33 | + process.stdout.write(data.toString()) |
| 34 | + }) |
| 35 | + |
| 36 | + building.stderr.on('data', (data) => { |
| 37 | + process.stderr.write(data.toString()) |
| 38 | + }) |
| 39 | + |
| 40 | + building.on('close', (code) => { |
| 41 | + consola.info(`child process exited with code ${code}`) |
| 42 | + code > 0 ? reject() : resolve() |
| 43 | + |
| 44 | + if (code > 0) return reject() |
| 45 | + |
| 46 | + consola.info('Hashing .env...') |
| 47 | + writeFileSync('.env.hash', hashEnv()) |
| 48 | + return resolve() |
| 49 | + }) |
| 50 | + }) |
| 51 | +} |
| 52 | + |
| 53 | +;(async () => { |
| 54 | + if (hashEnv() !== readHash()) { |
| 55 | + consola.warn('Hash changed, rebuilding...') |
| 56 | + consola.info(`Hash: ${hashEnv()}, Previous: ${readHash()}`) |
| 57 | + await buildNuxt() |
| 58 | + } |
| 59 | + |
| 60 | + consola.info('Starting Nuxt...') |
| 61 | + const starting = spawn('yarn', ['start'], { env: process.env, shell: true }) |
| 62 | + |
| 63 | + starting.stdout.on('data', (data) => { |
| 64 | + process.stdout.write(data.toString()) |
| 65 | + }) |
| 66 | + |
| 67 | + starting.stderr.on('data', (data) => { |
| 68 | + process.stderr.write(data.toString()) |
| 69 | + }) |
| 70 | + |
| 71 | + starting.on('close', (code) => { |
| 72 | + consola.warn(`child process exited with code ${code}`) |
| 73 | + }) |
| 74 | +})() |
0 commit comments