-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.js
76 lines (72 loc) · 1.91 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
const vscode = require("vscode");
function parseArgs(argStr) {
const bracketPairs = { "(": ")", "[": "]", "{": "}" };
const quotes = new Set(['"', "'"]);
let args = [];
let bracketStack = [];
let buffer = "";
let quoteStack = [];
for (const char of argStr) {
if (quotes.has(char)) {
if (char !== quoteStack[quoteStack.length - 1]) {
quoteStack.push(char);
} else {
quoteStack.pop();
}
}
if (!quoteStack.length) {
if (bracketPairs[char]) {
bracketStack.push(char);
} else if (char === bracketPairs[bracketStack[bracketStack.length - 1]]) {
bracketStack.pop();
}
}
if (!quoteStack.length && !bracketStack.length && char === ",") {
if ((buffer = buffer.trim())) {
args.push(buffer);
buffer = "";
}
} else {
buffer += char;
}
}
if ((buffer = buffer.trim())) {
args.push(buffer);
}
return args;
}
function activate(context) {
context.subscriptions.push(
vscode.commands.registerCommand("kwarg-sort.sortKwargs", () => {
const editor = vscode.window.activeTextEditor;
const selection = editor.selection;
const code = editor.document.getText(selection);
const argStr = (code.match(/\w+\s*\((.*)\)/s) || [])[1];
if (!argStr) {
return;
}
const args = parseArgs(argStr);
let keywordArgs = [];
let positionalArgs = [];
for (const arg of args) {
if (arg.includes("=")) {
keywordArgs.push(arg);
} else {
positionalArgs.push(arg);
}
}
keywordArgs.sort();
editor.edit((editBuilder) =>
editBuilder.replace(
selection,
code.replace(
/(\w+)\s*\(.*\)/s,
`$1(${[...positionalArgs, ...keywordArgs].join(", ")})`
)
)
);
})
);
}
function deactivate() {}
module.exports = { activate, deactivate };