snippeteer/lib/Helper.ts
2020-04-18 17:43:13 +02:00

65 lines
1.6 KiB
TypeScript

import path from 'path';
import child_process from 'child_process';
import fs from 'fs-extra';
/**
* write a template to a file
*
* @param {string} contents file contents
* @param {string} destination file destination
*/
async function apply_template (
contents: string,
destination: string
): Promise<void> {
const dst = path.join (process.cwd (), destination);
if (!await fs.pathExists (dst))
await fs.writeFile (dst, contents);
}
type JSONMutator = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(json: any): any;
}
/**
* modify a json file
*
* @param {Function} func function that modifies the object
* @param {string} json_path path of json file
*/
async function modify_json (
func: JSONMutator,
json_path = 'package.json'
): Promise<void> {
const file_path = path.join (process.cwd (), json_path);
const content = JSON.parse (await fs.readFile (file_path, 'utf-8'));
const new_obj = await func (content);
await fs.writeFile (file_path, JSON.stringify (new_obj, null, 2));
}
/**
* run a command
*
* @param {string} command command to run
* @param {string} folder folder to run in
* @returns {Promise<void>} promise
*/
function run_command (command: string, folder = ''): Promise<void> {
return new Promise ((res) => {
child_process.exec (
command,
{ cwd: path.join (process.cwd (), folder) },
(err, stdout, stderr) => {
if (err)
throw err;
// eslint-disable-next-line no-console
console.log (stdout + stderr);
res ();
}
);
});
}
export { modify_json, apply_template, run_command };