十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Repomix 代码压缩(Code Compression)指南:用 Tree-sitter 在保留代码结构的同时降低 token 消耗

Repomix 代码压缩(Code Compression)指南:用 Tree-sitter 在保留代码结构的同时降低 token 消耗 Repomix 代码压缩Code Compression指南用 Tree-sitter 在保留代码结构的同时降低 token 消耗【免费下载链接】repomix Repomix is a powerful tool that packs your entire repository into a single, AI-friendly file. Perfect for when you need to feed your codebase to Large Language Models (LLMs) or other AI tools like Claude, ChatGPT, DeepSeek, Perplexity, Gemini, Gemma, Llama, Grok, and more.项目地址: https://gitcode.com/GitHub_Trending/rep/repomixRepomix 的代码压缩Code Compression是一项基于 Tree-sitter 解析的试验性功能它能够在打包整个代码库时智能提取函数签名、接口/类型定义、类结构与导入语句等结构性信息同时剥离函数实现、循环与条件逻辑等实现细节从而显著减少喂给 LLM 的文件体积与 token 数量。本文基于 website/client/src/it/guide/code-compress.md 展开结合 src/core/treeSitter 下的解析器、策略与测试代码完整讲解该功能的使用方式、底层原理、配置方法及适用场景读完即可在自己的项目中用--compress生成“结构完整、细节精炼”的 AI 友好打包文件。基本用法一条命令开启压缩代码压缩是 Repomix 的一个可选输出开关通过 CLI 的--compress标志即可启用。对当前目录下的项目执行repomix --compress也可以与远程仓库处理结合使用直接对 GitHub 上的仓库进行压缩打包repomix --remote user/repo --compress从 CLI 解析链路看--compress最终被映射为配置对象中的output.compress字段见 src/cli/actions/defaultAction.tsif (options.compress ! undefined) { cliConfig.output { ...cliConfig.output, compress: options.compress }; }也就是说无论通过命令行还是配置文件开启底层走的都是同一条压缩管线。工作原理Tree-sitter 解析与结构提取代码压缩的核心思想是用 Tree-sitter 把源码解析成抽象语法树AST再通过语言专属的查询规则query捕获关键结构性节点只保留这些节点对应的代码片段。保留什么、移除什么压缩算法保留的是代码的“骨架”函数与方法签名Function and method signatures接口interface与类型type定义类结构及其属性Class structures and propertiesimport / export 语句等重要的结构性元素同时移除的是“血肉”函数与方法的具体实现循环与条件分支的逻辑细节函数体内部的局部变量声明与具体实现绑定的代码一个 TypeScript 示例原始代码import { ShoppingItem } from ./shopping-item; /** * Calculate the total price of shopping items */ const calculateTotal ( items: ShoppingItem[] ) { let total 0; for (const item of items) { total item.price * item.quantity; } return total; } // Shopping item interface interface Item { name: string; price: number; quantity: number; }压缩之后import { ShoppingItem } from ./shopping-item; ⋮---- /** * Calculate the total price of shopping items */ const calculateTotal ( items: ShoppingItem[] ) { ⋮---- // Shopping item interface interface Item { name: string; price: number; quantity: number; }可以看到import语句、函数签名含参数类型、以及完整的interface Item定义都被保留而calculateTotal内部的求和循环与返回值实现被移除⋮----是压缩产物中的区块分隔符由源码中的CHUNK_SEPARATOR常量定义见 src/core/treeSitter/parseFile.ts。压缩管线的实现细节整个压缩入口是parseFile见 src/core/treeSitter/parseFile.ts其处理步骤大致为根据文件扩展名猜测语言guessTheLang若语言不受支持则静默返回回退为未压缩内容获取该语言的 Tree-sitter query 与 parser将文件内容解析为 AST在根节点上执行 query得到捕获节点captures并按起始行排序交给对应语言的ParseStrategy逐节点提取内容经filterDuplicatedChunks去重同一起始行保留内容最长的捕获、mergeAdjacentChunks合并相邻区块后用⋮----拼接输出。值得注意的几个设计点WASM 而非原生绑定项目使用web-tree-sitterWASM而不是node-tree-sitter原生绑定原因在 src/core/treeSitter/parseFile.ts 的注释中写得很清楚跨平台一致、安装无需编译工具链Python/C 编译器、node-gyp、所有语言解析器集中在单一包repomix/tree-sitter-wasms中、并规避了部分 Node.js 版本如 v23下原生模块的构建问题。尽力而为best-effortparseFile设计上从不抛异常——任何解析失败包括 WASM 运行时中止都会记录警告并返回undefined让调用方回退到未压缩内容保证单个异常文件不会拖垮整个打包过程见 parseFile.ts。Parser 单例LanguageParser以单例形式懒加载复用初始化失败时保持null以便下次重试见 parseFile.ts。语言专属策略与查询每种语言都对应一个 Tree-sitter query 与一个解析策略注册表定义在 src/core/treeSitter/languageConfig.ts目前支持 16 种语言语言扩展名解析策略JavaScriptjs, jsx, cjs, mjs, mjsxTypeScriptParseStrategyTypeScriptts, tsx, mts, mtsx, ctsTypeScriptParseStrategyPythonpyPythonParseStrategyGogoGoParseStrategyVuevueVueParseStrategyCSScssCssParseStrategyRustrsDefaultParseStrategyJavajavaDefaultParseStrategyC#csDefaultParseStrategyRubyrbDefaultParseStrategyPHPphpDefaultParseStrategySwiftswiftDefaultParseStrategyCc, hDefaultParseStrategyCcpp, hppDefaultParseStrategySoliditysolDefaultParseStrategyDartdartDefaultParseStrategy以 TypeScript 策略为例见 src/core/treeSitter/parseStrategies/TypeScriptParseStrategy.ts其捕获类型包括注释comment、接口definition.interface、类型definition.type、枚举definition.enum、类definition.class、导入definition.import、函数definition.function、方法definition.method与属性definition.property。函数捕获会进一步只截取签名部分findSignatureEnd找到参数列表结束的)并配合{//;判断边界cleanFunctionSignature负责清理结尾类捕获则只保留类声明行以及紧随其后的extends/implements行——这正是压缩后“只有骨架”的原因。配置文件中的压缩开关除命令行外也可以在配置文件中开启压缩。在repomix.config.json的output节点下设置{ output: { compress: true } }字段定义与默认值见 src/config/configSchema.tscompress是可选布尔值默认关闭false因此想启用压缩必须显式打开。仓库根目录的 repomix.config.json 中compress: false就是默认未开启的真实示例。按文件粒度覆盖output.patterns配置层面还支持更细粒度的控制。output.patterns允许按 glob 模式对单个文件覆盖全局压缩设置见 src/config/configSchema.ts条目按数组顺序求值、第一个匹配生效且directoryStructureOnly优先于compress——若文件被标记为仅目录结构则其内容块会从输出中整体省略。示例{ output: { compress: true, patterns: [ { pattern: src/generated/**, compress: false }, { pattern: vendor/**, directoryStructureOnly: true } ] } }从源码看压缩的实际生效依据是每个文件解析出的包含级别inclusion level而非单纯看全局compress标志resolveFileLevel会综合全局配置与output.patterns得出每文件级别见 src/core/file/fileProcess.ts测试用例也验证了“全局关闭但传入compress级别时仍压缩”“全局开启但级别为full时不压缩”这两种行为见 tests/core/file/fileProcessContent.test.ts。在打包管线中的位置压缩不是独立于打包流程的旁路而是文件处理管线的一环。处理分两个阶段见 src/core/file/fileProcess.ts重型转换worker 线程removeComments→compress。因为 Tree-sitter 解析与 AST 操作开销大只有需要注释移除或压缩时才启动 worker 线程池useWorkers needsCompression || config.output.removeComments。轻量转换主线程truncateBase64→removeEmptyLines→trim→showLineNumbers。转换顺序的设计也有讲究removeEmptyLines放在removeComments之后是为了清理注释移除后留下的空行。此外压缩过的文件不会显示行号——因为其内容是被重构的签名片段、并非与源文件逐行对应showLineNumbers对级别为compress的文件会被抑制见 fileProcess.ts 相关逻辑即 src/core/file/fileProcess.ts。与其他选项组合使用压缩可以与 Repomix 的其他输出选项自由组合进一步控制产物--remove-comments移除代码注释进一步降低 token详见注释移除指南--remove-empty-lines移除空行让输出更紧凑--output-show-line-numbers为输出添加行号注意对已压缩文件不生效。组合示例repomix --compress --remove-comments --remove-empty-lines典型使用场景代码压缩特别适合以下需求分析代码结构与架构压缩产物本身就是一份“带签名的结构索引”快速呈现模块边界与调用面降低 token 消耗将大仓库喂给 LLM如 Claude、ChatGPT、DeepSeek 等前先压缩可显著减少输入 token生成高层级文档以压缩后的骨架为素材让 LLM 快速产出架构说明理解代码模式与函数签名不必通读实现即可掌握 API 形态分享 API 与接口设计接口、类型、类定义被完整保留适合跨团队沟通设计意图。相关资源注释移除指南移除注释以进一步缩减 token配置指南在配置文件中设置output.compress命令行选项参考完整的 CLI 参数说明压缩核心实现src/core/treeSitter/parseFile.ts、src/core/treeSitter/languageConfig.ts各语言解析策略src/core/treeSitter/parseStrategies压缩行为测试tests/core/file/fileProcessContent.test.ts。【免费下载链接】repomix Repomix is a powerful tool that packs your entire repository into a single, AI-friendly file. Perfect for when you need to feed your codebase to Large Language Models (LLMs) or other AI tools like Claude, ChatGPT, DeepSeek, Perplexity, Gemini, Gemma, Llama, Grok, and more.项目地址: https://gitcode.com/GitHub_Trending/rep/repomix创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表