unmock-core
Version:
[][npmjs] [](https://circleci.com/gh/unmock/unmock-js) [](h
85 lines • 3.39 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const debug_1 = require("debug");
const fs = require("fs");
const lodash_1 = require("lodash");
const os = require("os");
const path = require("path");
const debugLog = debug_1.default("unmock:snapshotter:writer");
exports.format = (snapshot) => {
const withStringTs = Object.assign(Object.assign({}, snapshot), { timestamp: snapshot.timestamp.toISOString() });
return JSON.stringify(withStringTs);
};
const ENCODING = "utf-8";
const SNAPSHOT_FILENAME = "snapshots.jsonl";
const createTmpDirIn = (snapshotFolder) => {
return fs.mkdtempSync(`${snapshotFolder}${path.sep}`);
};
exports.parseSnapshot = (str) => {
const parsed = JSON.parse(str);
return Object.assign(Object.assign({}, parsed), { timestamp: new Date(parsed.timestamp) });
};
class FsSnapshotWriterReader {
constructor(snapshotFolder) {
this.snapshotFolder = snapshotFolder;
this.outputFolder = createTmpDirIn(snapshotFolder);
this.outputFile = path.join(this.outputFolder, SNAPSHOT_FILENAME);
}
static readFileContents(filename) {
const fileContents = fs.readFileSync(filename, ENCODING);
const lines = fileContents.split(os.EOL);
return lines.filter(line => !!line.trim()).map(line => exports.parseSnapshot(line));
}
write(snapshot) {
const contents = exports.format(snapshot);
if (!fs.existsSync(this.outputFolder)) {
fs.mkdirSync(this.outputFolder);
}
if (!fs.existsSync(this.outputFile)) {
debugLog(`Writing to new file ${this.outputFile}`);
fs.writeFileSync(this.outputFile, contents + os.EOL, {
encoding: ENCODING,
});
}
else {
debugLog(`Appending to file ${this.outputFile}`);
fs.appendFileSync(this.outputFile, contents + os.EOL, {
encoding: ENCODING,
});
}
}
findSnapshotFiles() {
return fs
.readdirSync(this.snapshotFolder)
.map(filename => path.join(this.snapshotFolder, filename))
.filter(file => fs.lstatSync(file).isDirectory())
.map(dir => path.join(dir, SNAPSHOT_FILENAME))
.filter(filename => fs.existsSync(filename) && fs.lstatSync(filename).isFile());
}
read() {
if (!fs.existsSync(this.snapshotFolder)) {
return [];
}
const snapshotFiles = this.findSnapshotFiles();
const snapshots = snapshotFiles.map(filename => FsSnapshotWriterReader.readFileContents(filename));
return lodash_1.sortBy(lodash_1.flatten(snapshots), (snapshot) => snapshot.timestamp.getTime());
}
deleteSnapshots() {
if (!fs.existsSync(this.snapshotFolder)) {
return;
}
this.findSnapshotFiles().forEach(filename => {
fs.unlinkSync(filename);
const directory = path.dirname(filename);
if (fs.readdirSync(directory).length === 0) {
debugLog(`Deleting directory: ${directory}`);
fs.rmdirSync(directory);
}
else {
debugLog(`Directory not empty, not removing: ${directory}`);
}
});
}
}
exports.FsSnapshotWriterReader = FsSnapshotWriterReader;
//# sourceMappingURL=snapshot-writer-reader.js.map