|
| 1 | +import path from "path"; |
| 2 | +import * as vscode from "vscode"; |
| 3 | +import Utils from "./utils"; |
| 4 | + |
| 5 | +export default class GoMoveToNewFileActionProvider |
| 6 | + implements vscode.CodeActionProvider |
| 7 | +{ |
| 8 | + provideCodeActions( |
| 9 | + document: vscode.TextDocument, |
| 10 | + range: vscode.Range |
| 11 | + ): vscode.CodeAction[] { |
| 12 | + const lineText = document.lineAt(range.start.line).text; |
| 13 | + const typeOrMethodRegex = /^(type|func)\s+(\w+)/; |
| 14 | + const match = lineText.match(typeOrMethodRegex); |
| 15 | + |
| 16 | + if (match) { |
| 17 | + const action = new vscode.CodeAction( |
| 18 | + "Move to new file", |
| 19 | + vscode.CodeActionKind.RefactorMove |
| 20 | + ); |
| 21 | + action.command = { |
| 22 | + title: "Move to new file", |
| 23 | + command: "gohelp.moveToNewFile", |
| 24 | + arguments: [document, range, match[2]], |
| 25 | + }; |
| 26 | + return [action]; |
| 27 | + } |
| 28 | + |
| 29 | + return []; |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +vscode.commands.registerCommand( |
| 34 | + "gohelp.moveToNewFile", |
| 35 | + async (document: vscode.TextDocument, range: vscode.Range, name: string) => { |
| 36 | + const originalDir = path.dirname(document.uri.fsPath); |
| 37 | + const originalPackageName = await Utils.getPackageName(document); |
| 38 | + const newFilePath = await Utils.promptForNewFilePath(document, name); |
| 39 | + const newFileDir = newFilePath ? path.dirname(newFilePath) : ""; |
| 40 | + |
| 41 | + if (newFilePath) { |
| 42 | + let newPackageName = |
| 43 | + originalDir === newFileDir |
| 44 | + ? originalPackageName |
| 45 | + : path.basename(path.dirname(newFilePath)); |
| 46 | + const content = await Utils.extractContent( |
| 47 | + document, |
| 48 | + range.start.line, |
| 49 | + name |
| 50 | + ); |
| 51 | + if (!content) { |
| 52 | + vscode.window.showErrorMessage( |
| 53 | + "Failed to extract content. Please try again." |
| 54 | + ); |
| 55 | + return; |
| 56 | + } |
| 57 | + const updatedContent = Utils.updatePackageAndImports( |
| 58 | + content, |
| 59 | + originalPackageName, |
| 60 | + newPackageName |
| 61 | + ); |
| 62 | + await Utils.createNewFileWithContent( |
| 63 | + newFilePath, |
| 64 | + newPackageName, |
| 65 | + updatedContent |
| 66 | + ); |
| 67 | + await Utils.removeContentFromOriginalFile(document, content); |
| 68 | + await Utils.updateImportsInOriginalFile(document, name, newPackageName); |
| 69 | + await vscode.workspace |
| 70 | + .openTextDocument(newFilePath) |
| 71 | + .then((doc) => vscode.window.showTextDocument(doc)); |
| 72 | + } |
| 73 | + } |
| 74 | +); |
0 commit comments