@atomist/automation-client
Version:
Atomist API for software low-level client
61 lines • 2.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("../../internal/util/logger");
const projectUtils_1 = require("./projectUtils");
/**
* Manipulate the contents of the given JSON file within the project,
* using its object form and writing back using the same formatting.
* See the manipulate function.
* @param {P} p
* @param {string} jsonPath JSON file path. This function will do nothing
* without error if the file is ill-formed or not found.
* @param {JsonManipulation} manipulation
* @return {Promise<P extends ProjectAsync>}
*/
function doWithJson(p, jsonPath, manipulation) {
return projectUtils_1.doWithFiles(p, jsonPath, file => {
return file.getContent()
.then(content => {
const newContent = manipulate(content, manipulation, jsonPath);
return file.setContent(newContent)
.then(() => p);
});
});
}
exports.doWithJson = doWithJson;
const spacePossibilities = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, " ", " ", "\t"];
/**
* Update the object form of the given JSON content and write
* it back with minimal changes
* @param {string} jsonIn
* @param {(jsonObj: any) => Object} manipulation
* @return {string}
*/
function manipulate(jsonIn, manipulation, context = "") {
if (!jsonIn) {
return jsonIn;
}
try {
const newline = jsonIn.endsWith("\n"); // does this work on Windows?
const jsonToCompare = newline ? jsonIn.replace(/\n$/, "") : jsonIn;
const obj = JSON.parse(jsonIn);
let space = 2;
for (const sp of spacePossibilities) {
const maybe = JSON.stringify(obj, null, sp);
if (jsonToCompare === maybe) {
logger_1.logger.debug(`Definitely inferred space as [${sp}]`);
space = sp;
break;
}
}
logger_1.logger.debug(`Inferred space is [${space}]`);
manipulation(obj);
return JSON.stringify(obj, null, space) + (newline ? "\n" : "");
}
catch (e) {
logger_1.logger.warn("Syntax error parsing supposed JSON (%s). Context:[%s]. Alleged JSON:\n%s", e, context, jsonIn);
return jsonIn;
}
}
exports.manipulate = manipulate;
//# sourceMappingURL=jsonUtils.js.map