当前位置: 首页> 文旅> 酒店 > 如何拥有一个自己的网站_免费设计签名的软件_ping站长工具_阿里云域名购买

如何拥有一个自己的网站_免费设计签名的软件_ping站长工具_阿里云域名购买

时间:2025/8/26 14:58:03来源:https://blog.csdn.net/problc/article/details/142883014 浏览次数:0次
如何拥有一个自己的网站_免费设计签名的软件_ping站长工具_阿里云域名购买

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

你可以在 GitHub 上查看完整的代码:code-line-counter。
在这里插入图片描述

插件功能介绍

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

插件核心代码

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

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,分别用于统计整个工作区的代码行数和某个文件夹的代码行数。

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

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/**"]);
}
3. 结果展示

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);
}

扩展功能

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

插件开发工具

安装依赖

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

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

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

pnpm install

发布插件

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

vsce publish

结论

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

关键字:如何拥有一个自己的网站_免费设计签名的软件_ping站长工具_阿里云域名购买

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: