Compare commits

...

1 commit

Author SHA1 Message Date
Matt Seccafien dbe0ada3b8 feat: CLI display if file changed 2021-11-11 10:38:32 +01:00
3 changed files with 34 additions and 12 deletions

View file

@ -1,16 +1,19 @@
import {resolve, join, isAbsolute, dirname, relative} from 'path';
import {readFile, writeFile, mkdirp, pathExists, emptyDir} from 'fs-extra';
import {RunError} from '../utilities/error';
import {formatFile} from '../utilities';
export interface FileResult {
path: string;
overwritten: boolean;
diff: boolean;
}
export class Fs {
root: string;
files = new Map<string, string>();
// TODO: Implement dry-run behaviour by keeping track of original sources
readCache = new Map<string, string>();
constructor(root: string) {
@ -28,12 +31,19 @@ export class Fs {
return this.files.get(fullPath)!;
}
if (this.readCache.has(fullPath)) {
return this.readCache.get(fullPath)!;
const exists = await this.exists(path);
if (!exists) {
throw new RunError(
`Tried to operate on file at ${path}, but it does not exist.`
);
}
const contents = await readFile(fullPath, 'utf8');
this.readCache.set(fullPath, contents);
if (!this.readCache.has(fullPath)) {
this.readCache.set(fullPath, contents);
}
return contents;
}
@ -50,8 +60,12 @@ export class Fs {
await mkdirp(dirname(path));
}
await writeFile(path, formatFile(contents));
yield {path: this.relativePath(path), overwritten: exists};
const oldFile = this.readCache.get(path);
const formattedFile = formatFile(contents);
const diff = oldFile ? formatFile(oldFile) !== formattedFile : false;
await writeFile(path, formatFile(formattedFile));
yield {path: this.relativePath(path), overwritten: exists, diff: diff};
}
}

View file

@ -114,10 +114,15 @@ export class Cli implements Ui {
);
}
printFile({path, overwritten}: FileResult) {
printFile({path, overwritten, diff}: FileResult) {
const overwrote = overwritten
? chalk.redBright``
: chalk.greenBright``;
this.say([overwrote, path].join(''));
? chalk.redBright`• Overwrote`
: chalk.greenBright`• Wrote new`;
const difference = diff ? `` : chalk.cyanBright`• No change`;
this.say(
[overwrote, difference, chalk.underline.whiteBright(path)].join(' ')
);
}
}

View file

@ -1,3 +1,6 @@
export class NotImplementedError extends Error {}
export class InputError extends Error {}
export class UnknownError extends Error {}
// TODO: Make these more meaningful and logging behavior
export class BaseError extends Error {}
export class NotImplementedError extends BaseError {}
export class InputError extends BaseError {}
export class UnknownError extends BaseError {}
export class RunError extends BaseError {}