/ src / lib / yamlExtend.ts
yamlExtend.ts
 1  import yaml from "js-yaml";
 2  import { readFileSync, writeFileSync } from "fs";
 3  
 4  const options = Object.assign({}, (yaml as any).types.int.options);
 5  
 6  options.construct = (data: any) => {
 7    let value = data,
 8      sign = 1n,
 9      ch;
10  
11    if (value.indexOf("_") !== -1) {
12      value = value.replace(/_/g, "");
13    }
14  
15    ch = value[0];
16  
17    if (ch === "-" || ch === "+") {
18      if (ch === "-") sign = -1n;
19      value = value.slice(1);
20      ch = value[0];
21    }
22  
23    return sign * BigInt(value);
24  };
25  
26  options.predicate = (object: object) =>
27    Object.prototype.toString.call(object) === "[object BigInt]" ||
28    (yaml as any).types.int.options.predicate(object);
29  
30  const BigIntType = new yaml.Type("tag:yaml.org,2002:int", options);
31  
32  const SCHEMA_BIGINT = yaml.DEFAULT_SCHEMA.extend({
33    implicit: [BigIntType],
34  });
35  
36  export function loadYamlFile(filePath: string, bigint = true) {
37    const contents = readFileSync(filePath, { encoding: "utf8", flag: "r" });
38    const opts = bigint ? { schema: SCHEMA_BIGINT } : {};
39    return yaml.load(contents, opts);
40  }
41  export function writeYamlFile(filePath: string, obj: object) {
42    const encoded = yaml.dump(obj, {
43      schema: SCHEMA_BIGINT,
44      sortKeys: true,
45      condenseFlow: true,
46      forceQuotes: true,
47    });
48    console.log(`Writing yaml file ${filePath}`);
49    writeFileSync(filePath, encoded);
50  }