计划开发一个用于快速提交 MR 的插件,最好只需要用鼠标点击一两下即可完成全部操作。
generator-code
首先安装 Yeoman 和 VS Code Extension Generator,运行 yo code 填写一些必要的字段即可生成一个插件项目。
npm install -g yo generator-code
yo code# ? What type of extension do you want to create? New Extension (TypeScript)# ? What's the name of your extension? GitlabMrt### Press <Enter> to choose default for all options below #### ? What's the identifier of your extension? gitlabmrt# ? What's the description of your extension? LEAVE BLANK# ? Initialize a git repository? Yes# ? Bundle the source code with webpack? No# ? Which package manager to use? npmcode ./helloworld
配置
首先需要再 ActiveBar 显示一个图标,在 package.json 文件中做如下配置:
{"activationEvents": ["onView:gitlab.mrt"],"contributes": {"views": {"gitlab-mrt": [{"id": "gitlabMrt","name": "Gitlab Mrt","icon": "src/assets/gitlab.svg","contextualTitle": "Gitlab Mrt"}]},"viewsContainers": {"activitybar": [{"id": "gitlab-mrt","title": "Gitlab Mrt","icon": "src/assets/gitlab.svg"}]}},}
使用 GitExtension
// https://github.com/microsoft/vscode/tree/main/extensions/gitconst gitExtension = vscode.extensions.getExtension('vscode.git')?.exports;if (!gitExtension) {// log('Could not get Git Extension');return;}const gitApi = gitExtension.getAPI(1);
执行 shell 命令
在当前打开的项目路径下,执行 shell 命令,需要先获取到项目路径,再调用 execFile 方法。编辑器打开的可能是多个项目,vscode.workspace.workspaceFolders 返回值是一个数组。
import { execFile, ExecFileOptions } from 'child_process';import * as vscode from 'vscode';export function run<TOut extends string | Buffer>(command: string, args: string[]) {return new Promise<TOut>((res, rej) => {const folders = vscode.workspace.workspaceFolders;if (!folders || !folders[0]) {return rej();}const opts: ExecFileOptions = {cwd: folders[0].uri.path};execFile(command, args, opts, (error, stdout) => {if (error) {return rej(error);}res(stdout as TOut);});});}
获取当前打开文件的路径
const editor = vscode.window.activeTextEditor;const filePath = editor?.document.uri;
隐藏时保留 webview
// https://code.visualstudio.com/api/references/vscode-api#WebviewViewResolveContextvscode.window.registerWebviewViewProvider('view', provider, {webviewOptions: {retainContextWhenHidden: true}})
调试
直接点 vscode 中的调试按钮即可,会打开一个新窗口,选择一个项目即可调试插件。
发布
- 打包插件: vsce package
- 发布插件: vsce publish
