tree-sitter-analyzer 0.1.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 +121 -0
  2. tree_sitter_analyzer/__main__.py +12 -0
  3. tree_sitter_analyzer/api.py +539 -0
  4. tree_sitter_analyzer/cli/__init__.py +39 -0
  5. tree_sitter_analyzer/cli/__main__.py +13 -0
  6. tree_sitter_analyzer/cli/commands/__init__.py +27 -0
  7. tree_sitter_analyzer/cli/commands/advanced_command.py +88 -0
  8. tree_sitter_analyzer/cli/commands/base_command.py +155 -0
  9. tree_sitter_analyzer/cli/commands/default_command.py +19 -0
  10. tree_sitter_analyzer/cli/commands/partial_read_command.py +133 -0
  11. tree_sitter_analyzer/cli/commands/query_command.py +82 -0
  12. tree_sitter_analyzer/cli/commands/structure_command.py +121 -0
  13. tree_sitter_analyzer/cli/commands/summary_command.py +93 -0
  14. tree_sitter_analyzer/cli/commands/table_command.py +233 -0
  15. tree_sitter_analyzer/cli/info_commands.py +121 -0
  16. tree_sitter_analyzer/cli_main.py +276 -0
  17. tree_sitter_analyzer/core/__init__.py +20 -0
  18. tree_sitter_analyzer/core/analysis_engine.py +574 -0
  19. tree_sitter_analyzer/core/cache_service.py +330 -0
  20. tree_sitter_analyzer/core/engine.py +560 -0
  21. tree_sitter_analyzer/core/parser.py +288 -0
  22. tree_sitter_analyzer/core/query.py +502 -0
  23. tree_sitter_analyzer/encoding_utils.py +460 -0
  24. tree_sitter_analyzer/exceptions.py +340 -0
  25. tree_sitter_analyzer/file_handler.py +222 -0
  26. tree_sitter_analyzer/formatters/__init__.py +1 -0
  27. tree_sitter_analyzer/formatters/base_formatter.py +168 -0
  28. tree_sitter_analyzer/formatters/formatter_factory.py +74 -0
  29. tree_sitter_analyzer/formatters/java_formatter.py +270 -0
  30. tree_sitter_analyzer/formatters/python_formatter.py +235 -0
  31. tree_sitter_analyzer/interfaces/__init__.py +10 -0
  32. tree_sitter_analyzer/interfaces/cli.py +557 -0
  33. tree_sitter_analyzer/interfaces/cli_adapter.py +319 -0
  34. tree_sitter_analyzer/interfaces/mcp_adapter.py +170 -0
  35. tree_sitter_analyzer/interfaces/mcp_server.py +416 -0
  36. tree_sitter_analyzer/java_analyzer.py +219 -0
  37. tree_sitter_analyzer/language_detector.py +400 -0
  38. tree_sitter_analyzer/language_loader.py +228 -0
  39. tree_sitter_analyzer/languages/__init__.py +11 -0
  40. tree_sitter_analyzer/languages/java_plugin.py +1113 -0
  41. tree_sitter_analyzer/languages/python_plugin.py +712 -0
  42. tree_sitter_analyzer/mcp/__init__.py +32 -0
  43. tree_sitter_analyzer/mcp/resources/__init__.py +47 -0
  44. tree_sitter_analyzer/mcp/resources/code_file_resource.py +213 -0
  45. tree_sitter_analyzer/mcp/resources/project_stats_resource.py +550 -0
  46. tree_sitter_analyzer/mcp/server.py +319 -0
  47. tree_sitter_analyzer/mcp/tools/__init__.py +36 -0
  48. tree_sitter_analyzer/mcp/tools/analyze_scale_tool.py +558 -0
  49. tree_sitter_analyzer/mcp/tools/analyze_scale_tool_cli_compatible.py +245 -0
  50. tree_sitter_analyzer/mcp/tools/base_tool.py +55 -0
  51. tree_sitter_analyzer/mcp/tools/get_positions_tool.py +448 -0
  52. tree_sitter_analyzer/mcp/tools/read_partial_tool.py +302 -0
  53. tree_sitter_analyzer/mcp/tools/table_format_tool.py +359 -0
  54. tree_sitter_analyzer/mcp/tools/universal_analyze_tool.py +476 -0
  55. tree_sitter_analyzer/mcp/utils/__init__.py +106 -0
  56. tree_sitter_analyzer/mcp/utils/error_handler.py +549 -0
  57. tree_sitter_analyzer/models.py +481 -0
  58. tree_sitter_analyzer/output_manager.py +264 -0
  59. tree_sitter_analyzer/plugins/__init__.py +334 -0
  60. tree_sitter_analyzer/plugins/base.py +446 -0
  61. tree_sitter_analyzer/plugins/java_plugin.py +625 -0
  62. tree_sitter_analyzer/plugins/javascript_plugin.py +439 -0
  63. tree_sitter_analyzer/plugins/manager.py +355 -0
  64. tree_sitter_analyzer/plugins/plugin_loader.py +83 -0
  65. tree_sitter_analyzer/plugins/python_plugin.py +598 -0
  66. tree_sitter_analyzer/plugins/registry.py +366 -0
  67. tree_sitter_analyzer/queries/__init__.py +27 -0
  68. tree_sitter_analyzer/queries/java.py +394 -0
  69. tree_sitter_analyzer/queries/javascript.py +149 -0
  70. tree_sitter_analyzer/queries/python.py +286 -0
  71. tree_sitter_analyzer/queries/typescript.py +230 -0
  72. tree_sitter_analyzer/query_loader.py +260 -0
  73. tree_sitter_analyzer/table_formatter.py +448 -0
  74. tree_sitter_analyzer/utils.py +201 -0
  75. tree_sitter_analyzer-0.1.0.dist-info/METADATA +581 -0
  76. tree_sitter_analyzer-0.1.0.dist-info/RECORD +78 -0
  77. tree_sitter_analyzer-0.1.0.dist-info/WHEEL +4 -0
  78. tree_sitter_analyzer-0.1.0.dist-info/entry_points.txt +8 -0
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ CLI Adapter for tree-sitter-analyzer
4
+
5
+ 既存のCLI APIとの互換性を保ちながら、新しい統一解析エンジンを使用するアダプター。
6
+
7
+ Roo Code規約準拠:
8
+ - 型ヒント: 全関数に型ヒント必須
9
+ - MCPログ: 各ステップでログ出力
10
+ - docstring: Google Style docstring
11
+ - エラーハンドリング: 適切な例外処理
12
+ - パフォーマンス: 統一エンジンによる最適化
13
+ """
14
+
15
+ import asyncio
16
+ import logging
17
+ import time
18
+ from typing import Dict, Any, Optional, Union
19
+ from pathlib import Path
20
+
21
+ from ..core.analysis_engine import UnifiedAnalysisEngine, AnalysisRequest
22
+ from ..models import AnalysisResult
23
+
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class CLIAdapter:
29
+ """
30
+ CLI用アダプター
31
+
32
+ 既存のCLI APIとの互換性を保ちながら、新しい統一解析エンジンを使用します。
33
+ 同期APIを提供し、内部的に非同期エンジンを呼び出します。
34
+
35
+ Features:
36
+ - 既存API互換性の維持
37
+ - 統一解析エンジンの活用
38
+ - 同期/非同期変換
39
+ - パフォーマンス監視
40
+ - エラーハンドリング
41
+
42
+ Example:
43
+ >>> adapter = CLIAdapter()
44
+ >>> result = adapter.analyze_file("example.java")
45
+ >>> print(result.classes)
46
+ """
47
+
48
+ def __init__(self) -> None:
49
+ """
50
+ CLIアダプターを初期化
51
+
52
+ Raises:
53
+ Exception: 統一解析エンジンの初期化に失敗した場合
54
+ """
55
+ try:
56
+ self._engine = UnifiedAnalysisEngine()
57
+ logger.info("CLIAdapter initialized successfully")
58
+ except Exception as e:
59
+ logger.error(f"Failed to initialize CLIAdapter: {e}")
60
+ raise
61
+
62
+ def analyze_file(self, file_path: str, **kwargs: Any) -> AnalysisResult:
63
+ """
64
+ ファイルを解析(同期版)
65
+
66
+ 既存のCLI APIとの互換性を保つため、同期インターフェースを提供します。
67
+ 内部的には統一解析エンジンの非同期メソッドを呼び出します。
68
+
69
+ Args:
70
+ file_path: 解析対象ファイルのパス
71
+ **kwargs: 解析オプション
72
+ - language: 言語指定(自動検出も可能)
73
+ - include_complexity: 複雑度計算を含める
74
+ - include_details: 詳細情報を含める
75
+ - format_type: 出力形式("standard", "structure", "summary")
76
+
77
+ Returns:
78
+ AnalysisResult: 解析結果
79
+
80
+ Raises:
81
+ ValueError: 無効なファイルパスの場合
82
+ FileNotFoundError: ファイルが存在しない場合
83
+ UnsupportedLanguageError: サポートされていない言語の場合
84
+
85
+ Example:
86
+ >>> adapter = CLIAdapter()
87
+ >>> result = adapter.analyze_file("example.java", include_complexity=True)
88
+ >>> print(f"Classes: {len(result.classes)}")
89
+ """
90
+ start_time = time.time()
91
+
92
+ # 入力検証
93
+ if not file_path or not file_path.strip():
94
+ raise ValueError("File path cannot be empty")
95
+
96
+ # ファイル存在チェック
97
+ if not Path(file_path).exists():
98
+ raise FileNotFoundError(f"File not found: {file_path}")
99
+
100
+ try:
101
+ # AnalysisRequestを作成
102
+ request = AnalysisRequest(
103
+ file_path=file_path,
104
+ language=kwargs.get('language'),
105
+ include_complexity=kwargs.get('include_complexity', False),
106
+ include_details=kwargs.get('include_details', True),
107
+ format_type=kwargs.get('format_type', 'standard')
108
+ )
109
+
110
+ # 非同期エンジンを同期的に実行
111
+ result = asyncio.run(self._engine.analyze(request))
112
+
113
+ # パフォーマンスログ
114
+ elapsed_time = time.time() - start_time
115
+ logger.info(f"CLI analysis completed: {file_path} in {elapsed_time:.3f}s")
116
+
117
+ return result
118
+
119
+ except Exception as e:
120
+ logger.error(f"CLI analysis failed for {file_path}: {e}")
121
+ raise
122
+
123
+ def analyze_structure(self, file_path: str, **kwargs: Any) -> Dict[str, Any]:
124
+ """
125
+ 構造解析(既存API互換)
126
+
127
+ 既存のCLI APIとの互換性を保つため、構造情報を辞書形式で返します。
128
+
129
+ Args:
130
+ file_path: 解析対象ファイルのパス
131
+ **kwargs: 解析オプション
132
+
133
+ Returns:
134
+ Dict[str, Any]: 構造情報の辞書
135
+ - file_path: ファイルパス
136
+ - classes: クラス情報のリスト
137
+ - methods: メソッド情報のリスト
138
+ - fields: フィールド情報のリスト
139
+ - imports: インポート情報のリスト
140
+
141
+ Example:
142
+ >>> adapter = CLIAdapter()
143
+ >>> structure = adapter.analyze_structure("example.java")
144
+ >>> print(structure["classes"])
145
+ """
146
+ # 詳細情報を含めて解析
147
+ kwargs['include_details'] = True
148
+ kwargs['format_type'] = 'structure'
149
+
150
+ result = self.analyze_file(file_path, **kwargs)
151
+
152
+ # 構造情報を辞書形式に変換
153
+ return {
154
+ 'file_path': result.file_path,
155
+ 'language': result.language,
156
+ 'package': result.package,
157
+ 'imports': [imp.to_dict() for imp in result.imports],
158
+ 'classes': [cls.to_dict() for cls in result.classes],
159
+ 'methods': [method.to_dict() for method in result.methods],
160
+ 'fields': [field.to_dict() for field in result.fields],
161
+ 'annotations': [ann.to_dict() for ann in result.annotations],
162
+ 'analysis_time': result.analysis_time,
163
+ 'elements': [elem.to_dict() for elem in result.elements],
164
+ 'success': result.success
165
+ }
166
+
167
+ def analyze_batch(self, file_paths: list[str], **kwargs: Any) -> list[AnalysisResult]:
168
+ """
169
+ 複数ファイルの一括解析
170
+
171
+ Args:
172
+ file_paths: 解析対象ファイルパスのリスト
173
+ **kwargs: 解析オプション
174
+
175
+ Returns:
176
+ list[AnalysisResult]: 解析結果のリスト
177
+
178
+ Example:
179
+ >>> adapter = CLIAdapter()
180
+ >>> results = adapter.analyze_batch(["file1.java", "file2.java"])
181
+ >>> print(f"Analyzed {len(results)} files")
182
+ """
183
+ results = []
184
+
185
+ for file_path in file_paths:
186
+ try:
187
+ result = self.analyze_file(file_path, **kwargs)
188
+ results.append(result)
189
+ except Exception as e:
190
+ logger.warning(f"Failed to analyze {file_path}: {e}")
191
+ # エラーの場合も結果に含める(失敗情報付き)
192
+ error_result = AnalysisResult(
193
+ file_path=file_path,
194
+ package=None,
195
+ imports=[],
196
+ classes=[],
197
+ methods=[],
198
+ fields=[],
199
+ annotations=[],
200
+ analysis_time=0.0,
201
+ success=False,
202
+ error_message=str(e)
203
+ )
204
+ results.append(error_result)
205
+
206
+ return results
207
+
208
+ def get_supported_languages(self) -> list[str]:
209
+ """
210
+ サポートされている言語のリストを取得
211
+
212
+ Returns:
213
+ list[str]: サポート言語のリスト
214
+
215
+ Example:
216
+ >>> adapter = CLIAdapter()
217
+ >>> languages = adapter.get_supported_languages()
218
+ >>> print(languages)
219
+ """
220
+ return self._engine.get_supported_languages()
221
+
222
+ def clear_cache(self) -> None:
223
+ """
224
+ キャッシュをクリア
225
+
226
+ Example:
227
+ >>> adapter = CLIAdapter()
228
+ >>> adapter.clear_cache()
229
+ """
230
+ self._engine.clear_cache()
231
+ logger.info("CLI adapter cache cleared")
232
+
233
+ def get_cache_stats(self) -> Dict[str, Any]:
234
+ """
235
+ キャッシュ統計情報を取得
236
+
237
+ Returns:
238
+ Dict[str, Any]: キャッシュ統計情報
239
+
240
+ Example:
241
+ >>> adapter = CLIAdapter()
242
+ >>> stats = adapter.get_cache_stats()
243
+ >>> print(f"Cache hit rate: {stats['hit_rate']:.2%}")
244
+ """
245
+ return self._engine.get_cache_stats()
246
+
247
+ def validate_file(self, file_path: str) -> bool:
248
+ """
249
+ ファイルが解析可能かどうかを検証
250
+
251
+ Args:
252
+ file_path: 検証対象ファイルのパス
253
+
254
+ Returns:
255
+ bool: 解析可能な場合True
256
+
257
+ Example:
258
+ >>> adapter = CLIAdapter()
259
+ >>> if adapter.validate_file("example.java"):
260
+ ... result = adapter.analyze_file("example.java")
261
+ """
262
+ try:
263
+ # ファイル存在チェック
264
+ if not Path(file_path).exists():
265
+ return False
266
+
267
+ # 言語サポートチェック
268
+ supported_languages = self.get_supported_languages()
269
+ file_extension = Path(file_path).suffix.lower()
270
+
271
+ # 拡張子から言語を推定
272
+ extension_map = {
273
+ '.java': 'java',
274
+ '.py': 'python',
275
+ '.js': 'javascript',
276
+ '.ts': 'typescript',
277
+ '.cpp': 'cpp',
278
+ '.c': 'c',
279
+ '.cs': 'csharp',
280
+ '.go': 'go',
281
+ '.rs': 'rust',
282
+ '.php': 'php',
283
+ '.rb': 'ruby'
284
+ }
285
+
286
+ language = extension_map.get(file_extension)
287
+ return language in supported_languages if language else False
288
+
289
+ except Exception as e:
290
+ logger.warning(f"File validation failed for {file_path}: {e}")
291
+ return False
292
+
293
+ def get_engine_info(self) -> Dict[str, Any]:
294
+ """
295
+ エンジン情報を取得
296
+
297
+ Returns:
298
+ Dict[str, Any]: エンジン情報
299
+
300
+ Example:
301
+ >>> adapter = CLIAdapter()
302
+ >>> info = adapter.get_engine_info()
303
+ >>> print(f"Engine version: {info['version']}")
304
+ """
305
+ return {
306
+ 'adapter_type': 'CLI',
307
+ 'engine_type': 'UnifiedAnalysisEngine',
308
+ 'supported_languages': self.get_supported_languages(),
309
+ 'cache_enabled': True,
310
+ 'async_support': True
311
+ }
312
+
313
+
314
+ # Legacy AdvancedAnalyzerAdapter removed - use UnifiedAnalysisEngine directly
315
+
316
+ def get_analysis_engine():
317
+ """Get analysis engine instance for testing compatibility."""
318
+ from ..core.analysis_engine import AnalysisEngine
319
+ return AnalysisEngine()
@@ -0,0 +1,170 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ MCP Adapter for Tree-Sitter Analyzer
4
+
5
+ This module provides an adapter interface for integrating with the MCP protocol.
6
+ """
7
+
8
+ from typing import Dict, Any, List
9
+ from ..models import AnalysisResult
10
+
11
+
12
+ def get_analysis_engine():
13
+ """Get analysis engine instance for testing compatibility."""
14
+ from ..core.analysis_engine import AnalysisEngine
15
+ return AnalysisEngine()
16
+
17
+
18
+ def handle_mcp_resource_request(uri):
19
+ """Handle MCP resource request for testing compatibility."""
20
+ return {'contents': [{'mimeType': 'application/json', 'text': {'mock': 'resource'}, 'uri': uri}]}
21
+
22
+
23
+ def read_file_safe(file_path: str) -> str:
24
+ """Read file safely for MCP resource requests."""
25
+ try:
26
+ with open(file_path, 'r', encoding='utf-8') as f:
27
+ return f.read()
28
+ except Exception as e:
29
+ raise FileNotFoundError(f"Could not read file {file_path}: {e}")
30
+
31
+
32
+ class MCPAdapter:
33
+ """MCP Adapter for testing compatibility."""
34
+
35
+ def __init__(self):
36
+ """Initialize MCP Adapter."""
37
+ from ..core.analysis_engine import UnifiedAnalysisEngine
38
+ self.engine = UnifiedAnalysisEngine()
39
+
40
+ async def analyze_file_async(self, file_path: str, **kwargs) -> 'AnalysisResult':
41
+ """Analyze file asynchronously."""
42
+ from ..core.analysis_engine import AnalysisRequest
43
+ request = AnalysisRequest(
44
+ file_path=file_path,
45
+ language=kwargs.get('language'),
46
+ include_complexity=kwargs.get('include_complexity', False),
47
+ include_details=kwargs.get('include_details', True),
48
+ format_type=kwargs.get('format_type', 'standard')
49
+ )
50
+ return await self.engine.analyze(request)
51
+
52
+ async def get_file_structure_async(self, file_path: str, **kwargs) -> Dict[str, Any]:
53
+ """Get file structure asynchronously."""
54
+ result = await self.analyze_file_async(file_path, **kwargs)
55
+ return {
56
+ 'file_path': result.file_path,
57
+ 'language': result.language,
58
+ 'structure': {
59
+ 'classes': [cls.to_dict() for cls in result.classes],
60
+ 'methods': [method.to_dict() for method in result.methods],
61
+ 'fields': [field.to_dict() for field in result.fields],
62
+ 'imports': [imp.to_dict() for imp in result.imports],
63
+ 'annotations': [ann.to_dict() for ann in result.annotations]
64
+ },
65
+ 'metadata': {
66
+ 'analysis_time': result.analysis_time,
67
+ 'success': result.success,
68
+ 'error_message': result.error_message,
69
+ 'package': result.package,
70
+ 'class_count': len(result.classes),
71
+ 'method_count': len(result.methods),
72
+ 'field_count': len(result.fields),
73
+ 'import_count': len(result.imports),
74
+ 'annotation_count': len(result.annotations)
75
+ }
76
+ }
77
+
78
+ async def analyze_batch_async(self, file_paths: List[str], **kwargs) -> List['AnalysisResult']:
79
+ """Analyze multiple files asynchronously."""
80
+ results = []
81
+ for file_path in file_paths:
82
+ try:
83
+ result = await self.analyze_file_async(file_path, **kwargs)
84
+ results.append(result)
85
+ except Exception as e:
86
+ # Create error result
87
+ from ..models import AnalysisResult
88
+ error_result = AnalysisResult(
89
+ file_path=file_path,
90
+ language="unknown",
91
+ line_count=0,
92
+ elements=[],
93
+ node_count=0,
94
+ query_results={},
95
+ source_code="",
96
+ package=None,
97
+ imports=[],
98
+ classes=[],
99
+ methods=[],
100
+ fields=[],
101
+ annotations=[],
102
+ analysis_time=0.0,
103
+ success=False,
104
+ error_message=str(e)
105
+ )
106
+ results.append(error_result)
107
+ return results
108
+
109
+ async def handle_mcp_tool_request(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
110
+ """Handle MCP tool request."""
111
+ if tool_name == "analyze_file":
112
+ file_path = arguments.get("file_path")
113
+ if not file_path:
114
+ return {"error": "file_path is required"}
115
+
116
+ try:
117
+ result = await self.analyze_file_async(file_path)
118
+ return {
119
+ "success": True,
120
+ "result": result.to_dict()
121
+ }
122
+ except Exception as e:
123
+ return {"error": str(e)}
124
+
125
+ return {"error": f"Unknown tool: {tool_name}"}
126
+
127
+ async def handle_mcp_resource_request(self, uri: str) -> Dict[str, Any]:
128
+ """Handle MCP resource request."""
129
+ if uri.startswith("code://"):
130
+ # Extract file path from URI
131
+ file_path = uri.replace("code://", "")
132
+ try:
133
+ content = read_file_safe(file_path)
134
+ return {
135
+ "uri": uri,
136
+ "content": content,
137
+ "mimeType": "text/plain"
138
+ }
139
+ except Exception as e:
140
+ return {"error": str(e)}
141
+
142
+ return {"error": f"Unsupported URI: {uri}"}
143
+
144
+ def cleanup(self) -> None:
145
+ """Cleanup resources."""
146
+ pass
147
+
148
+ async def aclose(self) -> None:
149
+ """Async cleanup."""
150
+ pass
151
+
152
+ def analyze_with_mcp_request(self, arguments):
153
+ """Analyze with MCP request."""
154
+ if 'file_path' not in arguments:
155
+ raise KeyError('file_path is required in MCP request')
156
+ return self.analyze_file_async(arguments['file_path'])
157
+
158
+
159
+ class MCPServerAdapter:
160
+ """MCP Server Adapter for testing compatibility."""
161
+
162
+ def __init__(self):
163
+ """Initialize MCP Server Adapter."""
164
+ self.mcp_adapter = MCPAdapter()
165
+
166
+ async def handle_request(self, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
167
+ """Handle MCP request."""
168
+ if not params:
169
+ return {"error": "params are required"}
170
+ return await self.mcp_adapter.handle_mcp_tool_request(method, params)