@applicaster/zapplicaster-cli
Version:
CLI Tool for the zapp app and Quick Brick project
95 lines (82 loc) • 2.53 kB
JavaScript
const R = require("ramda");
/**
* module file
* @module @applicaster/zapplicaster-cli/util/file
*/
const { writeFile, readFile, readdir, copyFile, copyFileSync } = require("fs");
const { promisify } = require("util");
const { join } = require("path");
const writeFileAsync = promisify(writeFile);
const readFileAsync = promisify(readFile);
const readdirAsync = promisify(readdir);
const copyFileAsync = promisify(copyFile);
/**
* Writes a pretty-printed json file from a javascript object
* @param {String} path : path of the file to write
* @param {Object} object : object to write to the file
* @returns {Promise}
*/
async function writeJsonToFile(path, object) {
return await writeFileAsync(path, JSON.stringify(object, null, 2));
}
/**
* Read and parse json file to a javascript object
* @param {String} path : path of the json file to read
* @returns {Promise}
*/
async function readJsonFile(path) {
const file = await readFileAsync(path);
return JSON.parse(file);
}
/**
* Copies files from one folder to another
* @param {String} source path
* @param {String} destination path
* @returns {Promise[]} array of promises with the status of the copied files
*/
async function copyFolder(source, destination) {
const files = await readdirAsync(source);
return copyFiles(source, files, destination);
}
/**
* Changes the destination file name when a file is copied
* this is required since .npmrc template file is not pushed to npm unless it is renamed
*
* @param {string} destinationFileName to change if needed
* @returns {string} modified desinationFileName
*/
function destinationFileNameMapper(destinationFileName) {
return destinationFileName.replace("_package.json", "package.json");
}
/**
* Copies an array of files from a folder to another
*
* @param {String} source folder of the files
* @param {String[]} files list of the files
* @param {String} destination path
* @returns {Promise[]} array of promises with the status of the copied files
*/
function copyFiles(source, filesOrFilesGetter, destination, config) {
const files =
typeof filesOrFilesGetter === "function"
? filesOrFilesGetter(config)
: filesOrFilesGetter;
return R.map(
(file) =>
copyFileSync(
join(source, file),
destinationFileNameMapper(join(destination, file))
),
files
);
}
module.exports = {
writeFileAsync,
copyFileAsync,
writeJsonToFile,
readJsonFile,
readdirAsync,
copyFolder,
copyFiles,
destinationFileNameMapper,
};