Skip to content

[OSS26] 按方法体模式搜代码 search_code_by_body_pattern #135

Description

@ponyha

接口介绍

在方法体内按正则模式匹配代码片段,定位调用、赋值、异常处理等结构;命中位置返回所在方法的全限定名,与签名级搜索的核心区别是知道"命中点属于哪个方法"。

工具名

search_code_by_body_pattern

背景与目标

签名级搜索只能命中方法签名本身,本工具解决方法体内部的模式匹配,适合:

  • 找所有调用了 Runtime.exec(...) 的方法
  • 找所有 catch 了异常但只打了 log 没 rethrow 的方法
  • 找所有读取 request.getParameter 后直接拼到 SQL 的方法

比签名搜索难一档:方法体可能横跨多行,需要 AST 边界感知,不能用纯 line regex。

输入参数

参数 类型 必填 说明
pattern string 正则模式,如 Runtime\s*\.\s*exec\s*\(
repository_path string 仓库本地绝对路径
path_prefix string 限定搜索子目录
language string 默认 java
multi_line bool 默认 true,跨行匹配
max_results int 默认 100

输出结构

{
  "pattern": "Runtime\\s*\\.\\s*exec\\s*\\(",
  "total_matches": 5,
  "results": [
    {
      "file_path": "src/main/java/com/example/Cmd.java",
      "containing_method": "com.example.Cmd.run",
      "method_start_line": 42,
      "method_end_line": 58,
      "match_line": 47,
      "match_snippet": "Runtime.getRuntime().exec(userInput);",
      "snippet_with_context": "    public void run(String userInput) {\n        ...\n        Runtime.getRuntime().exec(userInput);\n        ...\n    }"
    }
  ]
}

验收标准

  • 命中位置必须返回所在方法的全限定名(containing_method),这是与关键词搜索的关键区别
  • 多行匹配正确(默认 multi_line=true)
  • 命中位置必须在真正的方法体内,不能命中字段初始化、import、注释
  • 单元测试覆盖:跨行匹配、嵌套方法(lambda/匿名类)、注释内伪命中过滤
  • 中等仓库响应 < 5s

预估工作量

3-5 人日(关键在方法体边界识别)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions