ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
52 lines (51 loc) • 2.2 kB
JavaScript
;
var __values = (this && this.__values)/* istanbul ignore next */ || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./../../utils");
var tree_1 = require("./../tree");
function replaceSourceFileTextForRename(opts) {
var sourceFile = opts.sourceFile, renameLocations = opts.renameLocations, newName = opts.newName;
var fullText = sourceFile.getFullText();
var newFileText = fullText;
var difference = 0;
try {
for (var _a = __values(renameLocations.map(function (l) { return l.getTextSpan(); })), _b = _a.next(); !_b.done; _b = _a.next()) {
var textSpan = _b.value;
var start = textSpan.getStart();
var end = start + textSpan.getLength();
start -= difference;
end -= difference;
newFileText = newFileText.substring(0, start) + newName + newFileText.substring(end);
difference += textSpan.getLength() - newName.length;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
}
finally { if (e_1) throw e_1.error; }
}
var tempSourceFile = sourceFile.global.compilerFactory.createTempSourceFileFromText(newFileText, { filePath: sourceFile.getFilePath() });
try {
tree_1.replaceTreeForgettingChangedNodes(sourceFile, tempSourceFile);
}
catch (ex) {
utils_1.Logger.warn("Could not replace tree, so forgetting all nodes instead. Message: " + ex);
// forget all the source file's nodes
sourceFile.getChildSyntaxListOrThrow().forget();
// replace the source file with the temporary source file
sourceFile.global.compilerFactory.replaceCompilerNode(sourceFile, tempSourceFile.compilerNode);
}
var e_1, _c;
}
exports.replaceSourceFileTextForRename = replaceSourceFileTextForRename;