VSCode 插件开发实战(十二):如何集成Git操作能力

前言

VSCode 不仅提供了丰富的编辑功能,还支持通过扩展插件来提升工作效率。本文将通过构建一个自定义 VSCode 插件,带你深入了解如何在编辑器中简化和自动化 Git 操作。这不仅能提升开发效率,还能减少人为操作失误,从而更加专注于代码本身。

基础集成步骤

打开生成的项目,你会看到一个 src/extension.ts 文件,这就是插件的入口文件。

1. 添加 Git 操作功能

我们需要使用 simple-git 库来简化 Git 操作。在项目根目录下运行以下命令安装 simple-git:

clike 复制代码
npm install simple-git

接下来,修改 src/extension.ts 文件,引入 simple-git 并添加一些命令:

clike 复制代码
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 部分,添加新的命令:

clike 复制代码
"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 操作,如创建分支、合并分支和查看状态等。此外,还可以增强用户体验,例如在状态栏显示当前分支信息。

创建新分支

clike 复制代码
在 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 文件中添加对应的命令描述:

clike 复制代码
{
    "command": "extension.createBranch",
    "title": "Git: Create Branch"
}

合并分支

类似地,我们可以添加一个合并分支的命令:

clike 复制代码
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 文件:

clike 复制代码
{
    "command": "extension.mergeBranch",
    "title": "Git: Merge Branch"
}

查看 Git 状态

为了检查当前的 Git 状态,比如已修改的文件和当前分支,可以添加以下命令:

clike 复制代码
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 中注册命令:

clike 复制代码
{
    "command": "extension.gitStatus",
    "title": "Git: Status"
}

显示当前分支信息

在状态栏显示当前分支信息,可以给用户提供即时反馈。我们可以在插件激活时设置状态栏项,并在每次状态更新时刷新它:

clike 复制代码
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 操作。从最基础的提交、推送和拉取功能,到创建分支、合并分支和实时显示当前分支信息,我们一步步构建了一个功能全面的插件。

相关推荐
Joy T3 小时前
voice-dump-to-todo:把混乱的语音整理成可执行待办,一个实用的 Agent Skill
ide·macos·语音识别·xcode·任务管理·自研skill
人工智能导论实践课7 小时前
【GUI桌面开发3】PyCharm配置外部工具
ide·python·pycharm
LannyChung7 小时前
PowerShell 下 git log 中文乱码的完整排查与解决
windows·git
import_random8 小时前
[git]本地main,origin/main,远程main(关系2)
git
golang学习记8 小时前
Zed Git重大更新:目录级对比支持分栏Diff
git·vscode·zed
JPower_mr.g10 小时前
SmartCall v1.0.9 发布:智能体知识库上线,让 AI 客服先查资料再回答
java·ide·人工智能·macos·架构·开源·xcode
Dev _12 小时前
PyCharm旧进程仍在后台运行,导致新实例无法启动或连接
ide·python·pycharm
阿俊-全栈开发13 小时前
LikeShop 单商户高级版二开项目的 Git 分支管理与版本发布规范
git·likeshop·likeshop开源商城·likeshop多商户
努力弹琴的大风天13 小时前
TortoiseGit 仓库不显示绿色对号解决方案
git·tortoisegit·图标显示
无巧不成书021815 小时前
Tomcat部署JSP文件完整指南:手动部署+IDEA工程化实现 附404访问错误全排查
java·ide·windows·tomcat·intellij-idea·js