forked from mgesbert/vscode-python-path
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
80 lines (70 loc) · 2.05 KB
/
extension.js
File metadata and controls
80 lines (70 loc) · 2.05 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
76
77
78
79
80
const vscode = require("vscode");
const fs = require("fs");
const clipboardy = require("clipboardy");
function getPythonPath(path) {
const splittedPath = path.split("/");
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("/"))
) {
pythonPath.unshift(splittedPath.pop());
}
return pythonPath.join(".");
}
function copyPythonPath(uri) {
try {
const path = uri
? uri.fsPath
: vscode.window.activeTextEditor.document.fileName;
const pythonPath = getPythonPath(path);
const selections = vscode.window.activeTextEditor.selections
.map(s => vscode.window.activeTextEditor.document.getText(s))
.filter(s => !!s);
if (pythonPath && selections.length > 0) {
const importStatement = generateImportStatement(pythonPath, selections);
clipboardy.writeSync(importStatement);
}
if (pythonPath && selections.length == 0) {
clipboardy.writeSync(pythonPath);
}
} catch (e) {
console.log(e);
}
}
function generateImportStatement(pythonPath, selections) {
let importPath;
if (selections.length == 0) {
importPath = `import ${pythonPath}`;
} else if (selections.length == 1) {
const selection = selections[0];
importPath = `from ${pythonPath} import ${selection}`;
} else {
const selection = selections.map(s => `\t${s},`).join("\n");
importPath = `from ${pythonPath} import (\n${selection}\n)`;
}
if (importPath) {
clipboardy.writeSync(importPath);
}
}
function activate(context) {
let disposable = vscode.commands.registerCommand(
"extension.copyPythonPath",
copyPythonPath
);
context.subscriptions.push(disposable);
}
exports.activate = activate;
function deactivate() {}
exports.deactivate = deactivate;