forked from stackwiseai/stackwise
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
83 lines (71 loc) · 2.4 KB
/
index.ts
File metadata and controls
83 lines (71 loc) · 2.4 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
81
82
83
import * as vscode from 'vscode';
import path from 'path';
export default function addImportStatement(
methodName: string,
document: vscode.TextDocument,
integration: string
) {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders) {
vscode.window.showErrorMessage('No workspace is open.');
return;
}
// Calculate the relative path for the import
const relativePath = calculateRelativePath(
document.uri,
workspaceFolders[0].uri
);
// Determine the import path based on integration
const importPath =
integration === 'generic'
? `${relativePath}stacks/${methodName}`
: `${relativePath}stacks/${integration}/${methodName}`;
const importStatement = `import ${methodName} from '${importPath}';\n`;
// Insert the import statement at the top of the document
const edit = new vscode.WorkspaceEdit();
edit.insert(document.uri, new vscode.Position(0, 0), importStatement);
vscode.workspace.applyEdit(edit).then(() => {
saveDocument(document);
});
}
function calculateRelativePath(
documentUri: vscode.Uri,
workspaceUri: vscode.Uri
): string {
// Normalize paths to handle different file systems
let documentPath = path.normalize(documentUri.fsPath).split(path.sep);
let workspacePath = path.normalize(workspaceUri.fsPath).split(path.sep);
// Special handling for Windows drive letters
if (process.platform === 'win32') {
documentPath[0] = documentPath[0].toLowerCase();
workspacePath[0] = workspacePath[0].toLowerCase();
}
// Remove common path segments
while (
documentPath.length > 0 &&
workspacePath.length > 0 &&
documentPath[0].toLowerCase() === workspacePath[0].toLowerCase()
) {
documentPath.shift();
workspacePath.shift();
}
// Replace each remaining segment in the document path with '../'
let relativePath = '../'.repeat(documentPath.length - 1); // -1 because we don't need to count the file itself
// Handle edge case when relative path is empty, it means document is in the workspace root
if (!relativePath) {
relativePath = './';
}
return relativePath;
}
function saveDocument(document: vscode.TextDocument) {
if (document.isDirty) {
document.save().then(
() => {
vscode.window.showInformationMessage('Stack created successfully 🎉');
},
(err) => {
vscode.window.showErrorMessage(`Error saving document: ${err}`);
}
);
}
}