@focuson/cod
Version:
A command line tool to help with the code on demand
63 lines (62 loc) • 2.85 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Files = void 0;
const path_1 = __importDefault(require("path"));
const Strings_1 = require("./Strings");
const TsxTransformer_1 = require("./TsxTransformer");
const fs = require('fs');
class Files {
forEachFile(dir) {
return fn => fs.promises.readdir(dir).then((files) => Promise.all(files.map(fn)));
}
validateDirectoryExists(message, dir) {
return fs.promises.lstat(dir).then((stat) => {
}, (err) => {
if (err.code === 'ENOENT') {
throw new Error(`Error: ${message}: ${dir} not found.`);
}
else {
throw new Error(`Error: ${message}: ${dir}: ${err.message}`);
}
});
}
createDirectoryForFile(parsedPath) {
return fs.promises.mkdir(parsedPath.dir, { recursive: true });
}
saveFileIfDoesntExist(parsedPath, content, sha) {
const newPath = path_1.default.join(parsedPath.dir, parsedPath.name, sha);
const newParsedPath = path_1.default.parse(newPath);
this.createDirectoryForFile(newParsedPath);
return fs.promises.stat(newPath).then((stat) => {
}, (err) => {
if (err.code === 'ENOENT') {
// file does not exist. Create sha files and write updated content to it
fs.promises.writeFile(newPath, content, 'utf-8'). //
then(() => {
console.log(`${newParsedPath.base} created`);
});
}
else {
console.log('Error saving file: ', err.code);
throw err;
}
});
}
copyAndChangeFile(fromFileName, transformer, toFileName) {
return fs.promises.readFile(path_1.default.join(fromFileName.dir, fromFileName.base), 'utf-8').then(transformer).then((content) => fs.promises.writeFile(toFileName, content, 'utf-8'));
}
copyTransformAndSaveFileForContentAddressableData(fromPath, transformer, toFileNameFn) {
return fs.promises.readFile(path_1.default.join(fromPath.dir, fromPath.base), 'utf-8')
.then((content) => transformer.call(new TsxTransformer_1.TsxTransformer(this), content, fromPath.base))
.then(Strings_1.Strings.findSha)
.then((contentAndSha) => {
let parsedPath = toFileNameFn(fromPath, contentAndSha.sha);
return this.saveFileIfDoesntExist(parsedPath, contentAndSha.content, contentAndSha.sha). //
then(() => ({ parsedPath: parsedPath, sha: contentAndSha.sha }));
});
}
}
exports.Files = Files;