jarvis-ai-assistant 0.3.30__py3-none-any.whl → 0.7.6__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.
Files changed (181) hide show
  1. jarvis/__init__.py +1 -1
  2. jarvis/jarvis_agent/__init__.py +458 -152
  3. jarvis/jarvis_agent/agent_manager.py +17 -13
  4. jarvis/jarvis_agent/builtin_input_handler.py +2 -6
  5. jarvis/jarvis_agent/config_editor.py +2 -7
  6. jarvis/jarvis_agent/event_bus.py +82 -12
  7. jarvis/jarvis_agent/file_context_handler.py +329 -0
  8. jarvis/jarvis_agent/file_methodology_manager.py +3 -4
  9. jarvis/jarvis_agent/jarvis.py +628 -55
  10. jarvis/jarvis_agent/language_extractors/__init__.py +57 -0
  11. jarvis/jarvis_agent/language_extractors/c_extractor.py +21 -0
  12. jarvis/jarvis_agent/language_extractors/cpp_extractor.py +21 -0
  13. jarvis/jarvis_agent/language_extractors/go_extractor.py +21 -0
  14. jarvis/jarvis_agent/language_extractors/java_extractor.py +84 -0
  15. jarvis/jarvis_agent/language_extractors/javascript_extractor.py +79 -0
  16. jarvis/jarvis_agent/language_extractors/python_extractor.py +21 -0
  17. jarvis/jarvis_agent/language_extractors/rust_extractor.py +21 -0
  18. jarvis/jarvis_agent/language_extractors/typescript_extractor.py +84 -0
  19. jarvis/jarvis_agent/language_support_info.py +486 -0
  20. jarvis/jarvis_agent/main.py +34 -10
  21. jarvis/jarvis_agent/memory_manager.py +7 -16
  22. jarvis/jarvis_agent/methodology_share_manager.py +10 -16
  23. jarvis/jarvis_agent/prompt_manager.py +1 -1
  24. jarvis/jarvis_agent/prompts.py +193 -171
  25. jarvis/jarvis_agent/protocols.py +8 -12
  26. jarvis/jarvis_agent/run_loop.py +105 -9
  27. jarvis/jarvis_agent/session_manager.py +2 -3
  28. jarvis/jarvis_agent/share_manager.py +20 -22
  29. jarvis/jarvis_agent/shell_input_handler.py +1 -2
  30. jarvis/jarvis_agent/stdio_redirect.py +295 -0
  31. jarvis/jarvis_agent/task_analyzer.py +31 -6
  32. jarvis/jarvis_agent/task_manager.py +11 -27
  33. jarvis/jarvis_agent/tool_executor.py +2 -3
  34. jarvis/jarvis_agent/tool_share_manager.py +12 -24
  35. jarvis/jarvis_agent/utils.py +5 -1
  36. jarvis/jarvis_agent/web_bridge.py +189 -0
  37. jarvis/jarvis_agent/web_output_sink.py +53 -0
  38. jarvis/jarvis_agent/web_server.py +786 -0
  39. jarvis/jarvis_c2rust/__init__.py +26 -0
  40. jarvis/jarvis_c2rust/cli.py +575 -0
  41. jarvis/jarvis_c2rust/collector.py +250 -0
  42. jarvis/jarvis_c2rust/constants.py +26 -0
  43. jarvis/jarvis_c2rust/library_replacer.py +1254 -0
  44. jarvis/jarvis_c2rust/llm_module_agent.py +1272 -0
  45. jarvis/jarvis_c2rust/loaders.py +207 -0
  46. jarvis/jarvis_c2rust/models.py +28 -0
  47. jarvis/jarvis_c2rust/optimizer.py +2157 -0
  48. jarvis/jarvis_c2rust/scanner.py +1681 -0
  49. jarvis/jarvis_c2rust/transpiler.py +2983 -0
  50. jarvis/jarvis_c2rust/utils.py +385 -0
  51. jarvis/jarvis_code_agent/build_validation_config.py +132 -0
  52. jarvis/jarvis_code_agent/code_agent.py +1371 -220
  53. jarvis/jarvis_code_agent/code_analyzer/__init__.py +65 -0
  54. jarvis/jarvis_code_agent/code_analyzer/base_language.py +74 -0
  55. jarvis/jarvis_code_agent/code_analyzer/build_validator/__init__.py +44 -0
  56. jarvis/jarvis_code_agent/code_analyzer/build_validator/base.py +106 -0
  57. jarvis/jarvis_code_agent/code_analyzer/build_validator/cmake.py +74 -0
  58. jarvis/jarvis_code_agent/code_analyzer/build_validator/detector.py +125 -0
  59. jarvis/jarvis_code_agent/code_analyzer/build_validator/fallback.py +72 -0
  60. jarvis/jarvis_code_agent/code_analyzer/build_validator/go.py +70 -0
  61. jarvis/jarvis_code_agent/code_analyzer/build_validator/java_gradle.py +53 -0
  62. jarvis/jarvis_code_agent/code_analyzer/build_validator/java_maven.py +47 -0
  63. jarvis/jarvis_code_agent/code_analyzer/build_validator/makefile.py +61 -0
  64. jarvis/jarvis_code_agent/code_analyzer/build_validator/nodejs.py +110 -0
  65. jarvis/jarvis_code_agent/code_analyzer/build_validator/python.py +154 -0
  66. jarvis/jarvis_code_agent/code_analyzer/build_validator/rust.py +110 -0
  67. jarvis/jarvis_code_agent/code_analyzer/build_validator/validator.py +153 -0
  68. jarvis/jarvis_code_agent/code_analyzer/build_validator.py +43 -0
  69. jarvis/jarvis_code_agent/code_analyzer/context_manager.py +648 -0
  70. jarvis/jarvis_code_agent/code_analyzer/context_recommender.py +18 -0
  71. jarvis/jarvis_code_agent/code_analyzer/dependency_analyzer.py +132 -0
  72. jarvis/jarvis_code_agent/code_analyzer/file_ignore.py +330 -0
  73. jarvis/jarvis_code_agent/code_analyzer/impact_analyzer.py +781 -0
  74. jarvis/jarvis_code_agent/code_analyzer/language_registry.py +185 -0
  75. jarvis/jarvis_code_agent/code_analyzer/language_support.py +110 -0
  76. jarvis/jarvis_code_agent/code_analyzer/languages/__init__.py +49 -0
  77. jarvis/jarvis_code_agent/code_analyzer/languages/c_cpp_language.py +299 -0
  78. jarvis/jarvis_code_agent/code_analyzer/languages/go_language.py +215 -0
  79. jarvis/jarvis_code_agent/code_analyzer/languages/java_language.py +212 -0
  80. jarvis/jarvis_code_agent/code_analyzer/languages/javascript_language.py +254 -0
  81. jarvis/jarvis_code_agent/code_analyzer/languages/python_language.py +269 -0
  82. jarvis/jarvis_code_agent/code_analyzer/languages/rust_language.py +281 -0
  83. jarvis/jarvis_code_agent/code_analyzer/languages/typescript_language.py +280 -0
  84. jarvis/jarvis_code_agent/code_analyzer/llm_context_recommender.py +605 -0
  85. jarvis/jarvis_code_agent/code_analyzer/structured_code.py +556 -0
  86. jarvis/jarvis_code_agent/code_analyzer/symbol_extractor.py +252 -0
  87. jarvis/jarvis_code_agent/code_analyzer/tree_sitter_extractor.py +58 -0
  88. jarvis/jarvis_code_agent/lint.py +501 -8
  89. jarvis/jarvis_code_agent/utils.py +141 -0
  90. jarvis/jarvis_code_analysis/code_review.py +493 -584
  91. jarvis/jarvis_data/config_schema.json +128 -12
  92. jarvis/jarvis_git_squash/main.py +4 -5
  93. jarvis/jarvis_git_utils/git_commiter.py +82 -75
  94. jarvis/jarvis_mcp/sse_mcp_client.py +22 -29
  95. jarvis/jarvis_mcp/stdio_mcp_client.py +12 -13
  96. jarvis/jarvis_mcp/streamable_mcp_client.py +15 -14
  97. jarvis/jarvis_memory_organizer/memory_organizer.py +55 -74
  98. jarvis/jarvis_methodology/main.py +32 -48
  99. jarvis/jarvis_multi_agent/__init__.py +287 -55
  100. jarvis/jarvis_multi_agent/main.py +36 -4
  101. jarvis/jarvis_platform/base.py +524 -202
  102. jarvis/jarvis_platform/human.py +7 -8
  103. jarvis/jarvis_platform/kimi.py +30 -36
  104. jarvis/jarvis_platform/openai.py +88 -25
  105. jarvis/jarvis_platform/registry.py +26 -10
  106. jarvis/jarvis_platform/tongyi.py +24 -25
  107. jarvis/jarvis_platform/yuanbao.py +32 -43
  108. jarvis/jarvis_platform_manager/main.py +66 -77
  109. jarvis/jarvis_platform_manager/service.py +8 -13
  110. jarvis/jarvis_rag/cli.py +53 -55
  111. jarvis/jarvis_rag/embedding_manager.py +13 -18
  112. jarvis/jarvis_rag/llm_interface.py +8 -9
  113. jarvis/jarvis_rag/query_rewriter.py +10 -21
  114. jarvis/jarvis_rag/rag_pipeline.py +24 -27
  115. jarvis/jarvis_rag/reranker.py +4 -5
  116. jarvis/jarvis_rag/retriever.py +28 -30
  117. jarvis/jarvis_sec/__init__.py +305 -0
  118. jarvis/jarvis_sec/agents.py +143 -0
  119. jarvis/jarvis_sec/analysis.py +276 -0
  120. jarvis/jarvis_sec/checkers/__init__.py +32 -0
  121. jarvis/jarvis_sec/checkers/c_checker.py +2680 -0
  122. jarvis/jarvis_sec/checkers/rust_checker.py +1108 -0
  123. jarvis/jarvis_sec/cli.py +139 -0
  124. jarvis/jarvis_sec/clustering.py +1439 -0
  125. jarvis/jarvis_sec/file_manager.py +427 -0
  126. jarvis/jarvis_sec/parsers.py +73 -0
  127. jarvis/jarvis_sec/prompts.py +268 -0
  128. jarvis/jarvis_sec/report.py +336 -0
  129. jarvis/jarvis_sec/review.py +453 -0
  130. jarvis/jarvis_sec/status.py +264 -0
  131. jarvis/jarvis_sec/types.py +20 -0
  132. jarvis/jarvis_sec/utils.py +499 -0
  133. jarvis/jarvis_sec/verification.py +848 -0
  134. jarvis/jarvis_sec/workflow.py +226 -0
  135. jarvis/jarvis_smart_shell/main.py +38 -87
  136. jarvis/jarvis_stats/cli.py +2 -2
  137. jarvis/jarvis_stats/stats.py +8 -8
  138. jarvis/jarvis_stats/storage.py +15 -21
  139. jarvis/jarvis_stats/visualizer.py +1 -1
  140. jarvis/jarvis_tools/clear_memory.py +3 -20
  141. jarvis/jarvis_tools/cli/main.py +21 -23
  142. jarvis/jarvis_tools/edit_file.py +1019 -132
  143. jarvis/jarvis_tools/execute_script.py +83 -25
  144. jarvis/jarvis_tools/file_analyzer.py +6 -9
  145. jarvis/jarvis_tools/generate_new_tool.py +14 -21
  146. jarvis/jarvis_tools/lsp_client.py +1552 -0
  147. jarvis/jarvis_tools/methodology.py +2 -3
  148. jarvis/jarvis_tools/read_code.py +1736 -35
  149. jarvis/jarvis_tools/read_symbols.py +140 -0
  150. jarvis/jarvis_tools/read_webpage.py +12 -13
  151. jarvis/jarvis_tools/registry.py +427 -200
  152. jarvis/jarvis_tools/retrieve_memory.py +20 -19
  153. jarvis/jarvis_tools/rewrite_file.py +72 -158
  154. jarvis/jarvis_tools/save_memory.py +3 -15
  155. jarvis/jarvis_tools/search_web.py +18 -18
  156. jarvis/jarvis_tools/sub_agent.py +36 -43
  157. jarvis/jarvis_tools/sub_code_agent.py +25 -26
  158. jarvis/jarvis_tools/virtual_tty.py +55 -33
  159. jarvis/jarvis_utils/clipboard.py +7 -10
  160. jarvis/jarvis_utils/config.py +232 -45
  161. jarvis/jarvis_utils/embedding.py +8 -5
  162. jarvis/jarvis_utils/fzf.py +8 -8
  163. jarvis/jarvis_utils/git_utils.py +225 -36
  164. jarvis/jarvis_utils/globals.py +3 -3
  165. jarvis/jarvis_utils/http.py +1 -1
  166. jarvis/jarvis_utils/input.py +99 -48
  167. jarvis/jarvis_utils/jsonnet_compat.py +465 -0
  168. jarvis/jarvis_utils/methodology.py +52 -48
  169. jarvis/jarvis_utils/utils.py +819 -491
  170. jarvis_ai_assistant-0.7.6.dist-info/METADATA +600 -0
  171. jarvis_ai_assistant-0.7.6.dist-info/RECORD +218 -0
  172. {jarvis_ai_assistant-0.3.30.dist-info → jarvis_ai_assistant-0.7.6.dist-info}/entry_points.txt +4 -0
  173. jarvis/jarvis_agent/config.py +0 -92
  174. jarvis/jarvis_agent/edit_file_handler.py +0 -296
  175. jarvis/jarvis_platform/ai8.py +0 -332
  176. jarvis/jarvis_tools/ask_user.py +0 -54
  177. jarvis_ai_assistant-0.3.30.dist-info/METADATA +0 -381
  178. jarvis_ai_assistant-0.3.30.dist-info/RECORD +0 -137
  179. {jarvis_ai_assistant-0.3.30.dist-info → jarvis_ai_assistant-0.7.6.dist-info}/WHEEL +0 -0
  180. {jarvis_ai_assistant-0.3.30.dist-info → jarvis_ai_assistant-0.7.6.dist-info}/licenses/LICENSE +0 -0
  181. {jarvis_ai_assistant-0.3.30.dist-info → jarvis_ai_assistant-0.7.6.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,65 @@
1
+ """Jarvis代码分析器模块。
2
+
3
+ 提供符号提取、依赖分析和上下文管理功能。
4
+ """
5
+
6
+ from .symbol_extractor import Symbol, SymbolTable, SymbolExtractor
7
+ from .dependency_analyzer import Dependency, DependencyGraph, DependencyAnalyzer
8
+ from .context_manager import ContextManager, EditContext, Reference
9
+ from .context_recommender import ContextRecommendation
10
+ from .llm_context_recommender import ContextRecommender
11
+ from .language_support import detect_language, get_symbol_extractor, get_dependency_analyzer
12
+ from .base_language import BaseLanguageSupport
13
+ from .language_registry import LanguageRegistry, get_registry, register_language
14
+ from .impact_analyzer import (
15
+ ImpactAnalyzer,
16
+ Impact,
17
+ ImpactReport,
18
+ ImpactType,
19
+ RiskLevel,
20
+ InterfaceChange,
21
+ Edit,
22
+ TestDiscoverer,
23
+ parse_git_diff_to_edits,
24
+ )
25
+ from .structured_code import StructuredCodeExtractor
26
+
27
+ __all__ = [
28
+ # Symbol extraction
29
+ 'Symbol',
30
+ 'SymbolTable',
31
+ 'SymbolExtractor',
32
+ # Dependency analysis
33
+ 'Dependency',
34
+ 'DependencyGraph',
35
+ 'DependencyAnalyzer',
36
+ # Context management
37
+ 'ContextManager',
38
+ 'EditContext',
39
+ 'Reference',
40
+ # Context recommendation
41
+ 'ContextRecommender',
42
+ 'ContextRecommendation',
43
+ # Language support
44
+ 'detect_language',
45
+ 'get_symbol_extractor',
46
+ 'get_dependency_analyzer',
47
+ # Language registry
48
+ 'BaseLanguageSupport',
49
+ 'LanguageRegistry',
50
+ 'get_registry',
51
+ 'register_language',
52
+ # Impact analysis
53
+ 'ImpactAnalyzer',
54
+ 'Impact',
55
+ 'ImpactReport',
56
+ 'ImpactType',
57
+ 'RiskLevel',
58
+ 'InterfaceChange',
59
+ 'Edit',
60
+ 'TestDiscoverer',
61
+ 'parse_git_diff_to_edits',
62
+ # Structured code extraction
63
+ 'StructuredCodeExtractor',
64
+ ]
65
+
@@ -0,0 +1,74 @@
1
+ """基础语言支持抽象类。
2
+
3
+ 定义所有语言支持需要实现的接口,便于扩展新的语言支持。
4
+ """
5
+
6
+ from abc import ABC, abstractmethod
7
+ from typing import Optional, Set
8
+
9
+ from .dependency_analyzer import DependencyAnalyzer
10
+ from .symbol_extractor import SymbolExtractor
11
+
12
+
13
+ class BaseLanguageSupport(ABC):
14
+ """语言支持的基础抽象类。
15
+
16
+ 所有语言支持类都应该继承此类并实现所需的方法。
17
+ """
18
+
19
+ @property
20
+ @abstractmethod
21
+ def language_name(self) -> str:
22
+ """返回语言名称(如 'python', 'rust', 'go')。"""
23
+ pass
24
+
25
+ @property
26
+ @abstractmethod
27
+ def file_extensions(self) -> Set[str]:
28
+ """返回该语言支持的文件扩展名集合(如 {'.py', '.pyw'})。"""
29
+ pass
30
+
31
+ @abstractmethod
32
+ def create_symbol_extractor(self) -> Optional[SymbolExtractor]:
33
+ """创建并返回该语言的符号提取器实例。
34
+
35
+ Returns:
36
+ SymbolExtractor实例,如果不支持符号提取则返回None
37
+ """
38
+ pass
39
+
40
+ @abstractmethod
41
+ def create_dependency_analyzer(self) -> Optional[DependencyAnalyzer]:
42
+ """创建并返回该语言的依赖分析器实例。
43
+
44
+ Returns:
45
+ DependencyAnalyzer实例,如果不支持依赖分析则返回None
46
+ """
47
+ pass
48
+
49
+ def is_source_file(self, file_path: str) -> bool:
50
+ """检查文件是否为该语言的源文件。
51
+
52
+ Args:
53
+ file_path: 文件路径
54
+
55
+ Returns:
56
+ 如果是该语言的源文件返回True,否则返回False
57
+ """
58
+ import os
59
+ _, ext = os.path.splitext(file_path)
60
+ return ext in self.file_extensions
61
+
62
+ def detect_language(self, file_path: str) -> Optional[str]:
63
+ """检测文件是否属于该语言。
64
+
65
+ Args:
66
+ file_path: 文件路径
67
+
68
+ Returns:
69
+ 如果属于该语言返回language_name,否则返回None
70
+ """
71
+ if self.is_source_file(file_path):
72
+ return self.language_name
73
+ return None
74
+
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ 构建验证模块
6
+
7
+ 提供编辑后编译/构建验证功能,支持多种构建系统,具有易扩展性和兜底机制。
8
+ """
9
+
10
+ # 导出主要接口
11
+ from .base import BuildSystem, BuildResult, BuildValidatorBase
12
+ from .detector import BuildSystemDetector
13
+ from .validator import BuildValidator
14
+
15
+ # 导出各语言验证器(便于扩展)
16
+ from .rust import RustBuildValidator
17
+ from .python import PythonBuildValidator
18
+ from .nodejs import NodeJSBuildValidator
19
+ from .java_maven import JavaMavenBuildValidator
20
+ from .java_gradle import JavaGradleBuildValidator
21
+ from .go import GoBuildValidator
22
+ from .cmake import CMakeBuildValidator
23
+ from .makefile import MakefileBuildValidator
24
+ from .fallback import FallbackBuildValidator
25
+
26
+ __all__ = [
27
+ # 主要接口
28
+ "BuildSystem",
29
+ "BuildResult",
30
+ "BuildValidatorBase",
31
+ "BuildSystemDetector",
32
+ "BuildValidator",
33
+ # 各语言验证器
34
+ "RustBuildValidator",
35
+ "PythonBuildValidator",
36
+ "NodeJSBuildValidator",
37
+ "JavaMavenBuildValidator",
38
+ "JavaGradleBuildValidator",
39
+ "GoBuildValidator",
40
+ "CMakeBuildValidator",
41
+ "MakefileBuildValidator",
42
+ "FallbackBuildValidator",
43
+ ]
44
+
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ 构建验证器基础模块
6
+
7
+ 提供基础类和枚举定义。
8
+ """
9
+
10
+ import subprocess
11
+ from abc import ABC, abstractmethod
12
+ from dataclasses import dataclass
13
+ from typing import List, Optional, Tuple
14
+ from enum import Enum
15
+
16
+
17
+ class BuildSystem(Enum):
18
+ """支持的构建系统类型"""
19
+ UNKNOWN = "unknown"
20
+ PYTHON = "python"
21
+ NODEJS = "nodejs"
22
+ RUST = "rust"
23
+ JAVA_MAVEN = "java_maven"
24
+ JAVA_GRADLE = "java_gradle"
25
+ GO = "go"
26
+ C_MAKEFILE = "c_makefile"
27
+ C_CMAKE = "c_cmake"
28
+ C_MAKEFILE_CMAKE = "c_makefile_cmake" # 同时存在Makefile和CMakeLists.txt
29
+
30
+
31
+ @dataclass
32
+ class BuildResult:
33
+ """构建验证结果"""
34
+ success: bool
35
+ output: str
36
+ error_message: Optional[str] = None
37
+ build_system: Optional[BuildSystem] = None
38
+ duration: float = 0.0 # 验证耗时(秒)
39
+
40
+
41
+ class BuildValidatorBase(ABC):
42
+ """构建验证器基类"""
43
+
44
+ # 子类需要定义的类变量
45
+ BUILD_SYSTEM_NAME: str = "" # 构建系统名称,如 "CMake", "Makefile", "Cargo"
46
+ SUPPORTED_LANGUAGES: List[str] = [] # 支持的语言列表,如 ["c", "cpp"]
47
+
48
+ def __init__(self, project_root: str, timeout: int = 30):
49
+ self.project_root = project_root
50
+ self.timeout = timeout
51
+
52
+ @abstractmethod
53
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
54
+ """验证构建
55
+
56
+ Args:
57
+ modified_files: 修改的文件列表(可选,用于增量验证)
58
+
59
+ Returns:
60
+ BuildResult: 验证结果
61
+ """
62
+ pass
63
+
64
+ def _run_command(
65
+ self,
66
+ cmd: List[str],
67
+ cwd: Optional[str] = None,
68
+ timeout: Optional[int] = None,
69
+ capture_output: bool = True,
70
+ ) -> Tuple[int, str, str]:
71
+ """运行命令
72
+
73
+ Args:
74
+ cmd: 命令列表
75
+ cwd: 工作目录
76
+ timeout: 超时时间(秒)
77
+ capture_output: 是否捕获输出
78
+
79
+ Returns:
80
+ (返回码, stdout, stderr)
81
+ """
82
+ if cwd is None:
83
+ cwd = self.project_root
84
+ if timeout is None:
85
+ timeout = self.timeout
86
+
87
+ try:
88
+ result = subprocess.run(
89
+ cmd,
90
+ cwd=cwd,
91
+ timeout=timeout,
92
+ capture_output=capture_output,
93
+ text=True,
94
+ encoding="utf-8",
95
+ errors="replace",
96
+ )
97
+ stdout = result.stdout if capture_output else ""
98
+ stderr = result.stderr if capture_output else ""
99
+ return result.returncode, stdout, stderr
100
+ except subprocess.TimeoutExpired:
101
+ return -1, "", f"命令执行超时({timeout}秒)"
102
+ except FileNotFoundError:
103
+ return -1, "", f"命令未找到: {cmd[0]}"
104
+ except Exception as e:
105
+ return -1, "", f"执行命令时出错: {str(e)}"
106
+
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ CMake构建验证器模块
6
+
7
+ 提供CMake项目的构建验证功能。
8
+ """
9
+
10
+ import os
11
+ import tempfile
12
+ import time
13
+ from typing import List, Optional
14
+
15
+ from .base import BuildValidatorBase, BuildResult, BuildSystem
16
+
17
+
18
+ class CMakeBuildValidator(BuildValidatorBase):
19
+ """CMake构建验证器"""
20
+
21
+ BUILD_SYSTEM_NAME = "CMake"
22
+ SUPPORTED_LANGUAGES = ["c", "cpp"]
23
+
24
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
25
+ start_time = time.time()
26
+
27
+ # 策略1: 尝试使用 cmake --build(如果已有构建目录)
28
+ build_dirs = ["build", "cmake-build-debug", "cmake-build-release"]
29
+ for build_dir in build_dirs:
30
+ build_path = os.path.join(self.project_root, build_dir)
31
+ if os.path.exists(build_path):
32
+ returncode, stdout, stderr = self._run_command(
33
+ ["cmake", "--build", build_path],
34
+ timeout=60,
35
+ )
36
+ duration = time.time() - start_time
37
+ success = returncode == 0
38
+ output = stdout + stderr
39
+ if success:
40
+ print(f"✅ CMake 构建验证成功(耗时 {duration:.2f} 秒)")
41
+ else:
42
+ print(f"❌ CMake 构建验证失败(耗时 {duration:.2f} 秒)")
43
+ print(f"错误信息:CMake构建失败\n{output[:500]}")
44
+ return BuildResult(
45
+ success=success,
46
+ output=output,
47
+ error_message=None if success else "CMake构建失败",
48
+ build_system=BuildSystem.C_CMAKE,
49
+ duration=duration,
50
+ )
51
+
52
+ # 策略2: 仅验证CMakeLists.txt语法
53
+ with tempfile.TemporaryDirectory(prefix="cmake_check_") as tmpdir:
54
+ returncode, stdout, stderr = self._run_command(
55
+ ["cmake", "-S", ".", "-B", tmpdir],
56
+ timeout=10,
57
+ )
58
+ duration = time.time() - start_time
59
+
60
+ success = returncode == 0
61
+ output = stdout + stderr
62
+ if success:
63
+ print(f"✅ CMake 配置验证成功(耗时 {duration:.2f} 秒)")
64
+ else:
65
+ print(f"❌ CMake 配置验证失败(耗时 {duration:.2f} 秒)")
66
+ print(f"错误信息:CMake配置失败\n{output[:500]}")
67
+ return BuildResult(
68
+ success=success,
69
+ output=output,
70
+ error_message=None if success else "CMake配置失败",
71
+ build_system=BuildSystem.C_CMAKE,
72
+ duration=duration,
73
+ )
74
+
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ 构建系统检测器模块
6
+
7
+ 提供构建系统自动检测功能。
8
+ """
9
+
10
+ import os
11
+ from typing import List, Optional
12
+
13
+ from .base import BuildSystem
14
+
15
+
16
+ class BuildSystemDetector:
17
+ """构建系统检测器"""
18
+
19
+ def __init__(self, project_root: str):
20
+ self.project_root = project_root
21
+
22
+ def detect(self) -> Optional[BuildSystem]:
23
+ """检测项目使用的构建系统(兼容旧接口,返回第一个检测到的)
24
+
25
+ Returns:
26
+ 检测到的构建系统,如果无法检测则返回None
27
+ """
28
+ all_systems = self.detect_all()
29
+ return all_systems[0] if all_systems else None
30
+
31
+ def detect_all(self) -> List[BuildSystem]:
32
+ """检测所有可能的构建系统
33
+
34
+ Returns:
35
+ 检测到的所有构建系统列表(按优先级排序)
36
+ """
37
+ detected = []
38
+ # 按优先级检测(从最具体到最通用)
39
+ detectors = [
40
+ self._detect_rust,
41
+ self._detect_go,
42
+ self._detect_java_maven,
43
+ self._detect_java_gradle,
44
+ self._detect_nodejs,
45
+ self._detect_python,
46
+ self._detect_c_cmake,
47
+ self._detect_c_makefile,
48
+ ]
49
+
50
+ for detector in detectors:
51
+ result = detector()
52
+ if result and result not in detected:
53
+ detected.append(result)
54
+
55
+ return detected
56
+
57
+ def _detect_rust(self) -> Optional[BuildSystem]:
58
+ """检测Rust项目(Cargo.toml)"""
59
+ cargo_toml = os.path.join(self.project_root, "Cargo.toml")
60
+ if os.path.exists(cargo_toml):
61
+ return BuildSystem.RUST
62
+ return None
63
+
64
+ def _detect_go(self) -> Optional[BuildSystem]:
65
+ """检测Go项目(go.mod)"""
66
+ go_mod = os.path.join(self.project_root, "go.mod")
67
+ if os.path.exists(go_mod):
68
+ return BuildSystem.GO
69
+ return None
70
+
71
+ def _detect_java_maven(self) -> Optional[BuildSystem]:
72
+ """检测Maven项目(pom.xml)"""
73
+ pom_xml = os.path.join(self.project_root, "pom.xml")
74
+ if os.path.exists(pom_xml):
75
+ return BuildSystem.JAVA_MAVEN
76
+ return None
77
+
78
+ def _detect_java_gradle(self) -> Optional[BuildSystem]:
79
+ """检测Gradle项目(build.gradle或build.gradle.kts)"""
80
+ build_gradle = os.path.join(self.project_root, "build.gradle")
81
+ build_gradle_kts = os.path.join(self.project_root, "build.gradle.kts")
82
+ if os.path.exists(build_gradle) or os.path.exists(build_gradle_kts):
83
+ return BuildSystem.JAVA_GRADLE
84
+ return None
85
+
86
+ def _detect_nodejs(self) -> Optional[BuildSystem]:
87
+ """检测Node.js项目(package.json)"""
88
+ package_json = os.path.join(self.project_root, "package.json")
89
+ if os.path.exists(package_json):
90
+ return BuildSystem.NODEJS
91
+ return None
92
+
93
+ def _detect_python(self) -> Optional[BuildSystem]:
94
+ """检测Python项目(setup.py, pyproject.toml, requirements.txt等)"""
95
+ indicators = [
96
+ "setup.py",
97
+ "pyproject.toml",
98
+ "requirements.txt",
99
+ "setup.cfg",
100
+ "Pipfile",
101
+ "poetry.lock",
102
+ ]
103
+ for indicator in indicators:
104
+ if os.path.exists(os.path.join(self.project_root, indicator)):
105
+ return BuildSystem.PYTHON
106
+ return None
107
+
108
+ def _detect_c_cmake(self) -> Optional[BuildSystem]:
109
+ """检测CMake项目(CMakeLists.txt)"""
110
+ cmake_lists = os.path.join(self.project_root, "CMakeLists.txt")
111
+ if os.path.exists(cmake_lists):
112
+ # 检查是否同时存在Makefile
113
+ makefile = os.path.join(self.project_root, "Makefile")
114
+ if os.path.exists(makefile):
115
+ return BuildSystem.C_MAKEFILE_CMAKE
116
+ return BuildSystem.C_CMAKE
117
+ return None
118
+
119
+ def _detect_c_makefile(self) -> Optional[BuildSystem]:
120
+ """检测Makefile项目"""
121
+ makefile = os.path.join(self.project_root, "Makefile")
122
+ if os.path.exists(makefile):
123
+ return BuildSystem.C_MAKEFILE
124
+ return None
125
+
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ 兜底构建验证器模块
6
+
7
+ 当无法检测构建系统时使用的兜底验证器。
8
+ """
9
+
10
+ import os
11
+ import time
12
+ from typing import List, Optional
13
+
14
+ from .base import BuildValidatorBase, BuildResult, BuildSystem
15
+
16
+
17
+ class FallbackBuildValidator(BuildValidatorBase):
18
+ """兜底验证器:当无法检测构建系统时使用"""
19
+
20
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
21
+ start_time = time.time()
22
+
23
+ # 策略1: 根据文件扩展名进行基本的语法检查
24
+ if modified_files:
25
+ errors = []
26
+ for file_path in modified_files:
27
+ ext = os.path.splitext(file_path)[1].lower()
28
+ full_path = os.path.join(self.project_root, file_path)
29
+
30
+ if not os.path.exists(full_path):
31
+ continue
32
+
33
+ # Python文件:使用py_compile
34
+ if ext == ".py":
35
+ returncode, _, stderr = self._run_command(
36
+ ["python", "-m", "py_compile", full_path],
37
+ timeout=5,
38
+ )
39
+ if returncode != 0:
40
+ errors.append(f"{file_path}: {stderr}")
41
+
42
+ # JavaScript文件:尝试使用node检查语法
43
+ elif ext in (".js", ".mjs", ".cjs"):
44
+ returncode, _, stderr = self._run_command(
45
+ ["node", "--check", full_path],
46
+ timeout=5,
47
+ )
48
+ if returncode != 0:
49
+ errors.append(f"{file_path}: {stderr}")
50
+
51
+ if errors:
52
+ duration = time.time() - start_time
53
+ print(f"❌ 基础语法检查失败(耗时 {duration:.2f} 秒)")
54
+ print(f"错误信息:语法检查失败\n{chr(10).join(errors[:5])}")
55
+ return BuildResult(
56
+ success=False,
57
+ output="\n".join(errors),
58
+ error_message="语法检查失败",
59
+ build_system=BuildSystem.UNKNOWN,
60
+ duration=duration,
61
+ )
62
+
63
+ duration = time.time() - start_time
64
+ print(f"✅ 基础语法检查通过(耗时 {duration:.2f} 秒,未检测到构建系统)")
65
+ return BuildResult(
66
+ success=True,
67
+ output="基础语法检查通过(未检测到构建系统)",
68
+ error_message=None,
69
+ build_system=BuildSystem.UNKNOWN,
70
+ duration=duration,
71
+ )
72
+
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Go构建验证器模块
6
+
7
+ 提供Go项目的构建验证功能。
8
+ """
9
+
10
+ import time
11
+ from typing import List, Optional
12
+
13
+ from .base import BuildValidatorBase, BuildResult, BuildSystem
14
+
15
+
16
+ class GoBuildValidator(BuildValidatorBase):
17
+ """Go构建验证器(使用go test,包括编译和测试)"""
18
+
19
+ BUILD_SYSTEM_NAME = "Go Build"
20
+ SUPPORTED_LANGUAGES = ["go"]
21
+
22
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
23
+ start_time = time.time()
24
+
25
+ # 使用 go test 进行构建和测试验证(会自动编译并运行测试)
26
+ cmd = ["go", "test", "./..."]
27
+
28
+ returncode, stdout, stderr = self._run_command(cmd, timeout=30)
29
+ duration = time.time() - start_time
30
+
31
+ success = returncode == 0
32
+ output = stdout + stderr
33
+
34
+ if not success:
35
+ # 尝试解析错误信息(包括编译错误和测试失败)
36
+ error_message = self._parse_go_errors(output)
37
+ print(f"❌ Go 构建验证失败(耗时 {duration:.2f} 秒)")
38
+ if error_message:
39
+ print(f"错误信息:\n{error_message}")
40
+ else:
41
+ print(f"输出:\n{output[:500]}")
42
+ else:
43
+ error_message = None
44
+ print(f"✅ Go 构建验证成功(耗时 {duration:.2f} 秒)")
45
+
46
+ return BuildResult(
47
+ success=success,
48
+ output=output,
49
+ error_message=error_message,
50
+ build_system=BuildSystem.GO,
51
+ duration=duration,
52
+ )
53
+
54
+ def _parse_go_errors(self, output: str) -> str:
55
+ """解析Go的错误输出(包括编译错误和测试失败)"""
56
+ # 简化处理:提取关键错误信息
57
+ lines = output.split("\n")
58
+ errors = []
59
+ for line in lines:
60
+ # 匹配编译错误
61
+ if "error:" in line.lower() or "cannot" in line.lower():
62
+ errors.append(line.strip())
63
+ # 匹配测试失败
64
+ elif "--- FAIL:" in line or "FAIL" in line:
65
+ errors.append(line.strip())
66
+ # 匹配断言失败
67
+ elif "got" in line.lower() and "want" in line.lower():
68
+ errors.append(line.strip())
69
+ return "\n".join(errors[:10]) if errors else output[:500] # 限制长度
70
+
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Java Gradle构建验证器模块
6
+
7
+ 提供Java Gradle项目的构建验证功能。
8
+ """
9
+
10
+ import os
11
+ import time
12
+ from typing import List, Optional
13
+
14
+ from .base import BuildValidatorBase, BuildResult, BuildSystem
15
+
16
+
17
+ class JavaGradleBuildValidator(BuildValidatorBase):
18
+ """Java Gradle构建验证器"""
19
+
20
+ BUILD_SYSTEM_NAME = "Gradle"
21
+ SUPPORTED_LANGUAGES = ["java"]
22
+
23
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
24
+ start_time = time.time()
25
+
26
+ # 使用 gradle compileJava 进行编译验证
27
+ # 优先使用 gradlew(如果存在)
28
+ gradlew = os.path.join(self.project_root, "gradlew")
29
+ if os.path.exists(gradlew):
30
+ cmd = ["./gradlew", "compileJava", "--quiet"]
31
+ else:
32
+ cmd = ["gradle", "compileJava", "--quiet"]
33
+
34
+ returncode, stdout, stderr = self._run_command(cmd, timeout=60)
35
+ duration = time.time() - start_time
36
+
37
+ success = returncode == 0
38
+ output = stdout + stderr
39
+
40
+ if success:
41
+ print(f"✅ Gradle 构建验证成功(耗时 {duration:.2f} 秒)")
42
+ else:
43
+ print(f"❌ Gradle 构建验证失败(耗时 {duration:.2f} 秒)")
44
+ print(f"错误信息:Gradle编译失败\n{output[:500]}")
45
+
46
+ return BuildResult(
47
+ success=success,
48
+ output=output,
49
+ error_message=None if success else "Gradle编译失败",
50
+ build_system=BuildSystem.JAVA_GRADLE,
51
+ duration=duration,
52
+ )
53
+