@easy-breezy/core
Version:
Command line root module
94 lines (93 loc) • 2.88 kB
JavaScript
import { dirname } from 'path';
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync } from 'fs';
import { createHash } from 'crypto';
import output from './../output/index.js';
import i18n from './../i18n/index.js';
export class FS {
operations = {
exists: [],
read: [],
created: [],
changed: [],
removed: []
};
createSignature = (data) => {
if (data) {
const hash = createHash('sha256').update(data, 'utf8');
return hash.digest('hex');
}
};
getSignature = (data) => {
const result = /\/\/ Signature: ([a-z\d]+)$/gm.exec(data);
return result?.[1];
};
getOperations = () => {
return this.operations;
};
createDir = (path) => {
const dir = dirname(path);
if (!this.exists(dir)) {
mkdirSync(dir, {
recursive: true
});
this.operations.created.push(dir);
output.info(i18n.t('core.fs.create.dir', { path: dir }));
}
};
write = (path, data, sign = false) => {
let payload = data;
if (sign && !path.endsWith('.json')) {
const signature = this.createSignature(data);
payload = `// Signature: ${signature}\n${payload}`;
}
writeFileSync(path, payload, {
encoding: 'utf8'
});
};
createFile = (path, data, sign) => {
const existsFile = this.exists(path);
if (!existsFile) {
this.createDir(path);
this.write(path, data, sign);
this.operations.created.push(path);
output.info(i18n.t('core.fs.create.file', { path }));
}
return existsFile;
};
updateFile = (path, data, sign) => {
if (this.createFile(path, data, sign)) {
const file = this.readFile(path);
if (file !== data) {
if (sign) {
const signature = this.createSignature(data);
if (this.getSignature(file) === signature) {
return;
}
}
this.write(path, data, sign);
this.operations.changed.push(path);
output.info(i18n.t('core.fs.create.update', { path }));
}
}
};
readFile = (path) => {
this.operations.read.push(path);
return readFileSync(path, {
encoding: 'utf8'
});
};
exists = (path) => {
this.operations.exists.push(path);
return existsSync(path);
};
remove = (path) => {
rmSync(path, {
force: true,
recursive: true
});
this.operations.removed.push(path);
};
readdirSync = readdirSync;
statSync = statSync;
}
export default new FS();