-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathextension.js
More file actions
75 lines (65 loc) · 2.03 KB
/
extension.js
File metadata and controls
75 lines (65 loc) · 2.03 KB
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
const vscode = require("vscode");
const fs = require("fs");
const path = require("path");
function getPythonPath(filePath) {
const splittedPath = filePath.split(path.sep);
if (
splittedPath.length === 0 ||
!splittedPath[splittedPath.length - 1].endsWith(".py")
) {
return "";
}
const fileName = splittedPath.pop();
// removing extension
let pythonPath =
fileName !== "__init__.py"
? [fileName.substring(0, fileName.lastIndexOf("."))]
: [];
while (
splittedPath.length > 0 &&
fs.existsSync([...splittedPath, ["__init__.py"]].join(path.sep))
) {
pythonPath.unshift(splittedPath.pop());
}
return pythonPath.join(".");
}
function copyPythonPath(uri) {
try {
const filePath = uri
? uri.fsPath
: vscode.window.activeTextEditor.document.fileName;
const pythonPath = getPythonPath(filePath);
const selections = vscode.window.activeTextEditor.selections
.map(s => vscode.window.activeTextEditor.document.getText(s))
.filter(s => !!s && !s.includes("\n") && !s.trim().includes(" "));
if (pythonPath && selections.length > 0) {
const importStatement = generateImportStatement(pythonPath, selections);
vscode.env.clipboard.writeText(importStatement);
}
if (pythonPath && selections.length == 0) {
vscode.env.clipboard.writeText(pythonPath);
}
} catch (e) {
console.log(e);
}
}
function generateImportStatement(pythonPath, selections) {
if (selections.length == 0) {
return `import ${pythonPath}`;
} else if (selections.length == 1) {
const selection = selections[0].trim();
return `from ${pythonPath} import ${selection}`;
}
const selection = selections.map(s => `\t${s.trim()},`).join("\n");
return `from ${pythonPath} import (\n${selection}\n)`;
}
function activate(context) {
let disposable = vscode.commands.registerCommand(
"extension.copyPythonPath",
copyPythonPath
);
context.subscriptions.push(disposable);
}
exports.activate = activate;
function deactivate() {}
exports.deactivate = deactivate;