/
refactor-to-es-module.ts
176 lines (140 loc) · 7.18 KB
/
refactor-to-es-module.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import { parse, print, types } from 'recast';
import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
import { IdentifierKind, MemberExpressionKind, ExpressionKind, CommentKind } from 'ast-types/gen/kinds';
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const FRONT_END_FOLDER = path.join(__dirname, '..', '..', 'front_end')
function capitalizeFirstLetter(string: string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
const b = types.builders;
function createReplacementDeclaration(propertyName: IdentifierKind, declaration: any): any {
// UI.ARIAUtils.Foo = class {} -> export class Foo {}
if (declaration.type === 'ClassExpression') {
return b.exportDeclaration(false, b.classDeclaration(propertyName, declaration.body));
}
// UI.ARIAUtils.Foo = expression; -> export const Foo = expression;
if (declaration.type === 'Literal' || declaration.type.endsWith('Expression')) {
return b.exportNamedDeclaration(b.variableDeclaration("const", [b.variableDeclarator(propertyName, declaration)]));
}
console.error(`Unable to refactor declaration of type "${declaration.type}" named "${propertyName.name}"`);
}
function getTopLevelMemberExpression(expression: MemberExpressionKind): any {
while (expression.object.type === 'MemberExpression') {
expression = expression.object;
}
return expression;
}
function rewriteSource(source: string, refactoringNamespace: string, refactoringFileName: string) {
const exportedMembers: {prop: IdentifierKind, comments: CommentKind[]}[] = [];
const ast = parse(source);
ast.program.body = ast.program.body.map((expression: any) => {
// UI.ARIAUtils.Foo = 5;
if (expression.type === 'ExpressionStatement') {
// UI.ARIAUtils.Foo = 5
if (expression.expression.type === 'AssignmentExpression') {
const assignment = expression.expression;
// UI.ARIAUtils.Foo
if (assignment.left.type === 'MemberExpression') {
// UI.ARIAUtils.Foo -> UI.ARIAUtils
// UI.ARIAUtils.Nested.Foo -> UI.ARIAUtils
const topLevelAssignment = getTopLevelMemberExpression(assignment.left);
// If there is a nested export, such as `UI.ARIAUtils.Nested.Field`
if (topLevelAssignment !== assignment.left.object) {
// Exports itself. E.g. `UI.ARIAUtils = <...>`
if (assignment.left.object.name === refactoringNamespace && assignment.left.property.name === refactoringFileName) {
const {declaration} = createReplacementDeclaration(assignment.left.property, assignment.right);
// If it is a variable declaration, we need to use the actual variabledeclator. E.g.:
// UI.ARIAUtils = 5; -> export ARIAUtils = 5; instead of "export const ARIAUtils = 5;"
const declarationStatement = b.exportDefaultDeclaration(declaration.type === 'VariableDeclaration' ? declaration.declarations[0].init : declaration);
declarationStatement.comments = expression.comments;
return declarationStatement;
}
console.error(`Nested field "${assignment.left.property.name}" detected! Requires manual changes.`);
expression.comments = expression.comments || [];
expression.comments.push(b.commentLine(' TODO(http://crbug.com/1006759): Fix exported symbol'));
return expression;
}
const propertyName = assignment.left.property;
const {object, property} = topLevelAssignment;
if (object.type === 'Identifier' && property.type === 'Identifier') {
// UI
const namespace = object.name;
// ARIAUtils
const fileName = property.name;
if (namespace === refactoringNamespace && fileName === refactoringFileName) {
const declaration = createReplacementDeclaration(propertyName, assignment.right);
if (declaration) {
exportedMembers.push({prop: propertyName, comments: expression.comments || [b.commentLine(' TODO(http://crbug.com/1006759): Add type information if necessary')]});
declaration.comments = expression.comments;
return declaration;
}
}
}
}
}
}
return expression;
});
// self.UI = self.UI || {};
{
const legacyNamespaceName = b.memberExpression(b.identifier('self'), b.identifier(refactoringNamespace), false);
const legacyNamespaceOr = b.logicalExpression("||", legacyNamespaceName, b.objectExpression([]));
ast.program.body.push(b.expressionStatement.from({
expression: b.assignmentExpression('=', legacyNamespaceName, legacyNamespaceOr),
comments: [b.commentBlock(' Legacy exported object ', true, false)]
}));
}
// UI = UI || {};
const legacyNamespaceName = b.identifier(refactoringNamespace)
{
const legacyNamespaceOr = b.logicalExpression("||", legacyNamespaceName, b.objectExpression([]));
ast.program.body.push(b.expressionStatement.from({
expression: b.assignmentExpression('=', legacyNamespaceName, legacyNamespaceOr),
comments: [b.commentBlock(' Legacy exported object ', true, false)]
}));
}
// UI.ARIAUtils = ARIAUtils;
const legacyNamespaceExport = b.memberExpression(b.identifier(refactoringNamespace), b.identifier(refactoringFileName), false);
ast.program.body.push(b.expressionStatement(b.assignmentExpression.from({
operator: '=',
left: legacyNamespaceExport,
right: b.identifier(refactoringFileName),
comments: [b.commentLine(' TODO(http://crbug.com/1006759): Add type information if necessary')]
})));
// UI.ARIAUtils.Foo = Foo;
exportedMembers.forEach(({prop, comments}) => {
const legacyExportedProperty = b.memberExpression(legacyNamespaceExport, b.identifier(prop.name), false);
ast.program.body.push(b.expressionStatement(b.assignmentExpression.from({
operator: '=',
left: legacyExportedProperty,
right: b.identifier(prop.name),
comments,
})));
});
return print(ast).code;
}
const FOLDER_MAPPING: {[name: string]: string} = require(path.join('..', 'build', 'special_case_namespaces.json'));
function computeNamespaceName(folderName: string): string {
if (folderName in FOLDER_MAPPING) {
return FOLDER_MAPPING[folderName];
}
return capitalizeFirstLetter(folderName);
}
async function main(refactoringNamespace: string, refactoringFileName: string) {
const pathName = path.join(FRONT_END_FOLDER, refactoringNamespace, `${refactoringFileName}.js`);
const source = await readFile(pathName, {encoding: 'utf-8'});
const rewrittenSource = rewriteSource(source, computeNamespaceName(process.argv[2]), refactoringFileName);
await writeFile(pathName, rewrittenSource);
// console.log(`Succesfully written source to "${pathName}". Make sure that no other errors are reported before submitting!`);
}
if (!process.argv[2]) {
console.error(`No arguments specified. Run this script with "<folder-name> <filename>". For example: "common Color"`);
process.exit(1);
}
main(process.argv[2], process.argv[3]);