tree-sitter-analyzer 0.2.0__py3-none-any.whl → 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of tree-sitter-analyzer might be problematic. Click here for more details.

Files changed (78) hide show
  1. tree_sitter_analyzer/__init__.py +134 -121
  2. tree_sitter_analyzer/__main__.py +11 -12
  3. tree_sitter_analyzer/api.py +533 -539
  4. tree_sitter_analyzer/cli/__init__.py +39 -39
  5. tree_sitter_analyzer/cli/__main__.py +12 -13
  6. tree_sitter_analyzer/cli/commands/__init__.py +26 -27
  7. tree_sitter_analyzer/cli/commands/advanced_command.py +88 -88
  8. tree_sitter_analyzer/cli/commands/base_command.py +160 -155
  9. tree_sitter_analyzer/cli/commands/default_command.py +18 -19
  10. tree_sitter_analyzer/cli/commands/partial_read_command.py +141 -133
  11. tree_sitter_analyzer/cli/commands/query_command.py +81 -82
  12. tree_sitter_analyzer/cli/commands/structure_command.py +138 -121
  13. tree_sitter_analyzer/cli/commands/summary_command.py +101 -93
  14. tree_sitter_analyzer/cli/commands/table_command.py +235 -233
  15. tree_sitter_analyzer/cli/info_commands.py +120 -121
  16. tree_sitter_analyzer/cli_main.py +278 -276
  17. tree_sitter_analyzer/core/__init__.py +15 -20
  18. tree_sitter_analyzer/core/analysis_engine.py +555 -574
  19. tree_sitter_analyzer/core/cache_service.py +320 -330
  20. tree_sitter_analyzer/core/engine.py +559 -560
  21. tree_sitter_analyzer/core/parser.py +293 -288
  22. tree_sitter_analyzer/core/query.py +502 -502
  23. tree_sitter_analyzer/encoding_utils.py +456 -460
  24. tree_sitter_analyzer/exceptions.py +337 -340
  25. tree_sitter_analyzer/file_handler.py +210 -222
  26. tree_sitter_analyzer/formatters/__init__.py +1 -1
  27. tree_sitter_analyzer/formatters/base_formatter.py +167 -168
  28. tree_sitter_analyzer/formatters/formatter_factory.py +78 -74
  29. tree_sitter_analyzer/formatters/java_formatter.py +291 -270
  30. tree_sitter_analyzer/formatters/python_formatter.py +259 -235
  31. tree_sitter_analyzer/interfaces/__init__.py +9 -10
  32. tree_sitter_analyzer/interfaces/cli.py +528 -557
  33. tree_sitter_analyzer/interfaces/cli_adapter.py +343 -319
  34. tree_sitter_analyzer/interfaces/mcp_adapter.py +206 -170
  35. tree_sitter_analyzer/interfaces/mcp_server.py +405 -416
  36. tree_sitter_analyzer/java_analyzer.py +187 -219
  37. tree_sitter_analyzer/language_detector.py +398 -400
  38. tree_sitter_analyzer/language_loader.py +224 -228
  39. tree_sitter_analyzer/languages/__init__.py +10 -11
  40. tree_sitter_analyzer/languages/java_plugin.py +1174 -1113
  41. tree_sitter_analyzer/{plugins → languages}/javascript_plugin.py +446 -439
  42. tree_sitter_analyzer/languages/python_plugin.py +747 -712
  43. tree_sitter_analyzer/mcp/__init__.py +31 -32
  44. tree_sitter_analyzer/mcp/resources/__init__.py +44 -47
  45. tree_sitter_analyzer/mcp/resources/code_file_resource.py +209 -213
  46. tree_sitter_analyzer/mcp/resources/project_stats_resource.py +555 -550
  47. tree_sitter_analyzer/mcp/server.py +333 -345
  48. tree_sitter_analyzer/mcp/tools/__init__.py +30 -31
  49. tree_sitter_analyzer/mcp/tools/analyze_scale_tool.py +654 -557
  50. tree_sitter_analyzer/mcp/tools/analyze_scale_tool_cli_compatible.py +247 -245
  51. tree_sitter_analyzer/mcp/tools/base_tool.py +54 -55
  52. tree_sitter_analyzer/mcp/tools/read_partial_tool.py +300 -302
  53. tree_sitter_analyzer/mcp/tools/table_format_tool.py +362 -359
  54. tree_sitter_analyzer/mcp/tools/universal_analyze_tool.py +543 -476
  55. tree_sitter_analyzer/mcp/utils/__init__.py +107 -106
  56. tree_sitter_analyzer/mcp/utils/error_handler.py +549 -549
  57. tree_sitter_analyzer/models.py +470 -481
  58. tree_sitter_analyzer/output_manager.py +255 -264
  59. tree_sitter_analyzer/plugins/__init__.py +280 -334
  60. tree_sitter_analyzer/plugins/base.py +496 -446
  61. tree_sitter_analyzer/plugins/manager.py +379 -355
  62. tree_sitter_analyzer/queries/__init__.py +26 -27
  63. tree_sitter_analyzer/queries/java.py +391 -394
  64. tree_sitter_analyzer/queries/javascript.py +148 -149
  65. tree_sitter_analyzer/queries/python.py +285 -286
  66. tree_sitter_analyzer/queries/typescript.py +229 -230
  67. tree_sitter_analyzer/query_loader.py +257 -260
  68. tree_sitter_analyzer/table_formatter.py +471 -448
  69. tree_sitter_analyzer/utils.py +277 -277
  70. {tree_sitter_analyzer-0.2.0.dist-info → tree_sitter_analyzer-0.4.0.dist-info}/METADATA +23 -8
  71. tree_sitter_analyzer-0.4.0.dist-info/RECORD +73 -0
  72. {tree_sitter_analyzer-0.2.0.dist-info → tree_sitter_analyzer-0.4.0.dist-info}/entry_points.txt +2 -1
  73. tree_sitter_analyzer/plugins/java_plugin.py +0 -625
  74. tree_sitter_analyzer/plugins/plugin_loader.py +0 -83
  75. tree_sitter_analyzer/plugins/python_plugin.py +0 -598
  76. tree_sitter_analyzer/plugins/registry.py +0 -366
  77. tree_sitter_analyzer-0.2.0.dist-info/RECORD +0 -77
  78. {tree_sitter_analyzer-0.2.0.dist-info → tree_sitter_analyzer-0.4.0.dist-info}/WHEEL +0 -0
@@ -1,219 +1,187 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """
4
- Java Code Analyzer with tree-sitter
5
- """
6
- import json
7
- import sys
8
- from pathlib import Path
9
- from typing import Any, Dict, List, Optional
10
-
11
- try:
12
- import tree_sitter
13
- import tree_sitter_java as tsjava
14
- from tree_sitter import Language, Node, Parser
15
-
16
- TREE_SITTER_AVAILABLE = True
17
- except ImportError:
18
- TREE_SITTER_AVAILABLE = False
19
- from .utils import log_error
20
-
21
- log_error(
22
- "tree-sitter libraries not found. Please install tree-sitter and tree-sitter-java."
23
- )
24
-
25
- from .file_handler import read_file_with_fallback
26
- from .output_manager import output_error, output_info, output_warning
27
- from .utils import log_error, log_info, log_warning
28
-
29
-
30
- class CodeAnalyzer:
31
- """
32
- Tree-sitterを使用してソースコードを解析するコアクラス。
33
-
34
- Attributes:
35
- language: Tree-sitter言語オブジェクト
36
- parser: Tree-sitterパーサー
37
- source_code_bytes: 解析対象のソースコードのバイト列
38
- tree: 構築されたAST
39
- """
40
-
41
- def __init__(self, language: str = "java") -> None:
42
- """
43
- 指定された言語用のパーサーを初期化する。
44
-
45
- Args:
46
- language: 解析対象のプログラミング言語。現在はJavaのみサポート。
47
-
48
- Raises:
49
- SystemExit: Tree-sitterライブラリの初期化に失敗した場合
50
- """
51
- if not TREE_SITTER_AVAILABLE:
52
- output_error("ERROR: Tree-sitter libraries not available.")
53
- raise RuntimeError("Tree-sitter libraries not available")
54
-
55
- try:
56
- if language != "java":
57
- output_warning(
58
- f"WARNING: Currently only Java is supported. Using Java parser."
59
- )
60
-
61
- self.language = Language(tsjava.language())
62
- self.parser = Parser(self.language)
63
- self.source_code_bytes: bytes = b""
64
- self.tree: Optional[tree_sitter.Tree] = None
65
-
66
- except Exception as e:
67
- output_error(
68
- f"ERROR: '{language}' 言語の初期化に失敗しました。ライブラリが正しくインストールされているか確認してください。"
69
- )
70
- output_error(f"詳細: {e}")
71
- raise RuntimeError(f"Failed to initialize language '{language}': {e}")
72
-
73
- def parse_file(self, file_path: str) -> bool:
74
- """
75
- 指定されたファイルを解析し、AST(抽象構文木)を構築する。
76
-
77
- Args:
78
- file_path: 解析するソースファイルのパス
79
-
80
- Returns:
81
- 解析に成功した場合はTrue、失敗した場合はFalse
82
-
83
- Raises:
84
- None: エラーは内部でハンドリングし、戻り値で示す
85
- """
86
- try:
87
- source_bytes = read_file_with_fallback(file_path)
88
- if source_bytes is None:
89
- output_error(
90
- f"ERROR: ファイル '{file_path}' の読み込みに失敗しました。"
91
- )
92
- return False
93
-
94
- self.source_code_bytes = source_bytes
95
- self.tree = self.parser.parse(self.source_code_bytes)
96
-
97
- if self.tree is None:
98
- output_error(f"ERROR: '{file_path}' のAST構築に失敗しました。")
99
- return False
100
-
101
- log_info(f"INFO: '{file_path}' の解析が完了し、ASTを構築しました。")
102
- return True
103
-
104
- except Exception as e:
105
- output_error(f"ERROR: ファイル解析中にエラーが発生しました: {e}")
106
- return False
107
-
108
- def execute_query(self, query_string: str) -> List[Dict[str, Any]]:
109
- """
110
- ASTに対して指定されたクエリを実行し、マッチしたノードの情報を抽出する。
111
-
112
- Args:
113
- query_string: 実行するTree-sitterクエリ
114
-
115
- Returns:
116
- マッチした各ノードの情報(内容、位置、キャプチャ名)のリスト
117
-
118
- Raises:
119
- None: エラーは内部でハンドリングし、空リストを返す
120
- """
121
- if not self.tree:
122
- output_error(
123
- "ERROR: ASTが構築されていません。先にparse_fileを実行してください。"
124
- )
125
- return []
126
-
127
- try:
128
- query = self.language.query(query_string)
129
- except Exception as e:
130
- output_error(
131
- f"ERROR: クエリのコンパイルに失敗しました。\nクエリ: {query_string}\nエラー: {e}"
132
- )
133
- return []
134
-
135
- try:
136
- captures = query.captures(self.tree.root_node)
137
- except Exception as e:
138
- output_error(f"ERROR: クエリの実行に失敗しました: {e}")
139
- return []
140
-
141
- results = []
142
-
143
- # Tree-sitter 0.24以降の辞書形式に対応
144
- try:
145
- if isinstance(captures, dict):
146
- # 新しい辞書形式: {capture_name: [nodes...]}
147
- for capture_name, nodes in captures.items():
148
- if isinstance(nodes, list):
149
- for node in nodes:
150
- try:
151
- start_line = node.start_point[0] + 1
152
- end_line = node.end_point[0] + 1
153
- node_text = self.source_code_bytes[
154
- node.start_byte : node.end_byte
155
- ].decode("utf-8", errors="ignore")
156
-
157
- results.append(
158
- {
159
- "capture_name": capture_name,
160
- "content": node_text,
161
- "start_line": start_line,
162
- "end_line": end_line,
163
- "node_type": node.type,
164
- }
165
- )
166
- except Exception as e:
167
- output_warning(
168
- f"WARNING: ノード処理中にエラーが発生しました: {e}"
169
- )
170
- continue
171
- else:
172
- # 古い形式への対応(フォールバック)
173
- if hasattr(captures, "__iter__"):
174
- for capture in captures:
175
- try:
176
- if isinstance(capture, tuple) and len(capture) == 2:
177
- node, capture_name = capture
178
- start_line = node.start_point[0] + 1
179
- end_line = node.end_point[0] + 1
180
- node_text = self.source_code_bytes[
181
- node.start_byte : node.end_byte
182
- ].decode("utf-8", errors="ignore")
183
-
184
- results.append(
185
- {
186
- "capture_name": capture_name,
187
- "content": node_text,
188
- "start_line": start_line,
189
- "end_line": end_line,
190
- "node_type": node.type,
191
- }
192
- )
193
- except Exception as e:
194
- output_warning(
195
- f"WARNING: ノード処理中にエラーが発生しました: {e}"
196
- )
197
- continue
198
-
199
- except Exception as e:
200
- output_error(f"ERROR: capture処理中に予期しないエラーが発生しました: {e}")
201
- return []
202
-
203
- return results
204
-
205
-
206
- def main() -> None:
207
- """
208
- モジュールが直接実行された場合のエントリーポイント。
209
- 通常はcli.pyを使用することを推奨。
210
- """
211
- output_warning("注意: 直接的なモジュール実行は非推奨です。")
212
- output_warning("代わりに以下を使用してください:")
213
- output_info(" uv run java-analyzer <file> --query-key <key>")
214
- output_info(" または")
215
- output_info(" python -m tree_sitter_analyzer.cli <file> --query-key <key>")
216
-
217
-
218
- if __name__ == "__main__":
219
- main()
1
+ #!/usr/bin/env python3
2
+ """
3
+ Java Code Analyzer with tree-sitter
4
+ """
5
+
6
+ from typing import Any
7
+
8
+ try:
9
+ import tree_sitter
10
+ import tree_sitter_java as tsjava
11
+ from tree_sitter import Language, Parser
12
+
13
+ TREE_SITTER_AVAILABLE = True
14
+ except ImportError:
15
+ TREE_SITTER_AVAILABLE = False
16
+ from .utils import log_error
17
+
18
+ log_error(
19
+ "tree-sitter libraries not found. Please install tree-sitter and tree-sitter-java."
20
+ )
21
+
22
+ from .file_handler import read_file_with_fallback
23
+ from .output_manager import output_error, output_info, output_warning
24
+ from .utils import log_error, log_info
25
+
26
+
27
+ class CodeAnalyzer:
28
+ """
29
+ Tree-sitterを使用してソースコードを解析するコアクラス。
30
+
31
+ Attributes:
32
+ language: Tree-sitter言語オブジェクト
33
+ parser: Tree-sitterパーサー
34
+ source_code_bytes: 解析対象のソースコードのバイト列
35
+ tree: 構築されたAST
36
+ """
37
+
38
+ def __init__(self, language: str = "java") -> None:
39
+ """
40
+ 指定された言語用のパーサーを初期化する。
41
+
42
+ Args:
43
+ language: 解析対象のプログラミング言語。現在はJavaのみサポート。
44
+
45
+ Raises:
46
+ SystemExit: Tree-sitterライブラリの初期化に失敗した場合
47
+ """
48
+ if not TREE_SITTER_AVAILABLE:
49
+ output_error("ERROR: Tree-sitter libraries not available.")
50
+ raise RuntimeError("Tree-sitter libraries not available")
51
+
52
+ try:
53
+ if language != "java":
54
+ output_warning(
55
+ "WARNING: Currently only Java is supported. Using Java parser."
56
+ )
57
+
58
+ self.language = Language(tsjava.language())
59
+ self.parser = Parser(self.language)
60
+ self.source_code_bytes: bytes = b""
61
+ self.tree: tree_sitter.Tree | None = None
62
+
63
+ except Exception as e:
64
+ output_error(
65
+ f"ERROR: '{language}' 言語の初期化に失敗しました。ライブラリが正しくインストールされているか確認してください。"
66
+ )
67
+ output_error(f"詳細: {e}")
68
+ raise RuntimeError(
69
+ f"Failed to initialize language '{language}': {e}"
70
+ ) from e
71
+
72
+ def parse_file(self, file_path: str) -> bool:
73
+ """
74
+ 指定されたファイルを解析し、AST(抽象構文木)を構築する。
75
+
76
+ Args:
77
+ file_path: 解析するソースファイルのパス
78
+
79
+ Returns:
80
+ 解析に成功した場合はTrue、失敗した場合はFalse
81
+
82
+ Raises:
83
+ None: エラーは内部でハンドリングし、戻り値で示す
84
+ """
85
+ try:
86
+ source_bytes = read_file_with_fallback(file_path)
87
+ if source_bytes is None:
88
+ output_error(
89
+ f"ERROR: ファイル '{file_path}' の読み込みに失敗しました。"
90
+ )
91
+ return False
92
+
93
+ self.source_code_bytes = source_bytes
94
+ self.tree = self.parser.parse(self.source_code_bytes)
95
+
96
+ # Tree parsing should always succeed with valid input
97
+ log_info(f"INFO: '{file_path}' の解析が完了し、ASTを構築しました。")
98
+ return True
99
+
100
+ except Exception as e:
101
+ output_error(f"ERROR: ファイル解析中にエラーが発生しました: {e}")
102
+ return False
103
+
104
+ def execute_query(self, query_string: str) -> list[dict[str, Any]]:
105
+ """
106
+ ASTに対して指定されたクエリを実行し、マッチしたノードの情報を抽出する。
107
+
108
+ Args:
109
+ query_string: 実行するTree-sitterクエリ
110
+
111
+ Returns:
112
+ マッチした各ノードの情報(内容、位置、キャプチャ名)のリスト
113
+
114
+ Raises:
115
+ None: エラーは内部でハンドリングし、空リストを返す
116
+ """
117
+ if not self.tree:
118
+ output_error(
119
+ "ERROR: ASTが構築されていません。先にparse_fileを実行してください。"
120
+ )
121
+ return []
122
+
123
+ try:
124
+ query = self.language.query(query_string)
125
+ except Exception as e:
126
+ output_error(
127
+ f"ERROR: クエリのコンパイルに失敗しました。\nクエリ: {query_string}\nエラー: {e}"
128
+ )
129
+ return []
130
+
131
+ try:
132
+ captures = query.captures(self.tree.root_node)
133
+ except Exception as e:
134
+ output_error(f"ERROR: クエリの実行に失敗しました: {e}")
135
+ return []
136
+
137
+ results = []
138
+
139
+ # Tree-sitter 0.24以降の辞書形式に対応
140
+ try:
141
+ # 辞書形式: {capture_name: [nodes...]}
142
+ for capture_name, nodes in captures.items():
143
+ if isinstance(nodes, list):
144
+ for node in nodes:
145
+ try:
146
+ start_line = node.start_point[0] + 1
147
+ end_line = node.end_point[0] + 1
148
+ node_text = self.source_code_bytes[
149
+ node.start_byte : node.end_byte
150
+ ].decode("utf-8", errors="ignore")
151
+
152
+ results.append(
153
+ {
154
+ "capture_name": capture_name,
155
+ "content": node_text,
156
+ "start_line": start_line,
157
+ "end_line": end_line,
158
+ "node_type": node.type,
159
+ }
160
+ )
161
+ except Exception as e:
162
+ output_warning(
163
+ f"WARNING: ノード処理中にエラーが発生しました: {e}"
164
+ )
165
+ continue
166
+
167
+ except Exception as e:
168
+ output_error(f"ERROR: capture処理中に予期しないエラーが発生しました: {e}")
169
+ return []
170
+
171
+ return results
172
+
173
+
174
+ def main() -> None:
175
+ """
176
+ モジュールが直接実行された場合のエントリーポイント。
177
+ 通常はcli.pyを使用することを推奨。
178
+ """
179
+ output_warning("注意: 直接的なモジュール実行は非推奨です。")
180
+ output_warning("代わりに以下を使用してください:")
181
+ output_info(" uv run java-analyzer <file> --query-key <key>")
182
+ output_info(" または")
183
+ output_info(" python -m tree_sitter_analyzer.cli <file> --query-key <key>")
184
+
185
+
186
+ if __name__ == "__main__":
187
+ main()