import fs from 'fs'; import path from 'path'; import mkdirp from 'mkdirp'; import merge from 'lodash/merge'; import { spawn } from 'child_process'; import { promisify } from 'util'; export const copyFileAsync = promisify(fs.copyFile); export const writeFileAsync = promisify(fs.writeFile); export const readFileAsync = promisify(fs.readFile); export const mkdirpAsync = promisify(mkdirp); export function runCommand(cmd:string) { return new Promise((resolve, reject) => { const [main, ...args] = cmd.split(' '); const child = spawn(main, args, {cwd: process.env.INIT_CWD, env: process.env}); child.stdout.setEncoding('utf-8').on('data', (chunk) => { process.stdout.write(chunk); }); child.stderr.setEncoding('utf-8').on('data', (chunk) => { process.stdout.write(chunk); }); child.on('error', (err) => { reject(err); }) child.on('close', () => { console.log(`"${cmd}" has finished.`) resolve(); }); }); } export function writeScript(pkg:{scripts:any}, key:string, script:string) { pkg.scripts = pkg.scripts || {}; if (pkg.scripts[key] !== script) { pkg.scripts[`legacy-${key}`] = pkg.scripts[key]; } pkg.scripts[key] = script; } function loadJson(path:string):T{ const configString = fs.readFileSync(path, {encoding: 'utf-8'}); return JSON.parse(configString) as T; } type PackageJson = { name:string } export function toolsPath(filePath:string) { const packageJson = loadJson(path.resolve(__dirname, './package.json')) const { name } = packageJson; return path.join('node_modules', name, filePath); } export function runPath(filePath:string) { const {INIT_CWD = path.resolve(__dirname, '../../.'), NODE_ENV} = process.env; const config = readConfigSync(); const pathArgs = NODE_ENV === 'production' ? [INIT_CWD, config.paths.build, filePath] : [INIT_CWD, filePath]; return path.resolve(...pathArgs); } export function rootPath(filePath:string){ return path.resolve(process.env.INIT_CWD || '', filePath); } type ConfigShape = { typescript?: string[], webpack?: string[], static?: string[], paths?: { build:string, static:string } } type Paths = { paths: { build:string, static:string } } export function readConfigSync() { const defaultConfig: Paths = { paths: { build: 'build', static: 'static', } } const config = loadJson('./tsmill.json'); return merge({}, defaultConfig, config) as ConfigShape & Paths; } export function evalJs(path:string) { const code = fs.readFileSync(path, {encoding: 'utf-8'}); return eval(code); }