UNPKG

2.29 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const logger_1 = require("../../util/logger");
4const projectUtils_1 = require("./projectUtils");
5/**
6 * Manipulate the contents of the given JSON file within the project,
7 * using its object form and writing back using the same formatting.
8 * See the manipulate function.
9 * @param {P} p
10 * @param {string} jsonPath JSON file path. This function will do nothing
11 * without error if the file is ill-formed or not found.
12 * @param {JsonManipulation} manipulation
13 * @return {Promise<P extends ProjectAsync>}
14 */
15function doWithJson(p, jsonPath, manipulation) {
16 return projectUtils_1.doWithFiles(p, jsonPath, file => {
17 return file.getContent()
18 .then(content => {
19 const newContent = manipulate(content, manipulation, jsonPath);
20 return file.setContent(newContent)
21 .then(() => p);
22 });
23 });
24}
25exports.doWithJson = doWithJson;
26const spacePossibilities = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, " ", " ", "\t"];
27/**
28 * Update the object form of the given JSON content and write
29 * it back with minimal changes
30 * @param {string} jsonIn
31 * @param {(jsonObj: any) => Object} manipulation
32 * @return {string}
33 */
34function manipulate(jsonIn, manipulation, context = "") {
35 if (!jsonIn) {
36 return jsonIn;
37 }
38 try {
39 const newline = jsonIn.endsWith("\n"); // does this work on Windows?
40 const jsonToCompare = newline ? jsonIn.replace(/\n$/, "") : jsonIn;
41 const obj = JSON.parse(jsonIn);
42 let space = 2;
43 for (const sp of spacePossibilities) {
44 const maybe = JSON.stringify(obj, null, sp);
45 if (jsonToCompare === maybe) {
46 logger_1.logger.debug(`Definitely inferred space as [${sp}]`);
47 space = sp;
48 break;
49 }
50 }
51 logger_1.logger.debug(`Inferred space is [${space}]`);
52 manipulation(obj);
53 return JSON.stringify(obj, null, space) + (newline ? "\n" : "");
54 }
55 catch (e) {
56 logger_1.logger.warn("Syntax error parsing supposed JSON (%s). Context:[%s]. Alleged JSON:\n%s", e, context, jsonIn);
57 return jsonIn;
58 }
59}
60exports.manipulate = manipulate;
61//# sourceMappingURL=jsonUtils.js.map
\No newline at end of file