UNPKG

ts-simple-ast

Version:

TypeScript compiler wrapper for AST navigation and code generation.

56 lines (55 loc) 2.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var doManipulation_1 = require("./doManipulation"); var nodeHandlers_1 = require("./../nodeHandlers"); var textManipulators_1 = require("./../textManipulators"); /** * Replaces text in a source file. Will forget any changed 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) { doManipulation_1.doManipulation(sourceFile, new textManipulators_1.InsertionTextManipulator({ insertPos: replaceStart, newText: newText, replacingLength: replaceEnd - replaceStart }), new nodeHandlers_1.NodeHandlerFactory().getForForgetChanged(sourceFile.global.compilerFactory)); } exports.replaceNodeText = replaceNodeText; /** * Replaces the text in a source file and assumes only the nodes will shift (no tree structure should change). * * This is very useful when making formatting changes that won't change the AST structure. */ function replaceSourceFileTextForFormatting(opts) { var sourceFile = opts.sourceFile, newText = opts.newText; doManipulation_1.doManipulation(sourceFile, new textManipulators_1.FullReplacementTextManipulator(newText), new nodeHandlers_1.NodeHandlerFactory().getForStraightReplacement(sourceFile.global.compilerFactory)); } exports.replaceSourceFileTextForFormatting = replaceSourceFileTextForFormatting; /** * Replaces the text in a source file based on rename locations. */ function replaceSourceFileTextForRename(opts) { var sourceFile = opts.sourceFile, renameLocations = opts.renameLocations, newName = opts.newName; var nodeHandlerFactory = new nodeHandlers_1.NodeHandlerFactory(); doManipulation_1.doManipulation(sourceFile, new textManipulators_1.RenameLocationTextManipulator(renameLocations, newName), nodeHandlerFactory.getForTryOrForget(nodeHandlerFactory.getForForgetChanged(sourceFile.global.compilerFactory))); } exports.replaceSourceFileTextForRename = replaceSourceFileTextForRename; /** * Replaces a node text while possibly creating new child nodes. */ function replaceTextPossiblyCreatingChildNodes(opts) { var replacePos = opts.replacePos, replacingLength = opts.replacingLength, newText = opts.newText, parent = opts.parent; doManipulation_1.doManipulation(parent.sourceFile, new textManipulators_1.InsertionTextManipulator({ insertPos: replacePos, replacingLength: replacingLength, newText: newText }), new nodeHandlers_1.NodeHandlerFactory().getForRange({ parent: parent, start: replacePos, end: replacePos + newText.length })); } exports.replaceTextPossiblyCreatingChildNodes = replaceTextPossiblyCreatingChildNodes;