Share
CodeFest 2019. Александр Мышов (Яндекс) — Автоматический рефакторинг кода с помощью codemodes
Иногда бывает так, что изменение сигнатуры одной функции или обновление зависимости может повлечь за собой несколько дней скрупулёзной работы. Для упрощения и автоматизации этого процесса, можно написать свой codemode. Сodemode — это скрипт, работающий с абстрактным синтаксическим деревом (ast) javascript. Цель codemode — автоматизировать рефакторинг кода.
В своём докладе я расскажу про jscodeshift — тулкит для написания codemodes. Покажу и разберу несколько примеров codemodes: начиная простыми и заканчивая теми, которые могут быть использованы в вашем проекте. Вы увидите, что работа с ast на самом деле не такая уж и сложная задача, как может показаться на первый взгляд, и что владение этим инструментом может дать очень сильный прирост вашей эффективности.
CodeFest
Transcript
101 slides
-
Что будет? >2 › Зачем нужны кодмоды › Немного про
AST › Описание jscodeshift › Примеры кодмодов -
Обновление библиотеки >4 // №1 (было/стало) this.createPageObject(pageObject, this.browser); this.createPageObject(pageObject); //
№2 (было/стало) this.createPageObject(pageObject, someParent); this.createPageObject(pageObject, { parent: 'someParent', }); // №3 (было/стало) this.createPageObject(pageObject, someParent, `some${val}Root`); this.createPageObject(pageObject, { parent: someParent, root: `some${val}Root`, }); -
Использование нового стандарта (было) >5 var React = require('react'); var
Clock = React.createClass({ getInitialState: function () { return { date: new Date() }; }, render: function () { return ( <div> Сейчас {this.state.date.toLocaleTimeString()} </div> ); } }); module.exports = Clock; -
Использование нового стандарта (стало) >6 import React, {Component} from 'react';
class Clock extends Component { constructor(props) { super(props); this.state = {date: new Date()}; } render() { return ( <div> Сейчас {this.state.date.toLocaleTimeString()} </div> ); } } export default Clock; -
Проблемы >7 › Рефакторинг может быть сложным и долгим ›
Обычный поиск и замена слишком просты › Регулярные выражения не помогут в сложных случаях › Ограниченные виды рефакторинга с помощью IDE › Нет автоматизации -
{ program: { type: "Program", body: [ { type: "VariableDeclaration",
declarations: [ { type: "VariableDeclarator", id: { type: "Identifier", name: "two" }, init: { type: "BinaryExpression", operator: "+", left: { type: "Literal", value: 1, raw: "1" }, right: { type: "Literal", value: 1, raw: "1" Представление AST в JS >13 -
Примеры использования AST >15 › Плагины для babel › Eslint
правила › Кодмоды › и т.п. -
Структура jscodeshift >20 › парсеры - babel/parser, flow › ast-types
- библиотека для создания узлов AST-дерева › recast - библиотека для красивого форматирования кода -
Основные понятия >21 › Node - узел ast-дерева › Path
- обёртка над узлом, позволяющая обходить дерево › Collection - набор объектов типа path с методами трансформации -
Блаблафикатор (codemod) >24 export default function transformer(file, api) { const
j = api.jscodeshift; return j(file.source) .find(j.Identifier) .replaceWith( j.identifier('bla') ) .toSource(); } -
Блаблафикатор (codemod) >25 export default function transformer(file, api) { const
j = api.jscodeshift; return j(file.source) .find(j.Identifier) .replaceWith( j.identifier('bla') ) .toSource(); } -
Блаблафикатор (codemod) >26 export default function transformer(file, api) { const
j = api.jscodeshift; return j(file.source) .find(j.Identifier) .replaceWith( j.identifier('bla') ) .toSource(); } -
Блаблафикатор (codemod) >27 export default function transformer(file, api) { const
j = api.jscodeshift; return j(file.source) .find(j.Identifier) .replaceWith( j.identifier('bla') ) .toSource(); } Тип узла (с заглавной буквы) -
Блаблафикатор (codemod) >28 export default function transformer(file, api) { const
j = api.jscodeshift; return j(file.source) .find(j.Identifier) .replaceWith( j.identifier('bla') ) .toSource(); } -
export default function transformer(file, api) { const j = api.jscodeshift;
return j(file.source) .find(j.Identifier) .replaceWith( j.identifier('bla') ) .toSource(); } Блаблафикатор (codemod) >29 Builder (со строчной буквы) -
export default function transformer(file, api) { const j = api.jscodeshift;
return j(file.source) .find(j.Identifier) .replaceWith( j.identifier('bla') ) .toSource(); } Блаблафикатор (codemod) >30 Builder (со строчной буквы) -
export default function transformer(file, api) { const j = api.jscodeshift;
return j(file.source) .find(j.Identifier) .replaceWith( j.identifier('bla') ) .toSource(); } Блаблафикатор (bla-transform.js) >31 -
export default function transformer(file, api) { const j = api.jscodeshift;
return j(file.source) .find(j.Identifier) .replaceWith( j.identifier('bla') ) .toSource(); } export const parser = 'flow'; Блаблафикатор (с нестандартным паресером) >32 -
Блаблафикатор (трансформация в cli) >33 $ npm i -g jscodeshift
$ jscodeshift -t bla-transform.js file.js -
Удаление console.log() >37 function sum(a, b) { const result =
a + b; console.log('Hello'); return result; } -
Удаление console.log() (план) >38 Поиск console.log() Проход по коллекции Удаление
.find(..., filter) .forEach(...) .remove() -
{ type: "CallExpression", callee: { type: "MemberExpression", object: { type:
"Identifier", name: "console" }, property: { type: "Identifier", name: "log" } } } Анатомия console.log() - часть 4 >42 -
{ type: "CallExpression", callee: { type: "MemberExpression", object: { type:
"Identifier", name: "console" }, property: { type: "Identifier", name: "log" } } } Анатомия console.log() - часть 4 >43 -
Анатомия console.log() - часть 4 >44 { type: "CallExpression", callee:
{ type: "MemberExpression", object: { type: "Identifier", name: "console" }, property: { type: "Identifier", name: "log" } } } -
.find(j.CallExpression, { type: "CallExpression", callee: { type: "MemberExpression", object: {
type: "Identifier", name: "console" }, property: { type: "Identifier", name: "log" } } }) Поиск console.log() >45 -
.find(j.CallExpression, { type: "CallExpression", callee: { type: "MemberExpression", object: {
type: "Identifier", name: "console" }, property: { type: "Identifier", name: "log" } } }) Поиск console.log() – filter >46 -
.find(j.CallExpression, { callee: { object: { type: "Identifier", name: "console"
}, property: { type: "Identifier", name: "log" } } }) Поиск console.log() – filter >47 -
Поиск console.log() >48 .find(j.CallExpression, { callee: { object: { name:
'console' }, property: { name: 'log' } } }) -
Удаление всех console.log() >49 export default function transformer(file, api) {
const j = api.jscodeshift; return j(file.source) .find(j.CallExpression, { callee: { object: { name: 'console' }, property: { name: 'log' } } }) .forEach(path => { j(path).remove(); }) .toSource(); } -
Удаление всех console.log() >50 return j(file.source) .find(j.CallExpression, { callee: {
object: { name: 'console' }, property: { name: 'log' } } }) .forEach(path => { j(path).remove(); }) .toSource(); -
Удаление всех console.log() >51 return j(file.source) .find(j.CallExpression, { callee: {
object: { name: 'console' }, property: { name: 'log' } } }) .forEach(path => { j(path).remove(); }) .toSource(); -
Удаление всех console.log() >52 return j(file.source) .find(j.CallExpression, { callee: {
object: { name: 'console' }, property: { name: 'log' } } }) .forEach(path => { j(path).remove(); }) .toSource(); -
Удаление всех console.log() >53 return j(file.source) .find(j.CallExpression, { callee: {
object: { name: 'console' }, property: { name: 'log' } } }) .forEach(path => { j(path).remove(); }) .toSource(); -
Удаление всех console.log() >54 return j(file.source) .find(j.CallExpression, { callee: {
object: { name: 'console' }, property: { name: 'log' } } }) .remove() .toSource(); -
Удаление всех console.log() >55 return j(file.source) .find(j.CallExpression, { callee: {
object: { name: 'console' }, property: { name: 'log' } } }) .remove() .toSource(); -
Удаление console.log() – исходный код >56 function sum(a, b) {
const result = a + b; console.log('Hello'); return result; } -
Удаление console.log() – результат >57 function sum(a, b) { const
result = a + b; return result; } -
Замена аргументов функции (план) >60 Поиск increment() Создание нового AST-узла
.find() .replaceWith() Замена arguments buildNode() -
Property - definition >66 def("Property") .bases("Node") .build("kind", "key", "value") .field("kind",
or("init", "get", "set")) .field("key", or(def("Literal"), def("Identifier"))) .field("value", def("Expression")); -
Property - аргументы builder'а >67 def("Property") .bases("Node") .build("kind", "key", "value")
.field("kind", or("init", "get", "set")) .field("key", or(def("Literal"), def("Identifier"))) .field("value", def("Expression")); -
Property - типы аргументов >68 def("Property") .bases("Node") .build("kind", "key", "value")
.field("kind", or("init", "get", "set")) .field("key", or(def("Literal"), def("Identifier"))) .field("value", def("Expression")); -
Замена аргументов функции >70 .find(...) .replaceWith(nodePath => { const {node}
= nodePath; const args = node.arguments; node.arguments = [ j.objectExpression([ buildProperty('value', args[0]) ]) ]; return node; }) -
Замена аргументов функции >71 .find(...) .replaceWith(nodePath => { const {node}
= nodePath; const args = node.arguments; node.arguments = [ j.objectExpression([ buildProperty('value', args[0]) ]) ]; return node; -
Замена аргументов функции >72 function buildProperty(name, value) { return j.property(
'init', j.identifier(name), value, ) } -
Замена аргументов функции >73 .replaceWith(nodePath => { const {node} =
nodePath; const args = node.arguments; node.arguments = [ j.objectExpression([ buildProperty('value', args[0]) ]) ]; return node; }) -
Замена аргументов функции >74 .replaceWith(nodePath => { const {node} =
nodePath; const args = node.arguments; node.arguments = [ j.objectExpression([ buildProperty('value', args[0]) ]) ]; return node; }) -
Замена аргументов функции >75 .replaceWith(nodePath => { const {node} =
nodePath; const args = node.arguments; node.arguments = [ j.objectExpression([ buildProperty('value', args[0]) ]) ]; return node; }) -
Замена аргументов функции (кодмод) >76 function buildProperty(name, value) { return
j.property( 'init', j.identifier(name), value, ) } return root .find(j.CallExpression, { callee: { type: 'Identifier', name: 'increment' } }) .replaceWith(nodePath => { const {node} = nodePath; const args = node.arguments; node.arguments = [ j.objectExpression([ buildProperty('value', args[0]) ]) ]; return node; }) .toSource(); -
Возможный import lodash >80 import _ from lodash; import l
from lodash; import lodash from lodash; -
Замена устаревшего кода (план) >81 Поиск имени идентифик атора .find()
.replaceWith() Замена имени метода .find() Поиск вызовов метода -
Поиск имени идентификатора >82 const importDeclarations = root.find(j.ImportDeclaration, { source:
{ type: 'Literal', value: 'lodash', }, }); const localNameSpace = importDeclarations .find(j.Identifier) .get(0) .node.name; -
Поиск имени идентификатора >83 const importDeclarations = root.find(j.ImportDeclaration, { source:
{ type: 'Literal', value: 'lodash', }, }); const localNameSpace = importDeclarations .find(j.Identifier) .get(0) .node.name; -
Поиск и замена вызова метода >84 .find(j.MemberExpression, { object: {
name: localNameSpace, }, property: { name: 'sortBy', }, }) .replaceWith(nodePath => { const {node} = nodePath; node.property.name = 'orderBy'; return node; }) .toSource() -
Поиск и замена вызова метода >85 .find(j.MemberExpression, { object: {
name: localNameSpace, }, property: { name: 'sortBy', }, }) .replaceWith(nodePath => { const {node} = nodePath; node.property.name = 'orderBy'; return node; }) .toSource() -
Поиск и замена вызова метода >86 .find(j.MemberExpression, { object: {
name: localNameSpace, }, property: { name: 'sortBy', }, }) .replaceWith(nodePath => { const {node} = nodePath; node.property.name = 'orderBy'; return node; }) .toSource() -
Поиск и замена вызова метода >87 .find(j.MemberExpression, { object: {
name: localNameSpace, }, property: { name: 'sortBy', }, }) .replaceWith(nodePath => { const {node} = nodePath; node.property.name = 'orderBy'; return node; }) .toSource() -
Замена устаревшего кода (план Б) >90 Поиск имени идентифик атора
.find() isLodashChain() Проверка чейнинга .find() Поиск вызовов метода .replaceWith() Замена имени метода -
Поиск и замена вызова метода >91 .find(j.MemberExpression, { property: {
name: 'sortBy', }, }) .replaceWith(nodePath => { const {node} = nodePath; if (isLodashChain(node)) { node.property.name = 'orderBy'; return node; } return node; }) .toSource() -
Поиск и замена вызова метода >92 .find(j.MemberExpression, { property: {
name: 'sortBy', }, }) .replaceWith(nodePath => { const {node} = nodePath; if (isLodashChain(node)) { node.property.name = 'orderBy'; return node; } return node; }) .toSource() -
Поиск и замена вызова метода >93 .find(j.MemberExpression, { property: {
name: 'sortBy', }, }) .replaceWith(nodePath => { const {node} = nodePath; if (isLodashChain(node)) { node.property.name = 'orderBy'; return node; } return node; }) .toSource() -
Проверка чейнинга >94 function isLodashChain(node) { while ( node.type !==
'Identifier' && node.object.type === 'CallExpression' ) { node = node.object.callee; } let name = node.name || node.object.name; return name === localNameSpace; } -
Поиск и замена вызова метода >95 .find(j.MemberExpression, { property: {
name: 'sortBy', }, }) .replaceWith(nodePath => { const {node} = nodePath; if (isLodashChain(node)) { node.property.name = 'orderBy'; return node; } return node; }) .toSource() -
Замена устаревшего кода >96 export default (fileInfo, api) => {
const j = api.jscodeshift; const root = j(fileInfo.source); const importDeclarations = root.find(j.ImportDeclaration, { source: { type: 'Literal', value: 'lodash', }, }); const oldMethodName = 'sortBy'; const newMethodName = 'orderBy'; if (importDeclarations.size() === 0) { return null; }; const localNameSpace = importDeclarations .find(j.Identifier) .get(0) .node.name; function isLodashChain(node) { while ( node.type !== 'Identifier' && node.object.type === 'CallExpression' ) { node = node.object.callee; } let name = node.name || node.object.name; return name === localNameSpace; } return root .find(j.MemberExpression, { property: { name: oldMethodName, }, }) .replaceWith(nodePath => { const {node} = nodePath; if (isLodashChain(node)) { node.property.name = newMethodName; } return node; }) .toSource(); }; 50 строк -
Известные проблемы >98 › Существует ненулевой порог входа › С
написанием кодмодов могут быть неочевидные проблемы › Сталкивался со странным форматированием -
Плюсы >99 › Простой переход на новые версии библиотек ›
Упрощение поддержки кода в здоровом состоянии › Упрощение рефакторинга большой кодовой базы › Кодмод - это обычный скрипт › Автоматизация -
Полезные ссылки >100 › https://github.com/facebook/jscodeshift - jscodeshift › https://github.com/benjamn/ast-types/blob/master/def -
определения AST-узлов › https://www.toptal.com/javascript/write-code-to-rewrite-your-code - статья с хорошими примерами › https://astexplorer.net - инспектор ast › https://github.com/sejoker/awesome-jscodeshift - полезная подборка › https://www.youtube.com/watch?v=d0pOgY8__JM - видео от создателя › https://2018.codefest.ru/lecture/1302/ - доклад про AST › https://github.com/reactjs/react-codemod - кодмоды для React