Last active
January 12, 2019 00:54
-
-
Save dsherret/2066e5fa9f9e72f84dc722fff052cf95 to your computer and use it in GitHub Desktop.
Programmatic refactor to prefix all private, protected, and internal class members with an underscore.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This script will look at all the exported class declarations from the main entrypoint of a library | |
// and ensure all private, protected, and @internal members are prefixed with an underscore. | |
import { Project, Node, SyntaxKind, TypeGuards, Scope, ClassMemberTypes, ParameterDeclaration } from "ts-simple-ast"; | |
const project = new Project({ tsConfigFilePath: "tsconfig.json" }); | |
const sourceFiles = project.getSourceFiles(); | |
for (const file of sourceFiles) | |
for (const classDec of file.getDescendantsOfKind(SyntaxKind.ClassDeclaration)) | |
for (const member of classDec.getMembers()) | |
doRenameIfNecessary(member); | |
project.save(); | |
function doRenameIfNecessary(node: ClassMemberTypes | ParameterDeclaration) { | |
// handle constructor parameter properties | |
if (TypeGuards.isConstructorDeclaration(node)) { | |
node.getParameters().forEach(doRenameIfNecessary); | |
return; | |
} | |
if (node.getScope() !== Scope.Protected && node.getScope() !== Scope.Private && !hasInternalDocTag(node)) | |
return; | |
if (node.getName().startsWith("_")) | |
return; | |
node.rename("_" + node.getName()); | |
} | |
function hasInternalDocTag(node: Node) { | |
// this checks if the node has an @internal jsdoc tag | |
return TypeGuards.isJSDocableNode(node) | |
&& node.getJsDocs().some(d => d.getTags().some(t => t.getTagName() === "internal")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment