├── .gitignore ├── LICENSE ├── README.md ├── _config.yml ├── ast-viewer.jpg ├── examples ├── fileA.ts ├── fileB.ts └── var_to_const_tramsform.ts ├── package.json ├── src ├── cli.ts ├── codemod.ts └── index.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | dist 64 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Wolk Software 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tsmod 2 | 3 | Inspired by the talk from [Cristina Bernardis](https://hmh.engineering/automating-javascript-refactoring-2f0a123702e8) about [jscodeshift](https://github.com/facebook/jscodeshift) at [JSDayIE](https://www.jsday.org/) I have released **tsmod**. A library that allows us to write automated refactoring code modifications powered by [David Sherret](https://twitter.com/DavidSherret)'s [ts-morph](https://github.com/dsherret/ts-morph). 4 | 5 | ## What is this about? 6 | 7 | If you have a very large codebase and you want to change something across many files this tool will allow you to write a script that will do the work for you. This is a good idea because it can save you time but also because it can be used by other members of the team as a valuable source of information. The transform scripts can also be shared online as open source. A common example is a migration script for a breaking change in the API of a framework. You can release the new version of the framework together with the transform scripts to help the users of the framework to upgrade their version with ease. 8 | 9 | ## Installation 10 | 11 | You can install this module as a global dependency using npm: 12 | 13 | ``` 14 | npm install -g tsmod 15 | ``` 16 | 17 | Please note that if you have never used TypeScript or ts-node you will also need them: 18 | 19 | ``` 20 | npm install -g typescript ts-node 21 | ``` 22 | 23 | The typescript module is the TypeScript compiler and the ts-node module is a version of Node.js that can work directly with TypeScript files (`.ts`) instead of using JavaScript files (`.js`). 24 | 25 | ## Usage 26 | 27 | The following command applies the transform `var_to_const_transform.ts` to the files `fileA.ts` and `fileB.ts`: 28 | 29 | ```sh 30 | tsmod -t var_to_const_transform.ts fileA.ts fileB.ts 31 | ``` 32 | 33 | > **Please Note**: A TypeScript compiler configuration file (`tsconfig.json`) file is expected in the current directory when you run the previous command. 34 | 35 | ## Transform example 36 | 37 | The transforms are powered by the `ts-morph` API. You can learn more about the API at [https://ts-morph.com](https://ts-morph.com/manipulation/). 38 | 39 | The following example changes all `var` variable declarations into `const` variable declarations: 40 | 41 | ```ts 42 | import { SourceFile, SyntaxKind, VariableDeclarationKind } from "ts-morph"; 43 | 44 | export const varToConstTransform = (file: SourceFile, transformArgs: {}) => { 45 | // Find all variable declarations in source file 46 | const variableStatements = file.getDescendantsOfKind( 47 | SyntaxKind.VariableStatement 48 | ); 49 | // Change var for const for each statement 50 | variableStatements.forEach(variableStatement => { 51 | const declarationKind = variableStatement.getDeclarationKind(); 52 | if (declarationKind === VariableDeclarationKind.Var) { 53 | variableStatement.setDeclarationKind(VariableDeclarationKind.Const); 54 | } 55 | }); 56 | // Return source code 57 | const updatedSourceCode = file.getText(); 58 | return updatedSourceCode; 59 | }; 60 | ``` 61 | 62 | The code is represented using a data structure known as Abstract Syntax Tree (AST). You can navigate and modify the AST to generate updated code. You can visit [https://ts-ast-viewer.com/](https://ts-ast-viewer.com/) to visualize the AST if you need help navigating it. 63 | 64 | ![](/ast-viewer.jpg) 65 | 66 | ## Options 67 | 68 | For additional help use the following: 69 | 70 | ```sh 71 | tsmod -h 72 | ``` 73 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-minimal -------------------------------------------------------------------------------- /ast-viewer.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WolkSoftware/tsmod/27347040832c8b53adf0a882b2cacfbbaa0a334b/ast-viewer.jpg -------------------------------------------------------------------------------- /examples/fileA.ts: -------------------------------------------------------------------------------- 1 | function foo() { 2 | var bar = "bar"; 3 | return bar; 4 | } 5 | -------------------------------------------------------------------------------- /examples/fileB.ts: -------------------------------------------------------------------------------- 1 | function bar() { 2 | var foo = "foo"; 3 | return foo; 4 | } 5 | -------------------------------------------------------------------------------- /examples/var_to_const_tramsform.ts: -------------------------------------------------------------------------------- 1 | import { SourceFile, SyntaxKind, VariableDeclarationKind } from "ts-morph"; 2 | 3 | export const varToConstTransform = (file: SourceFile, transformArgs: {}) => { 4 | // Find all variable declarations in source file 5 | const variableStatements = file.getDescendantsOfKind( 6 | SyntaxKind.VariableStatement 7 | ); 8 | // Change var for const for each statement 9 | variableStatements.forEach(variableStatement => { 10 | const declarationKind = variableStatement.getDeclarationKind(); 11 | if (declarationKind === VariableDeclarationKind.Var) { 12 | variableStatement.setDeclarationKind(VariableDeclarationKind.Const); 13 | } 14 | }); 15 | // Return source code 16 | const updatedSourceCode = file.getText(); 17 | return updatedSourceCode; 18 | }; 19 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tsmod", 3 | "version": "1.0.9", 4 | "description": "Refactor TypScript code programmatically using codemods", 5 | "main": "dist/src/index.js", 6 | "bin": { 7 | "tsmod": "dist/src/index.js" 8 | }, 9 | "scripts": { 10 | "build": "tsc -p tsconfig.json" 11 | }, 12 | "keywords": [], 13 | "author": "Remo Jansen", 14 | "license": "MIT", 15 | "dependencies": { 16 | "@types/node": "12.7.8", 17 | "arg": "4.1.1", 18 | "ts-morph": "4.0.1", 19 | "ts-node": "8.4.1", 20 | "typescript": "3.6.3" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | import arg from "arg"; 2 | 3 | enum CommandOptions { 4 | help = "--help", 5 | dry = "--dry", 6 | version = "--version", 7 | transform = "--transform", 8 | silent = "--silent", 9 | print = "--print", 10 | args = "--args" 11 | } 12 | 13 | enum CommandAliases { 14 | help = "-h", 15 | version = "-v", 16 | transform = "-t", 17 | dry = "-d", 18 | print = "-p", 19 | silent = "-s", 20 | args = "-a" 21 | } 22 | 23 | enum CommandDescriptions { 24 | help = "print this help and exit", 25 | version = "show more information about the transform process", 26 | transform = "path to the transform file (default: ./transform.ts)", 27 | dry = "dry run (no changes are made to files)", 28 | print = "print transformed files to stdout, useful for development", 29 | silent = "do not write to stdout or stderr", 30 | args = "arguments to be passed to the transform" 31 | } 32 | 33 | export function getVersion() { 34 | return "1.0.9"; 35 | } 36 | 37 | export function printHelp() { 38 | const keys: (keyof typeof CommandOptions)[] = Object.keys( 39 | CommandOptions 40 | ) as any; 41 | const output = [ 42 | "\nUsage: tsmod [OPTION]... FILE_PATH...", 43 | " or: tsmod [OPTION]... -t TRANSFORM_PATH FILE_PATH...\n", 44 | "Apply transform logic in TRANSFORM_PATH to every FILE_PATH\n", 45 | "Options:", 46 | ...keys.map( 47 | k => 48 | ` ${CommandAliases[k]}, ${CommandOptions[k]} ${CommandDescriptions[k]}` 49 | ) 50 | ]; 51 | output.forEach(l => console.log(l)); 52 | } 53 | 54 | export function parseArgumentsIntoOptions(rawArgs: string[]) { 55 | const args = arg( 56 | { 57 | [CommandOptions.help]: Boolean, 58 | [CommandOptions.dry]: Boolean, 59 | [CommandOptions.version]: Boolean, 60 | [CommandOptions.transform]: String, 61 | [CommandOptions.silent]: Boolean, 62 | [CommandOptions.print]: Boolean, 63 | [CommandOptions.args]: [String], 64 | [CommandAliases.help]: CommandOptions.help, 65 | [CommandAliases.version]: CommandOptions.version, 66 | [CommandAliases.transform]: CommandOptions.transform, 67 | [CommandAliases.dry]: CommandOptions.dry, 68 | [CommandAliases.print]: CommandOptions.print, 69 | [CommandAliases.silent]: CommandOptions.silent, 70 | [CommandAliases.args]: CommandOptions.args 71 | }, 72 | { 73 | argv: rawArgs.slice(2) 74 | } 75 | ); 76 | 77 | const defaultTransform = "./transform.ts"; 78 | const transformArgs = args[CommandOptions.args]; 79 | 80 | return { 81 | paths: args["_"], 82 | transform: args[CommandOptions.transform] || defaultTransform, 83 | help: args[CommandOptions.help] || false, 84 | version: args[CommandOptions.version] || false, 85 | dry: args[CommandOptions.dry] || false, 86 | print: args[CommandOptions.print] || false, 87 | silent: args[CommandOptions.silent] || false, 88 | args: 89 | transformArgs === undefined 90 | ? [] 91 | : transformArgs.map(a => { 92 | const parts = a.split("="); 93 | return { 94 | [parts[0]]: parts[1] 95 | }; 96 | }) 97 | }; 98 | } 99 | 100 | export type Options = ReturnType; 101 | -------------------------------------------------------------------------------- /src/codemod.ts: -------------------------------------------------------------------------------- 1 | import { Project, SourceFile } from "ts-morph"; 2 | import { Options } from "./cli"; 3 | import { normalize, join, parse } from "path"; 4 | import { readFile } from "fs"; 5 | import { promisify } from "util"; 6 | import { transpileModule } from "typescript"; 7 | 8 | export type Transform = (file: SourceFile, transformArgs: {}) => string; 9 | const readFileAsync = promisify(readFile); 10 | const tsConfigFilePath = join(process.cwd(), "tsconfig.json"); 11 | 12 | export async function loadTransform( 13 | transformPath: string 14 | ): Promise { 15 | const actualPath = join(process.cwd(), normalize(transformPath)); 16 | const buffer = await readFileAsync(actualPath); 17 | const tsSource = buffer.toString(); 18 | const jsSource = transpileModule(tsSource, {}).outputText; 19 | const tramsform = eval(jsSource); 20 | return tramsform; 21 | } 22 | 23 | export function runCodemod( 24 | filePath: string, 25 | transform: Transform, 26 | transformArgs: {}, 27 | options: Options 28 | ) { 29 | try { 30 | const project = new Project({ 31 | tsConfigFilePath: tsConfigFilePath, 32 | addFilesFromTsConfig: false 33 | }); 34 | project.addExistingSourceFile(filePath); 35 | const personFile = project.getSourceFile(filePath); 36 | if (personFile) { 37 | return transform(personFile, transformArgs); 38 | } 39 | } catch (err) { 40 | if (!options.silent) { 41 | throw err; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { parseArgumentsIntoOptions, printHelp, getVersion } from "./cli"; 2 | import { runCodemod, loadTransform } from "./codemod"; 3 | import { writeFile } from "fs"; 4 | import { promisify } from "util"; 5 | 6 | const writeFileAsync = promisify(writeFile); 7 | 8 | export async function main(args: string[]) { 9 | const options = parseArgumentsIntoOptions(args); 10 | 11 | if (options.version) { 12 | const version = getVersion(); 13 | console.log(`v${version}`); 14 | } else if (options.help) { 15 | printHelp(); 16 | } else { 17 | const transform = await loadTransform(options.transform); 18 | if (transform === undefined) { 19 | if (!options.silent) { 20 | throw new Error(`Invalid transform ${options.transform}`); 21 | } 22 | } else { 23 | Promise.all( 24 | options.paths.map(async path => { 25 | const source = runCodemod(path, transform, options.args, options); 26 | if (options.print) { 27 | console.log(`${path}\n\n${source}`); 28 | } 29 | if (!options.dry) { 30 | return await writeFileAsync(path, source); 31 | } 32 | }) 33 | ); 34 | } 35 | } 36 | } 37 | 38 | (async () => { 39 | await main(process.argv); 40 | })(); 41 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | // "incremental": true, /* Enable incremental compilation */ 5 | "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */, 6 | "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, 7 | // "lib": [], /* Specify library files to be included in the compilation. */ 8 | // "allowJs": true, /* Allow javascript files to be compiled. */ 9 | // "checkJs": true, /* Report errors in .js files. */ 10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 11 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 12 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 13 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 14 | // "outFile": "./", /* Concatenate and emit output to single file. */ 15 | "outDir": "./dist" /* Redirect output structure to the directory. */, 16 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 17 | // "composite": true, /* Enable project compilation */ 18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 19 | // "removeComments": true, /* Do not emit comments to output. */ 20 | // "noEmit": true, /* Do not emit outputs. */ 21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 24 | 25 | /* Strict Type-Checking Options */ 26 | "strict": true /* Enable all strict type-checking options. */, 27 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 28 | // "strictNullChecks": true, /* Enable strict null checks. */ 29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 34 | 35 | /* Additional Checks */ 36 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 38 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 40 | 41 | /* Module Resolution Options */ 42 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 46 | // "typeRoots": [], /* List of folders to include type definitions from. */ 47 | // "types": [], /* Type declaration files to be included in compilation. */ 48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 49 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 52 | 53 | /* Source Map Options */ 54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 58 | 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | } 63 | } 64 | --------------------------------------------------------------------------------