2020-07-29 13:42:51 +00:00
|
|
|
import {
|
|
|
|
readFileSync,
|
|
|
|
writeFileSync
|
|
|
|
} from "./filesystem";
|
2020-09-18 14:39:31 +00:00
|
|
|
import { sortElements } from "./types";
|
2020-07-29 13:42:51 +00:00
|
|
|
|
2020-08-06 19:17:38 +00:00
|
|
|
export function isValidJSON(path: string): boolean {
|
|
|
|
try {
|
2020-09-18 14:39:31 +00:00
|
|
|
const rawdata = readFileSync(path);
|
2020-08-06 19:17:38 +00:00
|
|
|
JSON.parse(rawdata);
|
|
|
|
return true;
|
|
|
|
} catch {
|
2020-09-18 14:39:31 +00:00
|
|
|
return false;
|
2020-07-29 13:42:51 +00:00
|
|
|
}
|
2020-08-06 19:17:38 +00:00
|
|
|
}
|
|
|
|
|
2020-09-18 14:39:31 +00:00
|
|
|
export function formatJson(content: unknown): string {
|
2020-08-06 19:17:38 +00:00
|
|
|
return JSON.stringify(content, null, 4);
|
|
|
|
}
|
|
|
|
|
2020-09-18 14:39:31 +00:00
|
|
|
export function formatSortJson(content: unknown[]): string {
|
2020-08-06 19:17:38 +00:00
|
|
|
return JSON.stringify(sortElements(content), null, 4);
|
|
|
|
}
|
|
|
|
|
2020-09-18 14:39:31 +00:00
|
|
|
export function formatJsonFile(filename: string): void {
|
2020-08-06 19:17:38 +00:00
|
|
|
writeFileSync(filename, formatJson(JSON.parse(readFileSync(filename))));
|
|
|
|
console.log(`Formatted json file ${filename}`);
|
2020-07-29 13:42:51 +00:00
|
|
|
}
|
|
|
|
|
2020-09-18 14:39:31 +00:00
|
|
|
export function formatSortJsonFile(filename: string): void {
|
2020-08-06 19:17:38 +00:00
|
|
|
writeFileSync(filename, formatSortJson(JSON.parse(readFileSync(filename))));
|
2020-07-29 13:42:51 +00:00
|
|
|
console.log(`Formatted json file ${filename}`);
|
|
|
|
}
|
|
|
|
|
2020-09-18 14:39:31 +00:00
|
|
|
export function readJsonFile(path: string): unknown {
|
2020-08-06 19:17:38 +00:00
|
|
|
return JSON.parse(readFileSync(path));
|
|
|
|
}
|
|
|
|
|
2020-09-18 14:39:31 +00:00
|
|
|
export function writeJsonFile(path: string, data: unknown): void {
|
2020-07-29 13:42:51 +00:00
|
|
|
writeFileSync(path, JSON.stringify(data, null, 4));
|
|
|
|
}
|