在这篇文章中,我将介绍如何使用 Cursor 来实现一个 VSCode 插件,并以 代码行统计插件 为例展示其实现步骤。这个插件的主要功能是统计某个工作区内各类编程语言的代码行数、空行数等,并展示统计结果。
你可以在 GitHub 上查看完整的代码:code-line-counter。
这个 Code Line Counter 插件能够统计代码文件的总行数、代码行数、以及空行数。它支持多种语言,包括 JavaScript、TypeScript、Python 等。用户可以自定义统计范围和排除的文件或文件夹。
以下是该插件的主要实现代码。
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);
}
在 activate
方法中注册了两个命令:countCodeLines
和 countCodeLinesInFolder
,分别用于统计整个工作区的代码行数和某个文件夹的代码行数。
export function activate(context: vscode.ExtensionContext) {
let countCodeLinesDisposable = vscode.commands.registerCommand(
"codeLineCounter.countCodeLines",
() => countCodeLines()
);
context.subscriptions.push(countCodeLinesDisposable);
}
countCodeLines
方法是代码行统计的核心功能。它从工作区中获取目录,读取目录下的文件,并根据文件的扩展名确定编程语言,统计每个文件的总行数、代码行数、和空行数。
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/**"]);
}
displayResults
函数将统计结果以弹窗的形式展示给用户。
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);
}
node_modules
)。插件的开发使用了以下工具:
在开始开发之前,使用 pnpm 安装依赖:
pnpm install
发布插件到 VSCode Marketplace 之前,确保你已经安装了 vsce 工具,并执行以下命令:
vsce publish
通过这篇文章,我们了解了如何使用 Cursor 实现一个 VSCode 插件。这个插件的主要功能是统计工作区中的代码行数,并支持多语言扩展。你可以在 GitHub 查看完整的代码和更多细节。