diffsense 2.2.12__tar.gz
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.
- diffsense-2.2.12/LICENSE +176 -0
- diffsense-2.2.12/PKG-INFO +18 -0
- diffsense-2.2.12/README.md +48 -0
- diffsense-2.2.12/adapters/__init__.py +0 -0
- diffsense-2.2.12/adapters/base.py +27 -0
- diffsense-2.2.12/adapters/github_adapter.py +164 -0
- diffsense-2.2.12/adapters/gitlab_adapter.py +207 -0
- diffsense-2.2.12/adapters/local_adapter.py +136 -0
- diffsense-2.2.12/banner.py +71 -0
- diffsense-2.2.12/cli.py +606 -0
- diffsense-2.2.12/config/__init__.py +1 -0
- diffsense-2.2.12/config/rules.yaml +371 -0
- diffsense-2.2.12/core/__init__.py +235 -0
- diffsense-2.2.12/core/ast_detector.py +853 -0
- diffsense-2.2.12/core/change.py +46 -0
- diffsense-2.2.12/core/composer.py +93 -0
- diffsense-2.2.12/core/evaluator.py +15 -0
- diffsense-2.2.12/core/ignore_manager.py +71 -0
- diffsense-2.2.12/core/knowledge.py +77 -0
- diffsense-2.2.12/core/parser.py +181 -0
- diffsense-2.2.12/core/parser_manager.py +104 -0
- diffsense-2.2.12/core/quality_manager.py +117 -0
- diffsense-2.2.12/core/renderer.py +197 -0
- diffsense-2.2.12/core/rule_base.py +98 -0
- diffsense-2.2.12/core/rule_runtime.py +103 -0
- diffsense-2.2.12/core/rules.py +718 -0
- diffsense-2.2.12/core/run_config.py +85 -0
- diffsense-2.2.12/core/semantic_diff.py +359 -0
- diffsense-2.2.12/core/signal_model.py +21 -0
- diffsense-2.2.12/core/signals_registry.py +62 -0
- diffsense-2.2.12/diffsense.egg-info/PKG-INFO +18 -0
- diffsense-2.2.12/diffsense.egg-info/SOURCES.txt +77 -0
- diffsense-2.2.12/diffsense.egg-info/dependency_links.txt +1 -0
- diffsense-2.2.12/diffsense.egg-info/entry_points.txt +3 -0
- diffsense-2.2.12/diffsense.egg-info/requires.txt +12 -0
- diffsense-2.2.12/diffsense.egg-info/top_level.txt +11 -0
- diffsense-2.2.12/diffsense_mcp/__init__.py +1 -0
- diffsense-2.2.12/diffsense_mcp/launcher.py +28 -0
- diffsense-2.2.12/diffsense_mcp/server.py +687 -0
- diffsense-2.2.12/governance/lifecycle.py +54 -0
- diffsense-2.2.12/main.py +318 -0
- diffsense-2.2.12/pyproject.toml +36 -0
- diffsense-2.2.12/rules/__init__.py +246 -0
- diffsense-2.2.12/rules/api_compatibility.py +372 -0
- diffsense-2.2.12/rules/collection_handling.py +349 -0
- diffsense-2.2.12/rules/concurrency.py +194 -0
- diffsense-2.2.12/rules/concurrency_adapter.py +250 -0
- diffsense-2.2.12/rules/cross_language_adapter.py +444 -0
- diffsense-2.2.12/rules/exception_handling.py +320 -0
- diffsense-2.2.12/rules/go_rules.py +401 -0
- diffsense-2.2.12/rules/null_safety.py +301 -0
- diffsense-2.2.12/rules/resource_management.py +222 -0
- diffsense-2.2.12/rules/yaml_adapter.py +195 -0
- diffsense-2.2.12/run_audit.py +478 -0
- diffsense-2.2.12/sdk/cpp_adapter.py +238 -0
- diffsense-2.2.12/sdk/go_adapter.py +199 -0
- diffsense-2.2.12/sdk/java_adapter.py +199 -0
- diffsense-2.2.12/sdk/javascript_adapter.py +229 -0
- diffsense-2.2.12/sdk/language_adapter.py +313 -0
- diffsense-2.2.12/sdk/python_adapter.py +195 -0
- diffsense-2.2.12/sdk/rule.py +63 -0
- diffsense-2.2.12/sdk/signal.py +14 -0
- diffsense-2.2.12/setup.cfg +4 -0
- diffsense-2.2.12/tests/test_adaptive_scheduling.py +103 -0
- diffsense-2.2.12/tests/test_cache_and_scheduling.py +219 -0
- diffsense-2.2.12/tests/test_critical_removal.py +46 -0
- diffsense-2.2.12/tests/test_entry_point_rules.py +114 -0
- diffsense-2.2.12/tests/test_go_cve_rules.py +95 -0
- diffsense-2.2.12/tests/test_inline_ignore.py +36 -0
- diffsense-2.2.12/tests/test_lifecycle.py +91 -0
- diffsense-2.2.12/tests/test_p0_concurrency.py +107 -0
- diffsense-2.2.12/tests/test_profile.py +86 -0
- diffsense-2.2.12/tests/test_regression.py +23 -0
- diffsense-2.2.12/tests/test_repo_ignore.py +56 -0
- diffsense-2.2.12/tests/test_rule_metadata.py +74 -0
- diffsense-2.2.12/tests/test_rules_directory.py +69 -0
- diffsense-2.2.12/tests/test_semantic_regression.py +97 -0
- diffsense-2.2.12/tests/test_signal_consistency.py +61 -0
- diffsense-2.2.12/tests/test_type_downgrade.py +43 -0
diffsense-2.2.12/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: diffsense
|
|
3
|
+
Version: 2.2.12
|
|
4
|
+
Summary: MR/PR risk audit: semantic diff + rule engine. Run in CI as image or pip.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: PyYAML
|
|
9
|
+
Requires-Dist: PyGithub
|
|
10
|
+
Requires-Dist: python-gitlab
|
|
11
|
+
Requires-Dist: requests
|
|
12
|
+
Requires-Dist: javalang
|
|
13
|
+
Requires-Dist: typer>=0.9.0
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest; extra == "dev"
|
|
16
|
+
Provides-Extra: mcp
|
|
17
|
+
Requires-Dist: mcp>=1.0.0; extra == "mcp"
|
|
18
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# DiffSense CLI
|
|
2
|
+
|
|
3
|
+
**定位**:PR 阶段的变更风险守门人(Change Risk Gate),针对当前 diff 判断是否引入回归风险。设计目标:少告警、高精度、低延迟、结果可解释。
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 快速开始
|
|
8
|
+
|
|
9
|
+
| 场景 | 操作 |
|
|
10
|
+
|------|------|
|
|
11
|
+
| **GitHub PR 审计** | 将 [quickstart 中的 GitHub workflow](docs/quickstart.md#方式一github-pull-request-审计) 复制到目标仓库的 `.github/workflows/diffsense.yml`,提交并创建/更新 PR 即可触发审计。 |
|
|
12
|
+
| **本地 diff 审计** | 执行 `pip install -e .` 后,运行 `diffsense replay <path-to-diff>`。 |
|
|
13
|
+
|
|
14
|
+
完整步骤与可选配置见 **[docs/quickstart.md](docs/quickstart.md)**。所有用户文档与契约索引见 **[docs/README.md](docs/README.md)**。
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 推荐配置(可选)
|
|
19
|
+
|
|
20
|
+
在仓库根目录添加 **`.diffsense.yaml`** 可启用 [官方推荐配置](docs/recommended-config.md),适用于大多数团队,无需逐项调参。
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## 文档索引
|
|
25
|
+
|
|
26
|
+
| 文档 | 说明 |
|
|
27
|
+
|------|------|
|
|
28
|
+
| [docs/README.md](docs/README.md) | **文档总索引**(用户文档与契约列表) |
|
|
29
|
+
| [quickstart.md](docs/quickstart.md) | 快速开始:GitHub workflow 与本地审计步骤 |
|
|
30
|
+
| [recommended-config.md](docs/recommended-config.md) | 官方推荐配置与默认行为承诺 |
|
|
31
|
+
| [ignoring.md](docs/ignoring.md) | 忽略规则与误报处理 |
|
|
32
|
+
| [ci-cache.md](docs/ci-cache.md) | CI 缓存配置与使用 |
|
|
33
|
+
| [rule-quickstart.md](docs/rule-quickstart.md) | 自定义规则开发入门(10 分钟上手) |
|
|
34
|
+
| [signals.md](docs/signals.md) | Signal 列表(规则只消费,不产生) |
|
|
35
|
+
| [contribute-rules.md](docs/contribute-rules.md) | 贡献审计规则(上游 vs 插件) |
|
|
36
|
+
|
|
37
|
+
**10 分钟写一条规则:** [rule-quickstart.md](docs/rule-quickstart.md) · `diffsense signals`
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## 开发与贡献
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install -e ".[dev]"
|
|
45
|
+
pytest tests/ -v
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
详见 [CONTRIBUTING.md](CONTRIBUTING.md)。
|
|
File without changes
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
class PlatformAdapter(ABC):
|
|
4
|
+
@abstractmethod
|
|
5
|
+
def fetch_diff(self) -> str:
|
|
6
|
+
"""
|
|
7
|
+
Fetch unified diff content from the platform.
|
|
8
|
+
"""
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
@abstractmethod
|
|
12
|
+
def post_comment(self, content: str):
|
|
13
|
+
"""
|
|
14
|
+
Post a comment to the MR/PR.
|
|
15
|
+
Should handle update logic if applicable (e.g. edit existing comment).
|
|
16
|
+
"""
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
def is_approved(self) -> bool:
|
|
20
|
+
"""
|
|
21
|
+
Check if the MR/PR is approved by a reviewer.
|
|
22
|
+
Default implementation returns False.
|
|
23
|
+
"""
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
def post_inline_comments(self, comments):
|
|
27
|
+
return None
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from github import Github, GithubException
|
|
3
|
+
import requests
|
|
4
|
+
from .base import PlatformAdapter
|
|
5
|
+
|
|
6
|
+
class GitHubAdapter(PlatformAdapter):
|
|
7
|
+
def __init__(self, token: str, repo_name: str, pr_number: int):
|
|
8
|
+
self.gh = Github(token)
|
|
9
|
+
self.repo = self.gh.get_repo(repo_name)
|
|
10
|
+
self.pr = self.repo.get_pull(pr_number)
|
|
11
|
+
self.comment_tag = "<!-- diffsense_audit_report -->"
|
|
12
|
+
|
|
13
|
+
def fetch_diff(self) -> str:
|
|
14
|
+
# PyGithub's get_files() doesn't give raw unified diff easily for the whole PR.
|
|
15
|
+
# It's better to fetch the diff url directly.
|
|
16
|
+
# But wait, self.pr.diff_url gives the url, we need to download it.
|
|
17
|
+
# However, accessing the URL requires auth if the repo is private.
|
|
18
|
+
# We can use the token in headers.
|
|
19
|
+
|
|
20
|
+
headers = {
|
|
21
|
+
'Authorization': f'token {self.gh.get_user().login if False else os.environ.get("GITHUB_TOKEN")}',
|
|
22
|
+
'Accept': 'application/vnd.github.v3.diff'
|
|
23
|
+
}
|
|
24
|
+
# Actually PyGithub handles auth, but for raw request we need to handle it.
|
|
25
|
+
# Let's use requests.
|
|
26
|
+
# Note: os.environ.get("GITHUB_TOKEN") is usually passed via constructor,
|
|
27
|
+
# but here we rely on the passed token.
|
|
28
|
+
|
|
29
|
+
# Re-construct headers properly
|
|
30
|
+
# We need to use the token passed in init.
|
|
31
|
+
# But wait, Github object doesn't expose raw token easily?
|
|
32
|
+
# Actually it does, but let's just use the one passed to init.
|
|
33
|
+
# Wait, self.gh is authenticated.
|
|
34
|
+
|
|
35
|
+
# self.pr.diff_url is public accessible? No, for private repos it needs auth.
|
|
36
|
+
# Let's use requests with the token.
|
|
37
|
+
|
|
38
|
+
# BUT, there's a simpler way:
|
|
39
|
+
# response = requests.get(self.pr.diff_url, headers={'Authorization': f'token {token}'})
|
|
40
|
+
# I need to store the token.
|
|
41
|
+
pass
|
|
42
|
+
# Let's refactor init to store token or handle this better.
|
|
43
|
+
# Actually, self.pr has not 'diff' attribute directly?
|
|
44
|
+
# PyGithub requests:
|
|
45
|
+
# content = self.repo._requester.requestJsonAndCheck("GET", self.pr.url, headers={"Accept": "application/vnd.github.v3.diff"})
|
|
46
|
+
# This is internal API usage.
|
|
47
|
+
|
|
48
|
+
# Safer way: requests.
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
def fetch_diff_safe(self, token: str) -> str:
|
|
52
|
+
headers = {
|
|
53
|
+
'Authorization': f'token {token}',
|
|
54
|
+
'Accept': 'application/vnd.github.v3.diff'
|
|
55
|
+
}
|
|
56
|
+
response = requests.get(self.pr.url, headers=headers)
|
|
57
|
+
response.raise_for_status()
|
|
58
|
+
return response.text
|
|
59
|
+
|
|
60
|
+
def post_comment(self, content: str):
|
|
61
|
+
# Check for existing comment
|
|
62
|
+
comments = self.pr.get_issue_comments()
|
|
63
|
+
existing_comment = None
|
|
64
|
+
for comment in comments:
|
|
65
|
+
if self.comment_tag in comment.body:
|
|
66
|
+
existing_comment = comment
|
|
67
|
+
break
|
|
68
|
+
|
|
69
|
+
body = f"{self.comment_tag}\n{content}"
|
|
70
|
+
|
|
71
|
+
if existing_comment:
|
|
72
|
+
existing_comment.edit(body)
|
|
73
|
+
print(f"Updated existing comment {existing_comment.id}")
|
|
74
|
+
else:
|
|
75
|
+
self.pr.create_issue_comment(body)
|
|
76
|
+
print("Created new comment")
|
|
77
|
+
|
|
78
|
+
# Redefine class to include token storage and proper fetch
|
|
79
|
+
class GitHubAdapter(PlatformAdapter):
|
|
80
|
+
def __init__(self, token: str, repo_name: str, pr_number: int):
|
|
81
|
+
self.token = token
|
|
82
|
+
self.gh = Github(token)
|
|
83
|
+
self.repo = self.gh.get_repo(repo_name)
|
|
84
|
+
self.pr = self.repo.get_pull(pr_number)
|
|
85
|
+
self.comment_tag = "<!-- diffsense_audit_report -->"
|
|
86
|
+
|
|
87
|
+
def fetch_diff(self) -> str:
|
|
88
|
+
headers = {
|
|
89
|
+
'Authorization': f'token {self.token}',
|
|
90
|
+
'Accept': 'application/vnd.github.v3.diff'
|
|
91
|
+
}
|
|
92
|
+
# self.pr.url gives the API url (e.g. https://api.github.com/repos/...)
|
|
93
|
+
# Requesting it with diff header gives the diff.
|
|
94
|
+
response = requests.get(self.pr.url, headers=headers)
|
|
95
|
+
response.raise_for_status()
|
|
96
|
+
return response.text
|
|
97
|
+
|
|
98
|
+
def post_comment(self, content: str):
|
|
99
|
+
comments = self.pr.get_issue_comments()
|
|
100
|
+
existing_comment = None
|
|
101
|
+
for comment in comments:
|
|
102
|
+
if self.comment_tag in comment.body:
|
|
103
|
+
existing_comment = comment
|
|
104
|
+
break
|
|
105
|
+
|
|
106
|
+
final_body = f"{content}\n\n{self.comment_tag}"
|
|
107
|
+
|
|
108
|
+
if existing_comment:
|
|
109
|
+
existing_comment.edit(final_body)
|
|
110
|
+
print(f"Updated GitHub comment {existing_comment.id}")
|
|
111
|
+
else:
|
|
112
|
+
self.pr.create_issue_comment(final_body)
|
|
113
|
+
print("Created GitHub comment")
|
|
114
|
+
|
|
115
|
+
def post_inline_comments(self, comments):
|
|
116
|
+
if not comments:
|
|
117
|
+
return
|
|
118
|
+
commit = self.pr.head.sha
|
|
119
|
+
for c in comments:
|
|
120
|
+
path = c.get("path")
|
|
121
|
+
position = c.get("position")
|
|
122
|
+
body = c.get("body")
|
|
123
|
+
if not path or not position or not body:
|
|
124
|
+
continue
|
|
125
|
+
try:
|
|
126
|
+
self.pr.create_review_comment(body, commit, path, position)
|
|
127
|
+
except Exception as e:
|
|
128
|
+
print(f"Inline comment failed: {e}")
|
|
129
|
+
|
|
130
|
+
def is_approved(self) -> bool:
|
|
131
|
+
reviews = self.pr.get_reviews()
|
|
132
|
+
reviewer_states = {}
|
|
133
|
+
for review in reviews:
|
|
134
|
+
# Dismissed reviews are not active, but get_reviews might return them?
|
|
135
|
+
# State can be APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED, PENDING.
|
|
136
|
+
# We only care about the latest state per user.
|
|
137
|
+
reviewer_states[review.user.login] = review.state
|
|
138
|
+
|
|
139
|
+
has_approval = False
|
|
140
|
+
has_changes_requested = False
|
|
141
|
+
|
|
142
|
+
for state in reviewer_states.values():
|
|
143
|
+
if state == 'APPROVED':
|
|
144
|
+
has_approval = True
|
|
145
|
+
elif state == 'CHANGES_REQUESTED':
|
|
146
|
+
has_changes_requested = True
|
|
147
|
+
|
|
148
|
+
# If any changes requested, it's not approved.
|
|
149
|
+
# If approved by at least one and no changes requested, it's approved.
|
|
150
|
+
return has_approval and not has_changes_requested
|
|
151
|
+
|
|
152
|
+
def has_ack_reaction(self) -> bool:
|
|
153
|
+
"""
|
|
154
|
+
Check if the bot's comment has a Thumbs Up (👍) reaction.
|
|
155
|
+
"""
|
|
156
|
+
comments = self.pr.get_issue_comments()
|
|
157
|
+
for comment in comments:
|
|
158
|
+
if self.comment_tag in comment.body:
|
|
159
|
+
# Check reactions
|
|
160
|
+
reactions = comment.get_reactions()
|
|
161
|
+
for reaction in reactions:
|
|
162
|
+
if reaction.content == "+1": # +1 corresponds to 👍
|
|
163
|
+
return True
|
|
164
|
+
return False
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import gitlab
|
|
2
|
+
import requests
|
|
3
|
+
from .base import PlatformAdapter
|
|
4
|
+
|
|
5
|
+
class GitLabAdapter(PlatformAdapter):
|
|
6
|
+
def __init__(self, url: str, token: str, project_id: str, mr_iid: int):
|
|
7
|
+
self.gl = gitlab.Gitlab(url, private_token=token)
|
|
8
|
+
try:
|
|
9
|
+
self.project = self.gl.projects.get(project_id)
|
|
10
|
+
self.mr = self.project.mergerequests.get(mr_iid)
|
|
11
|
+
except gitlab.exceptions.GitlabGetError as e:
|
|
12
|
+
if e.response_code == 404:
|
|
13
|
+
print(f"❌ Error: Could not find Project {project_id} or MR {mr_iid} on {url}.")
|
|
14
|
+
print(" - Check if DIFFSENSE_TOKEN has 'api' scope.")
|
|
15
|
+
print(" - Ensure the token user is a member of the project.")
|
|
16
|
+
print(" - Verify the GitLab URL is correct (defaults to gitlab.com if not specified).")
|
|
17
|
+
raise e
|
|
18
|
+
self.comment_tag = "<!-- diffsense_audit_report -->"
|
|
19
|
+
self.inline_comment_tag = "<!-- diffsense_inline_report -->"
|
|
20
|
+
self.token = token # store for manual request if needed
|
|
21
|
+
|
|
22
|
+
def fetch_diff(self) -> str:
|
|
23
|
+
# GitLab API returns diffs in list of dicts via /changes
|
|
24
|
+
# or we can get unified diff via .diff endpoint.
|
|
25
|
+
# However, for large MRs, the .diff endpoint might be paginated or truncated?
|
|
26
|
+
# Let's try to use the project.mergerequests.changes() method which gives structured diffs
|
|
27
|
+
# and reconstruct unified diff if needed, OR just use the raw diff endpoint.
|
|
28
|
+
|
|
29
|
+
# Issue: If the raw diff endpoint returns something unexpected or empty.
|
|
30
|
+
# Let's try to use the changes API as a fallback or primary source if raw fails.
|
|
31
|
+
|
|
32
|
+
base_url = self.gl.url.rstrip('/')
|
|
33
|
+
diff_url = f"{base_url}/api/v4/projects/{self.project.id}/merge_requests/{self.mr.iid}.diff"
|
|
34
|
+
|
|
35
|
+
headers = {
|
|
36
|
+
'PRIVATE-TOKEN': self.token
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
response = requests.get(diff_url, headers=headers)
|
|
41
|
+
response.raise_for_status()
|
|
42
|
+
content = response.text
|
|
43
|
+
|
|
44
|
+
# Validation: Check if it's JSON (API error or wrong endpoint behavior)
|
|
45
|
+
if content.strip().startswith('{') and '"id":' in content:
|
|
46
|
+
print("Warning: .diff endpoint returned JSON. Falling back to changes API.")
|
|
47
|
+
return self._fetch_diff_fallback()
|
|
48
|
+
|
|
49
|
+
if not content.strip():
|
|
50
|
+
print("Warning: Raw diff is empty. Trying fallback to changes API.")
|
|
51
|
+
return self._fetch_diff_fallback()
|
|
52
|
+
return content
|
|
53
|
+
except Exception as e:
|
|
54
|
+
print(f"Warning: Failed to fetch raw diff: {e}. Trying fallback.")
|
|
55
|
+
return self._fetch_diff_fallback()
|
|
56
|
+
|
|
57
|
+
def _fetch_diff_fallback(self) -> str:
|
|
58
|
+
# Fallback: Use python-gitlab changes() API and reconstruct unified-like diff
|
|
59
|
+
# This is robust because it uses the official API structure
|
|
60
|
+
mr_changes = self.mr.changes()
|
|
61
|
+
diffs = mr_changes.get('changes', [])
|
|
62
|
+
|
|
63
|
+
unified_diff = []
|
|
64
|
+
for d in diffs:
|
|
65
|
+
old_path = d.get('old_path')
|
|
66
|
+
new_path = d.get('new_path')
|
|
67
|
+
diff_text = d.get('diff', '')
|
|
68
|
+
|
|
69
|
+
unified_diff.append(f"diff --git a/{old_path} b/{new_path}")
|
|
70
|
+
if d.get('new_file'):
|
|
71
|
+
unified_diff.append(f"--- /dev/null")
|
|
72
|
+
unified_diff.append(f"+++ b/{new_path}")
|
|
73
|
+
elif d.get('deleted_file'):
|
|
74
|
+
unified_diff.append(f"--- a/{old_path}")
|
|
75
|
+
unified_diff.append(f"+++ /dev/null")
|
|
76
|
+
elif d.get('renamed_file'):
|
|
77
|
+
unified_diff.append(f"--- a/{old_path}")
|
|
78
|
+
unified_diff.append(f"+++ b/{new_path}")
|
|
79
|
+
else:
|
|
80
|
+
unified_diff.append(f"--- a/{old_path}")
|
|
81
|
+
unified_diff.append(f"+++ b/{new_path}")
|
|
82
|
+
|
|
83
|
+
unified_diff.append(diff_text)
|
|
84
|
+
|
|
85
|
+
return "\n".join(unified_diff)
|
|
86
|
+
|
|
87
|
+
def post_comment(self, content: str):
|
|
88
|
+
# Check for existing comment
|
|
89
|
+
notes = self.mr.notes.list(all=True)
|
|
90
|
+
existing_note = None
|
|
91
|
+
for note in notes:
|
|
92
|
+
if self.comment_tag in note.body:
|
|
93
|
+
existing_note = note
|
|
94
|
+
break
|
|
95
|
+
|
|
96
|
+
# Ensure content is properly formatted with the tag
|
|
97
|
+
final_body = f"{content}\n\n{self.comment_tag}"
|
|
98
|
+
|
|
99
|
+
if existing_note:
|
|
100
|
+
# Update existing comment
|
|
101
|
+
existing_note.body = final_body
|
|
102
|
+
existing_note.save()
|
|
103
|
+
print(f"Updated GitLab note {existing_note.id}")
|
|
104
|
+
else:
|
|
105
|
+
# Create new comment
|
|
106
|
+
self.mr.notes.create({'body': final_body})
|
|
107
|
+
print("Created GitLab note")
|
|
108
|
+
|
|
109
|
+
def post_inline_comments(self, comments):
|
|
110
|
+
if not comments:
|
|
111
|
+
return
|
|
112
|
+
# IMPORTANT:
|
|
113
|
+
# Do not call post_comment() here. That would overwrite the main
|
|
114
|
+
# markdown audit report (regression bug), causing plain text fallback.
|
|
115
|
+
lines = ["## Inline Findings", ""]
|
|
116
|
+
for c in comments:
|
|
117
|
+
path = c.get("path", "")
|
|
118
|
+
line = c.get("line", "")
|
|
119
|
+
body = c.get("body", "")
|
|
120
|
+
lines.append(f"- `{path}:{line}` {body}")
|
|
121
|
+
content = "\n".join(lines)
|
|
122
|
+
final_body = f"{content}\n\n{self.inline_comment_tag}"
|
|
123
|
+
|
|
124
|
+
notes = self.mr.notes.list(all=True)
|
|
125
|
+
existing_note = None
|
|
126
|
+
for note in notes:
|
|
127
|
+
if self.inline_comment_tag in note.body:
|
|
128
|
+
existing_note = note
|
|
129
|
+
break
|
|
130
|
+
|
|
131
|
+
if existing_note:
|
|
132
|
+
existing_note.body = final_body
|
|
133
|
+
existing_note.save()
|
|
134
|
+
print(f"Updated GitLab inline note {existing_note.id}")
|
|
135
|
+
else:
|
|
136
|
+
self.mr.notes.create({"body": final_body})
|
|
137
|
+
print("Created GitLab inline note")
|
|
138
|
+
|
|
139
|
+
def is_approved(self) -> bool:
|
|
140
|
+
"""
|
|
141
|
+
Check if MR is approved using GitLab's Approvals API.
|
|
142
|
+
"""
|
|
143
|
+
try:
|
|
144
|
+
# Need to fetch approvals explicitly
|
|
145
|
+
approvals = self.mr.approvals.get()
|
|
146
|
+
# Logic: If approved_by list is not empty, consider it approved?
|
|
147
|
+
# Or check approvals_left <= 0?
|
|
148
|
+
# Dubbo/OpenSource usually relies on 'approved' state.
|
|
149
|
+
|
|
150
|
+
# Strategy 1: Check if any approval exists
|
|
151
|
+
# Note: approvals.approved_by is a list of users
|
|
152
|
+
if hasattr(approvals, 'approved_by') and approvals.approved_by and len(approvals.approved_by) > 0:
|
|
153
|
+
return True
|
|
154
|
+
|
|
155
|
+
# Strategy 2: Check approvals_left (if configured)
|
|
156
|
+
# Note: approvals_left might not exist if no rules are set
|
|
157
|
+
if hasattr(approvals, 'approvals_left') and approvals.approvals_left == 0:
|
|
158
|
+
return True
|
|
159
|
+
|
|
160
|
+
# Strategy 3: Check 'approved' attribute directly (some GitLab versions)
|
|
161
|
+
if hasattr(approvals, 'approved') and approvals.approved:
|
|
162
|
+
return True
|
|
163
|
+
|
|
164
|
+
return False
|
|
165
|
+
except Exception as e:
|
|
166
|
+
print(f"Warning: Failed to fetch GitLab approvals: {e}")
|
|
167
|
+
return False
|
|
168
|
+
|
|
169
|
+
def has_ack_reaction(self) -> bool:
|
|
170
|
+
"""
|
|
171
|
+
Check if the bot's report comment has a 'thumbsup' or 'rocket' reaction.
|
|
172
|
+
This allows 'Click-to-Ack' flow without formal approval.
|
|
173
|
+
"""
|
|
174
|
+
try:
|
|
175
|
+
notes = self.mr.notes.list(all=True)
|
|
176
|
+
target_note = None
|
|
177
|
+
for note in notes:
|
|
178
|
+
if self.comment_tag in note.body:
|
|
179
|
+
target_note = note
|
|
180
|
+
break
|
|
181
|
+
|
|
182
|
+
if not target_note:
|
|
183
|
+
return False
|
|
184
|
+
|
|
185
|
+
# Fetch award emojis for this note
|
|
186
|
+
# python-gitlab note object usually has 'awardemojis' manager?
|
|
187
|
+
# Or we need to fetch specifically.
|
|
188
|
+
|
|
189
|
+
# Try efficient way first
|
|
190
|
+
# The list() might not include award_emoji info directly.
|
|
191
|
+
|
|
192
|
+
# Using specific API call for the note
|
|
193
|
+
# endpoint: GET /projects/:id/merge_requests/:mr_iid/notes/:note_id/award_emoji
|
|
194
|
+
|
|
195
|
+
# Note: python-gitlab objects are lazy. accessing .awardemojis might work if supported.
|
|
196
|
+
# Let's try standard way
|
|
197
|
+
|
|
198
|
+
awards = target_note.awardemojis.list()
|
|
199
|
+
for award in awards:
|
|
200
|
+
if award.name in ['thumbsup', 'rocket', '+1']:
|
|
201
|
+
return True
|
|
202
|
+
|
|
203
|
+
return False
|
|
204
|
+
|
|
205
|
+
except Exception as e:
|
|
206
|
+
print(f"Warning: Failed to check reaction: {e}")
|
|
207
|
+
return False
|