UNPKG

ts-simple-ast

Version:

TypeScript compiler wrapper for AST navigation and code generation.

67 lines (66 loc) 2.82 kB
"use strict"; 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 ts = require("typescript"); var utils_1 = require("./../../utils"); /** * Replaces text in a source file. Good for renaming identifiers. Not good for creating new nodes! * @param sourceFile - Source file to replace in. * @param replaceStart - Start of where to replace. * @param replaceEnd - End of where to replace. * @param newText - The new text to go in place. */ function replaceNodeText(sourceFile, replaceStart, replaceEnd, newText) { var difference = newText.length - (replaceEnd - replaceStart); replaceForNode(sourceFile); sourceFile.global.resetProgram(); sourceFile.setIsSaved(false); function replaceForNode(node) { var currentStart = utils_1.TypeGuards.isSourceFile(node) ? 0 : node.getStart(); var compilerNode = node.compilerNode; try { // do the children first so that the underlying _children array is filled in based on the source file for (var _a = __values(node.getChildren()), _b = _a.next(); !_b.done; _b = _a.next()) { var child = _b.value; replaceForNode(child); } } 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; } } if (node.containsRange(replaceStart, replaceEnd)) { var text = compilerNode.text; if (text != null) { var relativeStart = replaceStart - currentStart; var relativeEnd = replaceEnd - currentStart; var newNodeText = text.substring(0, relativeStart) + newText + text.substring(relativeEnd); if (compilerNode.kind === ts.SyntaxKind.SourceFile) compilerNode.text = newNodeText; else if (compilerNode.escapedText != null) compilerNode.escapedText = newNodeText; else utils_1.Logger.warn("Unhandled scenario when replacing node text: Node did not have an escapedText property."); } compilerNode.end += difference; } else if (currentStart > replaceStart) { compilerNode.pos += difference; compilerNode.end += difference; } var e_1, _c; } } exports.replaceNodeText = replaceNodeText;