const fs = require('fs') const yaml = require('js-yaml') const chproc = require('child_process') /** * Delete all files in a directory * * @param dirPath : string */ function rmInDir(dirPath) { let files console.log(`\x1b[32m[Clean]\x1b[m ${dirPath}`) try { files = fs.readdirSync(dirPath) } catch (e) { return } if (files.length > 0) { for (let i = 0; i < files.length; i++) { let filePath = dirPath + '/' + files[i] if (filePath.endsWith('.gitignore') || filePath.endsWith('.gitkeep')) continue // preserve special files if (fs.statSync(filePath).isFile()) fs.unlinkSync(filePath) else rmInDir(filePath) } } } /** * Copy a file * * @param src : string * @param dest : string * @param verbose : boolean, default true * @returns {boolean} */ function cp(src, dest, verbose=true) { if (!fs.existsSync(src)) { return false; } if (verbose) console.log(`\x1b[32m[Copy]\x1b[m ${src} -> ${dest}`) let data = fs.readFileSync(src); fs.writeFileSync(dest, data); return true } /** * Write with automatic encoding to JSON or YAML * * @param path : string * @param content : object|string */ function fwrite(path, content) { let towrite = content let format = 'plain' if (typeof towrite !== 'string') { if (path.endsWith('.json')) { towrite = JSON.stringify(towrite, null, 4) format = 'json' } else if (path.endsWith('.yaml') || path.endsWith('.yml')) { towrite = yaml.safeDump(towrite) format = 'yaml' } else { throw `Can't figure out data encoding (at ${path})` } } console.log(`\x1b[32m[Writing]\x1b[m ${path} (${format})`) fs.writeFileSync(path, towrite) } /** * Read with automatic decoding from JSON or YAML * * @param path : string * @return string|object|array */ function fread(path) { let content = fs.readFileSync(path, 'utf-8') let format = 'plain' if (path.endsWith('.json')) { content = JSON.parse(content) format = 'json' } else if (path.endsWith('.yaml') || path.endsWith('.yml')) { content = yaml.safeLoad(content) format = 'yaml' } console.log(`\x1b[32m[Reading]\x1b[m ${path} (${format})`) return content } /** * Test if a file exists * * @param path : string * @returns {boolean} exists */ function exists (path) { return fs.existsSync(path) } /** * Delete a file * * @param path : string * @returns {boolean} success */ function rm (path) { if (!exists(path)) { return false } fs.unlinkSync(path) return true } /** * Execute a command * * @param command * @param cwd */ function exec (command, cwd='.') { return chproc.execSync(command, { cwd: cwd, stdio: [0,1,2] }) } module.exports = { rmInDir, cp, fwrite, fread, exists, rm, exec, abort: (msg) => { console.log(`\x1b[31;1m${msg}\x1b[m`) process.exit() } }