计划开发一个用于快速提交 MR 的插件,最好只需要用鼠标点击一两下即可完成全部操作。

generator-code

首先安装 Yeoman 和 VS Code Extension Generator,运行 yo code 填写一些必要的字段即可生成一个插件项目。

  1. npm install -g yo generator-code
  1. yo code
  2. # ? What type of extension do you want to create? New Extension (TypeScript)
  3. # ? What's the name of your extension? GitlabMrt
  4. ### Press <Enter> to choose default for all options below ###
  5. # ? What's the identifier of your extension? gitlabmrt
  6. # ? What's the description of your extension? LEAVE BLANK
  7. # ? Initialize a git repository? Yes
  8. # ? Bundle the source code with webpack? No
  9. # ? Which package manager to use? npm
  10. code ./helloworld

配置

首先需要再 ActiveBar 显示一个图标,在 package.json 文件中做如下配置:

  1. {
  2. "activationEvents": [
  3. "onView:gitlab.mrt"
  4. ],
  5. "contributes": {
  6. "views": {
  7. "gitlab-mrt": [
  8. {
  9. "id": "gitlabMrt",
  10. "name": "Gitlab Mrt",
  11. "icon": "src/assets/gitlab.svg",
  12. "contextualTitle": "Gitlab Mrt"
  13. }
  14. ]
  15. },
  16. "viewsContainers": {
  17. "activitybar": [
  18. {
  19. "id": "gitlab-mrt",
  20. "title": "Gitlab Mrt",
  21. "icon": "src/assets/gitlab.svg"
  22. }
  23. ]
  24. }
  25. },
  26. }

使用 GitExtension

  1. // https://github.com/microsoft/vscode/tree/main/extensions/git
  2. const gitExtension = vscode.extensions.getExtension('vscode.git')?.exports;
  3. if (!gitExtension) {
  4. // log('Could not get Git Extension');
  5. return;
  6. }
  7. const gitApi = gitExtension.getAPI(1);

执行 shell 命令

在当前打开的项目路径下,执行 shell 命令,需要先获取到项目路径,再调用 execFile 方法。编辑器打开的可能是多个项目,vscode.workspace.workspaceFolders 返回值是一个数组。

  1. import { execFile, ExecFileOptions } from 'child_process';
  2. import * as vscode from 'vscode';
  3. export function run<TOut extends string | Buffer>(command: string, args: string[]) {
  4. return new Promise<TOut>((res, rej) => {
  5. const folders = vscode.workspace.workspaceFolders;
  6. if (!folders || !folders[0]) {
  7. return rej();
  8. }
  9. const opts: ExecFileOptions = {
  10. cwd: folders[0].uri.path
  11. };
  12. execFile(command, args, opts, (error, stdout) => {
  13. if (error) {
  14. return rej(error);
  15. }
  16. res(stdout as TOut);
  17. });
  18. });
  19. }

获取当前打开文件的路径

  1. const editor = vscode.window.activeTextEditor;
  2. const filePath = editor?.document.uri;

隐藏时保留 webview

  1. // https://code.visualstudio.com/api/references/vscode-api#WebviewViewResolveContext
  2. vscode.window.registerWebviewViewProvider('view', provider, {
  3. webviewOptions: {
  4. retainContextWhenHidden: true
  5. }
  6. })

调试

直接点 vscode 中的调试按钮即可,会打开一个新窗口,选择一个项目即可调试插件。

发布

  • 打包插件: vsce package
  • 发布插件: vsce publish

https://juejin.cn/post/6844903909564088333