iot-ux-fluent-css/codegen/outputWritter.ts

71 строка
2.3 KiB
TypeScript

import { EOL } from "os";
import { promisify } from "util";
import { writeFile, mkdir } from "fs";
import { dirname } from "path";
const OUTPUT_INDENT = ' ';
export class OutputWritter {
private size: number;
private buffer: Buffer;
private head: number;
private outputFilePath: string;
constructor(filePath: string) {
this.size = 1024;
this.buffer = Buffer.alloc(this.size);
this.head = 0;
this.outputFilePath = filePath;
this.ensureSizeAvailable = this.ensureSizeAvailable.bind(this);
this.writeLine = this.writeLine.bind(this);
this.flush = this.flush.bind(this);
this.writeAutogenComment = this.writeAutogenComment.bind(this);
this.writeAutogenComment();
}
private ensureSizeAvailable(size: number) {
if (this.buffer.length - this.head < size) {
var oldBuffer = this.buffer;
var newSize = this.size + (this.size >> 1) + size;
this.buffer = Buffer.alloc(newSize);
oldBuffer.copy(this.buffer);
this.size = newSize;
}
}
public writeLine(line: string = '', indentationLevel: number = 0) {
if (indentationLevel) {
this.ensureSizeAvailable(4 * indentationLevel);
for (let i = 0; i < indentationLevel; i++) {
this.buffer.write(OUTPUT_INDENT, this.head);
this.head += 4;
}
}
const lineLength = Buffer.byteLength(line);
this.ensureSizeAvailable(lineLength);
this.buffer.write(line, this.head);
this.head += lineLength;
const eolLength = Buffer.byteLength(EOL);
this.ensureSizeAvailable(eolLength);
this.buffer.write(EOL, this.head);
this.head += eolLength;
}
private writeAutogenComment() {
this.writeLine('/**');
this.writeLine(' * THIS IS AN AUTOGENERATED FILE, YOU SHOULD NOT MODIFY IT MANUALLY');
this.writeLine(' * TO REGENERATE THIS FILE RUN `NPM RUN CODEGEN`.');
this.writeLine(' */');
}
public async flush() {
await promisify(mkdir)(dirname(this.outputFilePath), { recursive: true });
await promisify(writeFile)(this.outputFilePath, this.buffer.slice(0, this.head), { flag: 'w+', encoding: 'utf8' });
}
}