You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code扩展开发中使用Octokit获取当前GitHub仓库名称的方法

VS Code扩展获取当前GitHub仓库名称方案

实现步骤

1. 声明Git扩展依赖

在扩展的package.json中新增配置,声明依赖VS Code内置Git扩展:

{
  "extensionDependencies": ["vscode.git"]
}

2. 调用Git API获取仓库远程地址

const vscode = require('vscode');

// 获取内置Git扩展实例
const gitExtension = vscode.extensions.getExtension('vscode.git')?.exports;
if (!gitExtension) {
  vscode.window.showErrorMessage('Git扩展未启用');
  return;
}
const gitApi = gitExtension.getAPI(1);

// 取当前工作区第一个Git仓库,多仓库场景可根据激活文件路径匹配对应仓库
const currentRepo = gitApi.repositories[0];
if (!currentRepo) {
  vscode.window.showErrorMessage('当前未打开Git仓库');
  return;
}

// 获取origin远程仓库地址
const originRemote = currentRepo.state.remotes.find(remote => remote.name === 'origin');
const remoteUrl = originRemote?.fetchUrl || originRemote?.pushUrl;
if (!remoteUrl) {
  vscode.window.showErrorMessage('仓库未配置origin远程地址');
  return;
}

3. 解析远程地址获取仓库名和所有者

function parseGitHubUrl(url) {
  // 同时匹配HTTPS和SSH两种Git地址格式
  const gitReg = /(?:https:\/\/github\.com\/|git@github\.com:)([^\/]+)\/([^.\n]+)(?:\.git)?$/;
  const matchResult = url.match(gitReg);
  if (matchResult) {
    return {
      owner: matchResult[1],
      repo: matchResult[2]
    };
  }
  return null;
}

const repoInfo = parseGitHubUrl(remoteUrl);
if (!repoInfo) {
  vscode.window.showErrorMessage('当前仓库不是GitHub仓库');
  return;
}
const { owner, repo: currentRepoName } = repoInfo;

4. 代入原有逻辑调用GitHub接口

return await octokit.rest.projects
  .listForRepo({
    owner: owner,
    repo: currentRepoName,
  });

注意事项

  • 多仓库工作区场景下,可通过vscode.window.activeTextEditor?.document.uri.fsPath获取当前激活文件路径,遍历gitApi.repositories匹配对应仓库
  • 若未启用内置Git扩展,也可自行读取工作区.git/config文件解析远程地址,逻辑和上述解析规则一致

内容的提问来源于stack exchange,提问作者Felix Niedermann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:24:03