前言
VSCode 不仅提供了丰富的编辑功能,还支持通过扩展插件来提升工作效率。本文将通过构建一个自定义 VSCode 插件,带你深入了解如何在编辑器中简化和自动化 Git 操作。这不仅能提升开发效率,还能减少人为操作失误,从而更加专注于代码本身。
基础集成步骤
打开生成的项目,你会看到一个 src/extension.ts 文件,这就是插件的入口文件。
1. 添加 Git 操作功能
我们需要使用 simple-git 库来简化 Git 操作。在项目根目录下运行以下命令安装 simple-git:
npm install simple-git
接下来,修改 src/extension.ts 文件,引入 simple-git 并添加一些命令:
import * as vscode from 'vscode';
import * as simpleGit from 'simple-git';
export function activate(context: vscode.ExtensionContext) {
const git = simpleGit();
let disposableCommit = vscode.commands.registerCommand('extension.commit', async () => {
const message = await vscode.window.showInputBox({ prompt: 'Commit message' });
if (message) {
git.commit(message)
.then(() => vscode.window.showInformationMessage(`Committed: ${message}`))
.catch((err: any) => vscode.window.showErrorMessage(`Commit failed: ${err.message}`));
}
});
let disposablePush = vscode.commands.registerCommand('extension.push', () => {
git.push()
.then(() => vscode.window.showInformationMessage('Pushed to remote repository'))
.catch((err: any) => vscode.window.showErrorMessage(`Push failed: ${err.message}`));
});
let disposablePull = vscode.commands.registerCommand('extension.pull', () => {
git.pull()
.then(() => vscode.window.showInformationMessage('Pulled from remote repository'))
.catch((err: any) => vscode.window.showErrorMessage(`Pull failed: ${err.message}`));
});
context.subscriptions.push(disposableCommit, disposablePush, disposablePull);
}
export function deactivate() {}
2. 配置命令
打开 package.json 文件,找到 contributes 部分,添加新的命令:
"contributes": {
"commands": [
{
"command": "extension.commit",
"title": "Git: Commit"
},
{
"command": "extension.push",
"title": "Git: Push"
},
{
"command": "extension.pull",
"title": "Git: Pull"
}
]
}
3. 运行和调试插件
在 VSCode 中按 F5 启动调试,会打开一个新的 VSCode 窗口,其中已经加载了你的插件。在命令面板中(按 Ctrl+Shift+P 调出),尝试搜索你定义的命令(如 Git: Commit),并测试其功能。
功能扩展
我们可以进一步扩展插件,添加更多的 Git 操作,如创建分支、合并分支和查看状态等。此外,还可以增强用户体验,例如在状态栏显示当前分支信息。
创建新分支
在 src/extension.ts 中添加一个新命令,用于创建分支:
let disposableBranch = vscode.commands.registerCommand('extension.createBranch', async () => {
const branchName = await vscode.window.showInputBox({ prompt: 'New branch name' });
if (branchName) {
git.checkoutLocalBranch(branchName)
.then(() => vscode.window.showInformationMessage(`Branch created: ${branchName}`))
.catch((err: any) => vscode.window.showErrorMessage(`Create branch failed: ${err.message}`));
}
});
context.subscriptions.push(disposableBranch);
然后在 package.json 文件中添加对应的命令描述:
{
"command": "extension.createBranch",
"title": "Git: Create Branch"
}
合并分支
类似地,我们可以添加一个合并分支的命令:
let disposableMerge = vscode.commands.registerCommand('extension.mergeBranch', async () => {
const branchName = await vscode.window.showInputBox({ prompt: 'Branch name to merge into current branch' });
if (branchName) {
git.merge([branchName])
.then(() => vscode.window.showInformationMessage(`Merged branch: ${branchName}`))
.catch((err: any) => vscode.window.showErrorMessage(`Merge failed: ${err.message}`));
}
});
context.subscriptions.push(disposableMerge);
并更新 package.json 文件:
{
"command": "extension.mergeBranch",
"title": "Git: Merge Branch"
}
查看 Git 状态
为了检查当前的 Git 状态,比如已修改的文件和当前分支,可以添加以下命令:
let disposableStatus = vscode.commands.registerCommand('extension.gitStatus', () => {
git.status()
.then((status: any) => {
const message = `
On branch: ${status.current}
Changes to be committed: ${status.staged.length} file(s)
Changes not staged for commit: ${status.not_staged.length} file(s)
Untracked files: ${status.not_added.length} file(s)
`;
vscode.window.showInformationMessage(message);
})
.catch((err: any) => vscode.window.showErrorMessage(`Git status failed: ${err.message}`));
});
context.subscriptions.push(disposableStatus);
并在 package.json 中注册命令:
{
"command": "extension.gitStatus",
"title": "Git: Status"
}
显示当前分支信息
在状态栏显示当前分支信息,可以给用户提供即时反馈。我们可以在插件激活时设置状态栏项,并在每次状态更新时刷新它:
function updateBranchStatusBarItem(statusBarItem: vscode.StatusBarItem) {
git.status()
.then((status: any) => {
statusBarItem.text = `$(git-branch) ${status.current}`;
statusBarItem.show();
})
.catch((err: any) => {
statusBarItem.text = '$(git-branch) Unknown';
statusBarItem.show();
});
}
export function activate(context: vscode.ExtensionContext) {
const git = simpleGit();
const branchStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 100);
updateBranchStatusBarItem(branchStatusBarItem);
context.subscriptions.push(branchStatusBarItem);
let disposableCommit = vscode.commands.registerCommand('extension.commit', async () => {
const message = await vscode.window.showInputBox({ prompt: 'Commit message' });
if (message) {
git.commit(message)
.then(() => {
vscode.window.showInformationMessage(`Committed: ${message}`);
updateBranchStatusBarItem(branchStatusBarItem);
})
.catch((err: any) => vscode.window.showErrorMessage(`Commit failed: ${err.message}`));
}
});
let disposablePush = vscode.commands.registerCommand('extension.push', () => {
git.push()
.then(() => {
vscode.window.showInformationMessage('Pushed to remote repository');
updateBranchStatusBarItem(branchStatusBarItem);
})
.catch((err: any) => vscode.window.showErrorMessage(`Push failed: ${err.message}`));
});
let disposablePull = vscode.commands.registerCommand('extension.pull', () => {
git.pull()
.then(() => {
vscode.window.showInformationMessage('Pulled from remote repository');
updateBranchStatusBarItem(branchStatusBarItem);
})
.catch((err: any) => vscode.window.showErrorMessage(`Pull failed: ${err.message}`));
});
context.subscriptions.push(disposableCommit, disposablePush, disposablePull);
}
总结
通过本文的详细教程,你已经掌握了如何创建一个自定义的 VSCode 插件,用于简化和增强 Git 操作。从最基础的提交、推送和拉取功能,到创建分支、合并分支和实时显示当前分支信息,我们一步步构建了一个功能全面的插件。