This repository has been archived by the owner on Jan 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessFile.ts
44 lines (34 loc) · 1.5 KB
/
processFile.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { mCExecutinTreeGenerator } from "./mCExecutinTreeGenerator";
import { writeFileSync, existsSync, readFileSync } from "fs";
import { Interpreter } from "./Intrerpreter";
import * as Path from "path";
import { throwReturn } from "./common";
import { TNode } from "./ExecutionTree";
import { validate } from "jsonschema";
import * as treeSchema from "./mCTree.schema.json";
import chalk from "chalk";
// tslint:disable: no-console
export const processFile = (input: string, output: "" | string, interpret: boolean, forceOverwrite?: boolean) => {
if (!existsSync(input))
throw new Error(`Invalid input, file doesn't exists: ${input}`);
const ext = Path.extname(input).slice(1).toLowerCase();
const tree =
(ext === "json") && readJsonTreeFile(input)
|| (ext === "mc") && mCExecutinTreeGenerator.run(input)
|| throwReturn(`invalid file extension ${ext}`)
;
if ((ext !== "json") && output
&& (!existsSync(output) || forceOverwrite ||
console.warn(chalk.yellow(`Output file ${output} already exists. Use -f argument if you want overwrite it.`))))
writeFileSync(output, JSON.stringify(tree, undefined, 2));
if (interpret)
new Interpreter(tree).start();
};
const readJsonTreeFile = (file: string): TNode => {
const json = JSON.parse(readFileSync(file).toString());
const validationRes = validate(json, treeSchema);
if (validationRes.errors.length) {
throw new Error(`Error reading json file ${file} \n${validationRes.errors.join("\n")}`);
}
return json as TNode;
};