///
import {createHash} from "crypto";
import {pathExistsSync, readFile, readFileSync, writeFile, writeFileSync} from "fs-extra";
function md5(data: Buffer|string, charset?: 'utf8') {
return createHash('md5')
.update(data, charset)
.digest('hex')
}
export class FileChange {
public readonly fileExists: boolean;
private knownMd5: string;
private fileBuffer: Buffer;
private md5Value: string;
constructor(private file: string, private md5File: string) {
this.fileExists = pathExistsSync(this.file);
if (pathExistsSync(this.md5File)) {
this.knownMd5 = readFileSync(this.md5File, {encoding: 'utf8'})
} else {
this.knownMd5 = null;
}
}
public get changed() {
// console.log(this.fileExists, this.knownMd5, this.md5, this.knownMd5);
return !(
this.fileExists &&
this.knownMd5 &&
this.md5 === this.knownMd5
);
}
public get md5(): string {
if (!this.md5Value) {
this.md5Value = md5(this.readFileSync());
}
return this.md5Value;
}
public readFileSync() {
if (!this.fileBuffer) {
this.fileBuffer = readFileSync(this.file);
}
return this.fileBuffer;
}
public async readFile(): Promise {
if (!this.fileBuffer) {
this.fileBuffer = await readFile(this.file);
}
return this.fileBuffer;
}
public writeFileSync(newContent: string) {
const newMd5 = md5(newContent, 'utf8');
if (newMd5 !== this.knownMd5) {
writeFileSync(this.file, newContent, 'utf8');
this.md5Value = newMd5;
this.fileBuffer = new Buffer(newContent, 'utf8');
}
}
public async writeFile(newContent: string): Promise {
const newMd5 = md5(newContent, 'utf8');
if (newMd5 !== this.knownMd5) {
await writeFile(this.file, newContent, {encoding: 'utf8'});
this.md5Value = newMd5;
this.fileBuffer = new Buffer(newContent, 'utf8');
}
}
store() {
this.knownMd5 = md5(this.readFileSync());
this.writeMd5Sync();
}
private writeMd5(): Promise {
return writeFile(this.md5File, this.knownMd5);
}
private writeMd5Sync(): void {
writeFileSync(this.md5File, this.knownMd5);
}
}