snippeteer/lib/Helper.ts

67 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-05-07 18:40:35 +02:00
/*
* Copyright (C) SapphireCode - All Rights Reserved
* This file is part of Snippeteer which is released under BSD-3-Clause.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, May 2020
*/
2020-04-18 17:24:41 +02:00
import path from 'path';
import child_process from 'child_process';
import fs from 'fs-extra';
/**
* write a template to a file
*
2020-05-08 09:58:49 +02:00
* @param contents - file contents
* @param destination - file destination
2020-04-18 17:24:41 +02:00
*/
async function apply_template (
contents: string,
destination: string
): Promise<void> {
const dst = path.join (process.cwd (), destination);
2020-04-18 19:00:27 +02:00
if (!await fs.pathExists (dst)) {
await fs.mkdirp (path.dirname (dst));
2020-04-18 17:24:41 +02:00
await fs.writeFile (dst, contents);
2020-04-18 19:00:27 +02:00
}
2020-04-18 17:24:41 +02:00
}
type JSONMutator = {
2020-04-18 17:43:13 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(json: any): any;
2020-04-18 17:24:41 +02:00
}
/**
* modify a json file
*
2020-05-08 09:58:49 +02:00
* @param func - function that modifies the object
* @param json_path - path of json file
2020-04-18 17:24:41 +02:00
*/
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);
2020-05-11 11:33:34 +02:00
if (typeof new_obj === 'undefined' || new_obj === null)
return;
2020-04-18 17:24:41 +02:00
await fs.writeFile (file_path, JSON.stringify (new_obj, null, 2));
}
/**
* run a command
*
2020-05-08 09:58:49 +02:00
* @param command - command to run
* @param folder - folder to run in
2020-04-18 17:24:41 +02:00
*/
2020-04-18 19:00:27 +02:00
function run_command (command: string, folder = ''): void {
// eslint-disable-next-line no-sync
child_process.execSync (
command,
{ cwd: path.join (process.cwd (), folder), stdio: 'inherit' }
);
2020-04-18 17:24:41 +02:00
}
export { modify_json, apply_template, run_command };