使用 Cursor 实现 VSCode 插件

在这篇文章中,我将介绍如何使用 Cursor 来实现一个 VSCode 插件 ,并以 代码行统计插件 为例展示其实现步骤。这个插件的主要功能是统计某个工作区内各类编程语言的代码行数、空行数等,并展示统计结果。

你可以在 GitHub 上查看完整的代码:code-line-counter

插件功能介绍

这个 Code Line Counter 插件能够统计代码文件的总行数、代码行数、以及空行数。它支持多种语言,包括 JavaScriptTypeScriptPython 等。用户可以自定义统计范围和排除的文件或文件夹。

插件核心代码

以下是该插件的主要实现代码。

typescript 复制代码
import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
import { promisify } from "util";
import glob from "glob";

const globAsync = promisify(glob);

// 定义语言和文件扩展名的映射
const defaultLanguageExtensions: { [key: string]: string[] } = {
  JavaScript: [".js", ".jsx"],
  TypeScript: [".ts", ".tsx"],
  Python: [".py"],
  Java: [".java"],
  "C++": [".cpp", ".hpp", ".h"],
};

interface CodeStats {
  totalLines: number;
  codeLines: number;
  blankLines: number;
}

interface LanguageStats {
  [language: string]: CodeStats;
}

export function activate(context: vscode.ExtensionContext) {
  console.log("Code Line Counter 扩展已激活");

  let countCodeLinesDisposable = vscode.commands.registerCommand(
    "codeLineCounter.countCodeLines",
    () => countCodeLines()
  );

  let countCodeLinesInFolderDisposable = vscode.commands.registerCommand(
    "codeLineCounter.countCodeLinesInFolder",
    (folderUri: vscode.Uri) => countCodeLines([folderUri.fsPath])
  );

  context.subscriptions.push(countCodeLinesDisposable, countCodeLinesInFolderDisposable);
  console.log("countCodeLines 命令已注册");
}

async function countCodeLines(initialIncludeDirs: string[] = []) {
  console.log("countCodeLines 命令已执行");

  const workspaceFolders = vscode.workspace.workspaceFolders;
  if (!workspaceFolders) {
    vscode.window.showErrorMessage("没有打开的工作区。");
    return;
  }

  const rootPath = workspaceFolders[0].uri.fsPath;
  const defaultSrcPath = path.join(rootPath, 'src');

  const config = vscode.workspace.getConfiguration("codeLineCounter");
  let includeDirs = config.get<string[]>("includeDirs") || [];
  let excludePatterns = config.get<string[]>("excludePatterns") || [];

  includeDirs = [...new Set([...initialIncludeDirs, ...includeDirs])];

  if (includeDirs.length === 0 && fs.existsSync(defaultSrcPath)) {
    includeDirs = [defaultSrcPath];
  }

  const includeInput = await vscode.window.showInputBox({
    prompt: "请输入要包含的目录(用逗号分隔)",
    value: includeDirs.join(", "),
  });

  const excludeInput = await vscode.window.showInputBox({
    prompt: "请输入要排除的模式(用逗号分隔)",
    value: excludePatterns.join(", "),
  });

  if (includeInput !== undefined) {
    includeDirs = includeInput.split(",").map(dir => dir.trim());
  }

  if (excludeInput !== undefined) {
    excludePatterns = excludeInput.split(",").map(pattern => pattern.trim());
  }

  await config.update("includeDirs", includeDirs, vscode.ConfigurationTarget.Workspace);
  await config.update("excludePatterns", excludePatterns, vscode.ConfigurationTarget.Workspace);

  const userDefinedLanguages = config.get<{ [key: string]: string[] }>("languageExtensions") || {};
  const languageExtensions = { ...defaultLanguageExtensions, ...userDefinedLanguages };

  if (includeDirs.length === 0) {
    vscode.window.showErrorMessage("请指定要统计的目录。");
    return;
  }

  const stats: LanguageStats = {};

  for (const dir of includeDirs) {
    await countLinesInDirectory(dir, excludePatterns, stats, languageExtensions);
  }

  displayResults(stats, includeDirs, excludePatterns);
}

代码解析

1. 激活插件

activate 方法中注册了两个命令:countCodeLinescountCodeLinesInFolder,分别用于统计整个工作区的代码行数和某个文件夹的代码行数。

typescript 复制代码
export function activate(context: vscode.ExtensionContext) {
  let countCodeLinesDisposable = vscode.commands.registerCommand(
    "codeLineCounter.countCodeLines",
    () => countCodeLines()
  );
  
  context.subscriptions.push(countCodeLinesDisposable);
}
2. 统计代码行数

countCodeLines 方法是代码行统计的核心功能。它从工作区中获取目录,读取目录下的文件,并根据文件的扩展名确定编程语言,统计每个文件的总行数、代码行数、和空行数。

typescript 复制代码
async function countCodeLines(initialIncludeDirs: string[] = []) {
  // 获取工作区目录和用户输入的包含目录、排除模式
  const includeDirs = ["src", "lib"]; // 示例目录
  const stats: LanguageStats = {};

  for (const dir of includeDirs) {
    await countLinesInDirectory(dir, ["**/node_modules/**"], stats, defaultLanguageExtensions);
  }

  displayResults(stats, includeDirs, ["**/node_modules/**"]);
}
3. 结果展示

displayResults 函数将统计结果以弹窗的形式展示给用户。

typescript 复制代码
function displayResults(stats: LanguageStats, includeDirs: string[], excludePatterns: string[]): void {
  let message = "代码行统计结果:\n\n";
  
  message += "包含的文件夹:\n";
  includeDirs.forEach(dir => message += `  - ${dir}\n`);
  message += "\n排除的模式:\n";
  excludePatterns.forEach(pattern => message += `  - ${pattern}\n\n`);

  Object.entries(stats).forEach(([language, { totalLines, codeLines, blankLines }]) => {
    message += `${language}:\n  总行数: ${totalLines}\n  代码行: ${codeLines}\n  空行: ${blankLines}\n\n`;
  });

  vscode.window.showInformationMessage(message);
}

扩展功能

  • 语言扩展配置 :用户可以通过 settings.json 来扩展插件支持的编程语言和对应的文件扩展名。
  • 排除模式 :用户可以通过输入框选择排除特定目录或文件模式(例如 node_modules)。

插件开发工具

安装依赖

插件的开发使用了以下工具:

  • TypeScript:作为插件的主要编程语言。
  • VSCode Extension API:提供了操作工作区、读取文件的接口。
  • Glob:用于查找指定目录下的文件。

在开始开发之前,使用 pnpm 安装依赖:

bash 复制代码
pnpm install

发布插件

发布插件到 VSCode Marketplace 之前,确保你已经安装了 vsce 工具,并执行以下命令:

bash 复制代码
vsce publish

结论

通过这篇文章,我们了解了如何使用 Cursor 实现一个 VSCode 插件 。这个插件的主要功能是统计工作区中的代码行数,并支持多语言扩展。你可以在 GitHub 查看完整的代码和更多细节。

相关推荐
Mr.简锋1 小时前
vim实用笔记
笔记·编辑器·vim
獨枭2 小时前
Visual Studio 2022 配置 Boost 库
ide·visual studio
PleaSure乐事5 小时前
【React】如何在MacBook的vscode中配置React环境
开发语言·前端·javascript·vscode·react.js·前端框架
乐闻x6 小时前
VSCode 如何格式化某个文件夹下所有的文件
ide·vscode·prettier
snailaf6 小时前
VSCODE 导入cubeide工程
ide·vscode·编辑器
xxxxxmy6 小时前
VSCode的常用插件(持续更新)
vscode·python·编辑器
zkk95276 小时前
C++调试方法(Vscode)(二) ——本地调试(ROS版)
开发语言·c++·vscode·gdb·调试
海鸥_6 小时前
Ubuntu中vscode如何选择ROS版本
linux·vscode·ubuntu
Eiceblue7 小时前
.NET 通过C#设置Excel工作表的页面设置
开发语言·vscode·c#·.net·excel