-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.js
224 lines (199 loc) · 7.13 KB
/
extension.js
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
const vscode = require('vscode');
const path = require('path');
const fs = require("fs");
const parse = require('@babel/parser').parse;
const generate = require('@babel/generator').default;
const template = require('@babel/template').default;
const traverse = require('@babel/traverse').default;
const t = require('@babel/types');
const fileName = 'workbench.desktop.main.js';
const backUpFileName = 'workbench.desktop.main.origin.js';
const patchFileName = 'workbench.desktop.main.patch.js';
let BASE_PATH = '';
let step = 0;
function getVSCodePath() {
const app = require.main
? path.dirname(require.main.filename)
: globalThis._VSCODE_FILE_ROOT;
if (!app) {
vscode.window.showInformationMessage("Unable to locate the installation path of VSCode. This extension won't work.");
return false;
}
BASE_PATH = path.join(app, "vs", "workbench");
}
// backup
async function backup() {
const unWritable = await fs.promises.access(path.resolve(BASE_PATH, fileName), fs.constants.W_OK).catch(() => true);
if (unWritable) {
vscode.window.showErrorMessage('VS Code can not modify itself.');
return false;
}
const notBackup = await fs.promises.access(path.resolve(BASE_PATH, backUpFileName), fs.constants.F_OK).catch(e => {
console.log('backup file not exist', e);
return true;
});
if (notBackup) {
await fs.promises.copyFile(path.resolve(BASE_PATH, fileName), path.resolve(BASE_PATH, backUpFileName));
}
return true;
}
// restore
async function restore() {
const unWritable = await fs.promises.access(path.resolve(BASE_PATH, fileName), fs.constants.W_OK).catch(() => true);
if (unWritable) {
vscode.window.showErrorMessage('VS Code can not modify itself.');
return false;
}
const notBackup = await fs.promises.access(path.resolve(BASE_PATH, backUpFileName), fs.constants.F_OK).catch(e => {
console.log('backup file not exist', e);
return true;
});
if (notBackup) {
vscode.window.showErrorMessage('There is not a backup file.');
return;
}
await fs.promises.copyFile(path.resolve(BASE_PATH, backUpFileName), path.resolve(BASE_PATH, fileName));
vscode.window.showInformationMessage('restored.');
}
async function patch() {
vscode.window.showInformationMessage('git submodule sort patch starts. It will take some time.')
step = 0;
const status = await backup();
if (!status) {
return;
}
const config = vscode.workspace.getConfiguration("git-submodule-sort");
const data = await fs.promises.readFile(path.resolve(BASE_PATH, backUpFileName), 'utf8')
const ast = parse(data, {
sourceType: 'module',
plugins: [
"classStaticBlock",
],
});
const sortRepositoriesBody = template.ast(`function _sort(repos, prefix) {
repos.sort((a, b) => b.uri.length - a.uri.length);
for (let i = repos.length; i--;) {
const repo = repos[i];
const rootUri = repo.uri + '/';
for (let j = i; j--;) {
if (repos[j].uri.includes(rootUri)) {
repos[j].prefix = prefix;
repo.children = repos.splice(j, 1).concat(repo.children);
--i;
}
}
repo.children = _sort(repo.children, ' ' + prefix);
}
repos.sort((a, b) => a.index - b.index);
return repos.reduce((acc, repo) => { acc.push(repo, ...repo.children); return acc; }, []);
}
let sortIndexs = visibleRepositories.map((repo, index) => ({
index,
uri: repo.repository.provider.rootUri.path,
children: []
}));
let sortedIndex = _sort(sortIndexs, '${config.prefix || '┡'} ');
const sorted = sortedIndex.map(({ index, prefix }) => {
visibleRepositories[index].repository.provider.prefix = prefix || '';
return visibleRepositories[index];
});
return sorted;`);
transformer(ast, sortRepositoriesBody);
if (step !== 4) {
vscode.window.showErrorMessage('git submodule sort patch failed!!');
return;
}
const { code } = generate(ast, {
compact: true,
concise: true,
});
output(code);
}
async function output(data) {
await fs.promises.writeFile(path.join(BASE_PATH, fileName), data).catch((e) => {
console.error(e)
vscode.window.showWarningMessage('git submodule sort patch failed!');
})
vscode.window.showInformationMessage('git submodule sort patch successed! Restart to take effect.', { title: 'Restart VS Code' })
.then(() => {
vscode.commands.executeCommand("workbench.action.reloadWindow")
});
}
function transformer(ast, sortRepositoriesBody) {
traverse(ast, {
ClassMethod: function (path) {
if (path.node.key.name === 'renderElement') {
if (path.toString().includes('.provider.rootUri')) {
path.traverse({
ExpressionStatement: function (path) {
path.traverse({
AssignmentExpression: function (path) {
// r.name.textContent = f.basename(a.provider.rootUri)
// 1.59.0 a.name.textContent=(0,f.basename)(o.provider.rootUri)
// 1.85.0 o.name.textContent=d.provider.name => o.name.textContent=d.provider.prefix + d.provider.name
if (path.node.right.type === 'MemberExpression' && path.node.right.property.name === 'name') {
path.node.right = t.binaryExpression(
'+',
t.memberExpression(
path.node.right.object,
t.identifier('prefix')
),
path.node.right
);
path.skip();
step++;
}
}
});
}
});
}
}
if (path.node.kind === 'get' && path.node.key.name === 'visibleRepositories') {
const propertyName = path.node.body.body[0].argument.consequent.callee.object.callee.object.callee.object.property.name
const getRepositoriesBody = template.ast(`return this.sortRepositories(this.${propertyName})
.filter(r => r.selectionIndex !== -1)
.map(r => r.repository);`);
path.node.body = t.blockStatement([getRepositoriesBody])
step++;
path.parentPath.traverse({
ClassMethod: function (path) {
if (path.node.kind === 'get' && path.node.key.name === 'repositories') {
const propertyName = path.node.body.body[0].argument.callee.object.property.name;
const getRepositoriesBody = template.ast(`return this.sortRepositories(this.${propertyName}).map(o => o.repository);`);
path.node.body = t.blockStatement([getRepositoriesBody])
step++;
}
if (path.node.key.name === 'toggleVisibility') {
if (path.toString().includes('this.visibleRepositories')) {
const sortRepositories = t.classMethod('method', t.identifier('sortRepositories'), [t.identifier('visibleRepositories')], t.blockStatement(sortRepositoriesBody))
path.insertAfter(sortRepositories);
step++;
}
}
}
});
}
},
});
}
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
if (getVSCodePath() === false) {
return;
}
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const patchInstall = vscode.commands.registerCommand('git-submodule-sort.patch', patch);
context.subscriptions.push(patchInstall);
const restorePatchInstall = vscode.commands.registerCommand('git-submodule-sort.restore', restore);
context.subscriptions.push(restorePatchInstall);
}
function deactivate() { }
module.exports = {
activate,
deactivate
}