|
1 | 1 | local read_file = require("neotest-java.util.read_file") |
2 | 2 |
|
3 | | -local PACKAGE_QUERY = [[ |
4 | | - ((package_declaration (scoped_identifier) @package.name)) |
5 | | - ((package_declaration (identifier) @package.name)) |
6 | | -]] |
7 | | - |
8 | 3 | ---Resolve the Java package name from a file. |
9 | 4 | ---Returns "" if no package declaration is present. |
10 | 5 | ---@param filename string |
11 | 6 | ---@return string |
12 | 7 | local function resolve_package_name(filename) |
13 | | - local function find_in_text(raw_query, content) |
14 | | - local query = vim.treesitter.query.parse("java", raw_query) |
15 | | - local lang_tree = vim.treesitter.get_string_parser(content, "java") |
16 | | - local root = lang_tree:parse()[1]:root() |
17 | | - |
18 | | - local result = {} |
19 | | - for _, node in query:iter_captures(root, content, 0, -1) do |
20 | | - result[#result + 1] = vim.treesitter.get_node_text(node, content) |
21 | | - end |
22 | | - return result |
23 | | - end |
24 | | - |
25 | 8 | local ok, content = pcall(function() |
26 | 9 | return read_file(filename) |
27 | 10 | end) |
28 | 11 | if not ok then |
29 | 12 | error(string.format("file does not exist: %s", filename)) |
30 | 13 | end |
31 | 14 |
|
32 | | - local package_lines = find_in_text(PACKAGE_QUERY, content) |
33 | | - local package_name = (package_lines and package_lines[1]) or "" |
34 | | - |
35 | | - return package_name |
| 15 | + -- Match: package com.example.foo; |
| 16 | + -- capture com.example.foo into %1 |
| 17 | + local pkg = content:match("[\r\n]^%s*package%s+([%w_%.]+)%s*;%s*[\r\n]") |
| 18 | + or content:match("^%s*package%s+([%w_%.]+)%s*;") -- in case it's on the very first line |
| 19 | + or content:match("\n%s*package%s+([%w_%.]+)%s*;") -- general fallback |
| 20 | + return pkg or "" |
36 | 21 | end |
37 | 22 |
|
38 | 23 | return resolve_package_name |
0 commit comments