patchwise 0.2.0__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.
- patchwise-0.2.0/LICENSE.txt +26 -0
- patchwise-0.2.0/PKG-INFO +19 -0
- patchwise-0.2.0/README.md +185 -0
- patchwise-0.2.0/patchwise/__init__.py +18 -0
- patchwise-0.2.0/patchwise/logger_setup.py +81 -0
- patchwise-0.2.0/patchwise/main.py +101 -0
- patchwise-0.2.0/patchwise/patch_review/__init__.py +171 -0
- patchwise-0.2.0/patchwise/patch_review/ai_review/__init__.py +2 -0
- patchwise-0.2.0/patchwise/patch_review/ai_review/ai_code_review.py +965 -0
- patchwise-0.2.0/patchwise/patch_review/ai_review/ai_review.py +204 -0
- patchwise-0.2.0/patchwise/patch_review/ai_review/llm_commit_audit.py +60 -0
- patchwise-0.2.0/patchwise/patch_review/decorators.py +50 -0
- patchwise-0.2.0/patchwise/patch_review/kernel_tree.py +122 -0
- patchwise-0.2.0/patchwise/patch_review/patch_review.py +317 -0
- patchwise-0.2.0/patchwise/patch_review/static_analysis/__init__.py +2 -0
- patchwise-0.2.0/patchwise/patch_review/static_analysis/checkpatch.py +48 -0
- patchwise-0.2.0/patchwise/patch_review/static_analysis/coccicheck.py +81 -0
- patchwise-0.2.0/patchwise/patch_review/static_analysis/dt_check.py +130 -0
- patchwise-0.2.0/patchwise/patch_review/static_analysis/dtbs_check.py +85 -0
- patchwise-0.2.0/patchwise/patch_review/static_analysis/sparse.py +150 -0
- patchwise-0.2.0/patchwise/patch_review/static_analysis/static_analysis.py +48 -0
- patchwise-0.2.0/patchwise.egg-info/PKG-INFO +19 -0
- patchwise-0.2.0/patchwise.egg-info/SOURCES.txt +27 -0
- patchwise-0.2.0/patchwise.egg-info/dependency_links.txt +1 -0
- patchwise-0.2.0/patchwise.egg-info/entry_points.txt +2 -0
- patchwise-0.2.0/patchwise.egg-info/requires.txt +11 -0
- patchwise-0.2.0/patchwise.egg-info/top_level.txt +1 -0
- patchwise-0.2.0/pyproject.toml +33 -0
- patchwise-0.2.0/setup.cfg +4 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
|
|
2
|
+
|
|
3
|
+
Redistribution and use in source and binary forms, with or without
|
|
4
|
+
modification, are permitted provided that the following conditions are
|
|
5
|
+
met:
|
|
6
|
+
* Redistributions of source code must retain the above copyright
|
|
7
|
+
notice, this list of conditions and the following disclaimer.
|
|
8
|
+
* Redistributions in binary form must reproduce the above
|
|
9
|
+
copyright notice, this list of conditions and the following
|
|
10
|
+
disclaimer in the documentation and/or other materials provided
|
|
11
|
+
with the distribution.
|
|
12
|
+
* Neither the name of the copyright holder nor the names of its
|
|
13
|
+
contributors may be used to endorse or promote products derived
|
|
14
|
+
from this software without specific prior written permission.
|
|
15
|
+
|
|
16
|
+
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
|
|
17
|
+
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
|
18
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
|
|
19
|
+
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
|
|
20
|
+
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
21
|
+
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
22
|
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
|
23
|
+
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
|
24
|
+
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
|
25
|
+
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
|
|
26
|
+
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
patchwise-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: patchwise
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A tool for reviewing kernel patches
|
|
5
|
+
Author-email: David Gantman <dgantman@quicinc.com>
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
License-File: LICENSE.txt
|
|
8
|
+
Requires-Dist: Sphinx>=8.1.3
|
|
9
|
+
Requires-Dist: litellm>=1.41.1
|
|
10
|
+
Requires-Dist: cachetools>=5.5.2
|
|
11
|
+
Requires-Dist: dtschema>=2025.2
|
|
12
|
+
Requires-Dist: yamllint>=1.26.3
|
|
13
|
+
Requires-Dist: ply>=3.11
|
|
14
|
+
Requires-Dist: GitPython>=3.1.44
|
|
15
|
+
Requires-Dist: codespell>=2.4.1
|
|
16
|
+
Requires-Dist: pytest>=8.3.5
|
|
17
|
+
Requires-Dist: rich-argparse>=1.7.0
|
|
18
|
+
Requires-Dist: tqdm>=4.67.1
|
|
19
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
# PatchWise
|
|
2
|
+
|
|
3
|
+
<!-- [](LICENSE) -->
|
|
4
|
+
[](https://www.python.org/downloads/)
|
|
5
|
+
<!-- [](#) -->
|
|
6
|
+
|
|
7
|
+
> **PatchWise** automates patch review and static analysis for the Linux kernel, streamlining upstream contributions and ensuring code quality.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Table of Contents
|
|
12
|
+
|
|
13
|
+
- [Features](#features)
|
|
14
|
+
- [Getting Started](#getting-started)
|
|
15
|
+
- [Prerequisites](#prerequisites)
|
|
16
|
+
- [Installation](#installation)
|
|
17
|
+
- [Usage](#usage)
|
|
18
|
+
- [Command-Line Options](#command-line-options)
|
|
19
|
+
- [Development](#development)
|
|
20
|
+
- [Contact](#getting-in-contact)
|
|
21
|
+
- [License](#license)
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Features
|
|
26
|
+
|
|
27
|
+
- **Automated Patch Review**: Runs static analysis and style checks on kernel patches.
|
|
28
|
+
- **Integration with Mailing Lists**: Processes patches sent via email and responds automatically.
|
|
29
|
+
- **Flexible Review Selection**: Choose which review checks to run.
|
|
30
|
+
- **Rich Logging**: Colorized and file-based logging for easy debugging.
|
|
31
|
+
- **LLM Integration**: Uses Artificial Intelligence for commit message analysis and suggestions.
|
|
32
|
+
- **AI Code Review**: Leverages artificial intelligence to provide insights on code quality and potential issues. Integrated with Language Server Protocol (LSP) for context-aware code review. Support for multiple LLMs and providers, including OpenAI.
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## Getting Started
|
|
37
|
+
|
|
38
|
+
### Prerequisites
|
|
39
|
+
|
|
40
|
+
- Python 3.10 or newer
|
|
41
|
+
- Access to a Linux kernel git repository
|
|
42
|
+
|
|
43
|
+
### Installation
|
|
44
|
+
|
|
45
|
+
1. **Clone the repository:**
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
git clone https://github.com/qualcomm/PatchWise.git
|
|
49
|
+
cd PatchWise
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
1. **Create and activate a virtual environment:**
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
python3.10 -m venv .venv
|
|
56
|
+
source .venv/bin/activate
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
1. **Install dependencies:**
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
pip install .
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
1. **Set up your API key:**
|
|
66
|
+
|
|
67
|
+
Obtain your API key from your provider and set it as an environment variable:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
export OPENAI_API_KEY=<your-api-key>
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Add this line to your shell profile (e.g., `~/.bashrc` or `~/.zshrc`) for persistence.
|
|
74
|
+
|
|
75
|
+
1. **Run help message:**
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
patchwise --help
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Usage
|
|
82
|
+
|
|
83
|
+
1. **Run PatchWise:**
|
|
84
|
+
|
|
85
|
+
Run PatchWise in the root of your kernel workspace:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
patchwise
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
By default, PatchWise will review the `HEAD` commit. Use the `--commits` flag to review a specific commit:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
patchwise --commits <commit-sha>
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
To run only short reviews, use:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
patchwise --short-reviews
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
To run specific reviews, use the `--reviews` flag:
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
patchwise --reviews checkpatch dt_checker
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
To see available reviews and other options, run:
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
patchwise --help
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Example Workflow
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
# Replace with a path on your system where you would like to download patchwise
|
|
119
|
+
cd /local/mnt/workspace/dgantman/kernel-tools
|
|
120
|
+
|
|
121
|
+
### Clone the repository
|
|
122
|
+
git clone https://github.com/qualcomm/PatchWise.git
|
|
123
|
+
cd /local/mnt/workspace/dgantman/kernel-tools/PatchWise
|
|
124
|
+
|
|
125
|
+
### Create and activate a virtual environment
|
|
126
|
+
python3.10 -m venv .venv
|
|
127
|
+
# Required every time you start a new shell session
|
|
128
|
+
source /local/mnt/workspace/dgantman/kernel-tools/PatchWise/.venv/bin/activate
|
|
129
|
+
# Required every time you update the codebase
|
|
130
|
+
pip install /local/mnt/workspace/dgantman/kernel-tools/PatchWise
|
|
131
|
+
# Required every time you start a new shell session
|
|
132
|
+
# unless you've added it to your shell profile (e.g., ~/.bashrc or ~/.zshrc)
|
|
133
|
+
# You can find your API key from your provider
|
|
134
|
+
export OPENAI_API_KEY=<your-api-key>
|
|
135
|
+
|
|
136
|
+
### Run PatchWise in your kernel workspace that has the patch you want to review already applied
|
|
137
|
+
cd /local/mnt/workspace/dgantman/linux-next
|
|
138
|
+
patchwise --all-reviews
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## Command-Line Options
|
|
144
|
+
|
|
145
|
+
- `-h`, `--help`: Show help message and exit
|
|
146
|
+
|
|
147
|
+
### Patch Review Options
|
|
148
|
+
|
|
149
|
+
- `--commits`: Space separated list of commit SHAs/refs, or a single commit range in start..end format. (default: [`HEAD`])
|
|
150
|
+
- `--repo-path`: Path to the kernel workspace root. Uses your current directory if not specified. (default: `$PWD`)
|
|
151
|
+
- `--reviews`: Space-separated list of reviews to run. (default: all available reviews)
|
|
152
|
+
- `--short-reviews`: Run only short reviews. Overrides `--reviews`.
|
|
153
|
+
- `--install`: Install missing dependencies for the specified reviews. This will not run any reviews, only install dependencies.
|
|
154
|
+
|
|
155
|
+
### Ai Review Options
|
|
156
|
+
|
|
157
|
+
- `--model`: Specify the AI model to use for code review. (default: `openai/Pro`).
|
|
158
|
+
- `--provider`: The base URL for the AI model API. (default: `https://api.openai.com/v1`)
|
|
159
|
+
- `--api-key`: The API key for the AI model API. If not provided, it will be read from the `OPENAI_API_KEY` environment variable.
|
|
160
|
+
|
|
161
|
+
### Logging Options
|
|
162
|
+
|
|
163
|
+
- `--log-level`: Set the logging level. (default: `INFO`)
|
|
164
|
+
- `--log-file`: Path to the log file (default: `<package_path>/sandbox/patchwise.log`)
|
|
165
|
+
|
|
166
|
+
## Development
|
|
167
|
+
|
|
168
|
+
If you'd like to develop new features or fix existing issues:
|
|
169
|
+
|
|
170
|
+
- Fork the repository and create a new branch for your changes.
|
|
171
|
+
- Make your changes with clear, descriptive commit messages.
|
|
172
|
+
- Ensure your code follows the project's coding standards and passes all tests.
|
|
173
|
+
- Submit a pull request (PR) with a detailed description of your changes to pull your changes into the staging branch in the main repository.
|
|
174
|
+
|
|
175
|
+
Please make sure to follow our contribution guidelines before submitting a pull request. [CONTRIBUTING.md](CONTRIBUTING.md)
|
|
176
|
+
|
|
177
|
+
## Getting in Contact
|
|
178
|
+
|
|
179
|
+
- [Report an Issue on GitHub](../../issues/new/choose)
|
|
180
|
+
- [Open a Discussion on GitHub](../../discussions/new/choose)
|
|
181
|
+
- [E-mail us](mailto:dgantman@quicinc.com) for general questions
|
|
182
|
+
|
|
183
|
+
## License
|
|
184
|
+
|
|
185
|
+
PatchWise is licensed under the BSD-3-clause License. See [LICENSE.txt](LICENSE.txt) for the full license text.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
|
|
2
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
# Get the path of the patchwise package
|
|
7
|
+
PACKAGE_PATH = Path(__file__).resolve().parent
|
|
8
|
+
|
|
9
|
+
PACKAGE_NAME = __name__.split('.')[0]
|
|
10
|
+
|
|
11
|
+
# Define the sandbox/workspace path relative to the package location
|
|
12
|
+
SANDBOX_PATH = PACKAGE_PATH / "sandbox"
|
|
13
|
+
SANDBOX_BIN = SANDBOX_PATH / "bin"
|
|
14
|
+
# Define the kernel workspace path
|
|
15
|
+
KERNEL_PATH = SANDBOX_PATH / "kernel"
|
|
16
|
+
|
|
17
|
+
# Ensure the sandbox directory exists
|
|
18
|
+
SANDBOX_PATH.mkdir(parents=True, exist_ok=True)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
|
|
2
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
from patchwise import SANDBOX_PATH
|
|
9
|
+
|
|
10
|
+
LOG_PATH = os.path.join(SANDBOX_PATH, f"{__name__.split('.')[0]}.log")
|
|
11
|
+
|
|
12
|
+
# === Global logging config ===
|
|
13
|
+
ENABLE_LOG_COLORS = True # Set to False to disable colored logs in the stream handler
|
|
14
|
+
FILE_HANDLER_LOG_LEVEL = logging.DEBUG # Default log level for file handler
|
|
15
|
+
|
|
16
|
+
# ANSI color codes
|
|
17
|
+
RESET = "\033[0m"
|
|
18
|
+
CYAN = "\033[36m"
|
|
19
|
+
YELLOW = "\033[33m"
|
|
20
|
+
RED = "\033[31m"
|
|
21
|
+
GRAY = "\033[232m"
|
|
22
|
+
BOLD = "\033[1m"
|
|
23
|
+
|
|
24
|
+
class ColorFormatter(logging.Formatter):
|
|
25
|
+
def format(self, record):
|
|
26
|
+
msg = super().format(record)
|
|
27
|
+
if not ENABLE_LOG_COLORS:
|
|
28
|
+
return msg
|
|
29
|
+
|
|
30
|
+
# Color everything up to and including the first ": "
|
|
31
|
+
split_idx = msg.find(": ")
|
|
32
|
+
if split_idx != -1:
|
|
33
|
+
header = msg[:split_idx + 2]
|
|
34
|
+
message = msg[split_idx + 2 :]
|
|
35
|
+
else:
|
|
36
|
+
return msg
|
|
37
|
+
|
|
38
|
+
if record.levelno >= logging.ERROR:
|
|
39
|
+
return f"{BOLD}{RED}{header}{message}{RESET}"
|
|
40
|
+
elif record.levelno == logging.WARNING:
|
|
41
|
+
return f"{BOLD}{YELLOW}{header}{message}{RESET}"
|
|
42
|
+
elif record.levelno in (logging.INFO, logging.DEBUG):
|
|
43
|
+
return f"{CYAN}{header}{RESET}{message}"
|
|
44
|
+
|
|
45
|
+
else:
|
|
46
|
+
return msg
|
|
47
|
+
|
|
48
|
+
def setup_logger(
|
|
49
|
+
log_file: str = LOG_PATH, log_level: str = "INFO"
|
|
50
|
+
):
|
|
51
|
+
"""
|
|
52
|
+
Sets up the logger with the specified log file and log level.
|
|
53
|
+
"""
|
|
54
|
+
format = "%(asctime)s %(levelname).1s %(name)s %(filename)s#%(lineno)d: %(message)s"
|
|
55
|
+
file_handler = logging.FileHandler(log_file, mode="w")
|
|
56
|
+
file_handler.setLevel(FILE_HANDLER_LOG_LEVEL) # Use global default
|
|
57
|
+
file_handler.setFormatter(logging.Formatter(format, datefmt="%H:%M:%S"))
|
|
58
|
+
stream_handler = logging.StreamHandler()
|
|
59
|
+
stream_handler.setFormatter(ColorFormatter(format, datefmt="%H:%M:%S"))
|
|
60
|
+
# Set stream_handler level based on user input
|
|
61
|
+
stream_handler.setLevel(log_level)
|
|
62
|
+
logging.basicConfig(
|
|
63
|
+
level=logging.ERROR,
|
|
64
|
+
handlers=[file_handler, stream_handler],
|
|
65
|
+
)
|
|
66
|
+
logging.getLogger(__name__.split(".")[0]).setLevel(log_level)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def add_logging_arguments(parser_or_group: argparse.ArgumentParser | argparse._ArgumentGroup):
|
|
70
|
+
parser_or_group.add_argument(
|
|
71
|
+
"--log-level",
|
|
72
|
+
choices=("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"),
|
|
73
|
+
default="INFO",
|
|
74
|
+
help="Set the logging level. (default: %(default)s)"
|
|
75
|
+
)
|
|
76
|
+
parser_or_group.add_argument(
|
|
77
|
+
"--log-file",
|
|
78
|
+
default=LOG_PATH,
|
|
79
|
+
help="Path to the log file. (default: %(default)s)",
|
|
80
|
+
)
|
|
81
|
+
return parser_or_group
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
|
|
2
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from git import Repo
|
|
8
|
+
from git.objects.commit import Commit
|
|
9
|
+
from rich_argparse import RichHelpFormatter
|
|
10
|
+
|
|
11
|
+
from .logger_setup import setup_logger, add_logging_arguments
|
|
12
|
+
from .patch_review.kernel_tree import create_git_worktree
|
|
13
|
+
from .patch_review.patch_review import PATCH_PATH
|
|
14
|
+
from .patch_review import review_patch, add_review_arguments, get_selected_reviews_from_args, install_missing_dependencies
|
|
15
|
+
from .patch_review.ai_review.ai_review import add_ai_arguments, apply_ai_args
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def parse_args() -> argparse.Namespace:
|
|
22
|
+
parser = argparse.ArgumentParser(
|
|
23
|
+
formatter_class=RichHelpFormatter
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
review_group = parser.add_argument_group("Patch Review Options")
|
|
27
|
+
|
|
28
|
+
review_group.add_argument(
|
|
29
|
+
"--commits",
|
|
30
|
+
nargs="*",
|
|
31
|
+
default=["HEAD"],
|
|
32
|
+
help="Space separated list of commit SHAs/refs, or a single commit range in start..end format. (default: %(default)s)"
|
|
33
|
+
)
|
|
34
|
+
review_group.add_argument(
|
|
35
|
+
"--repo-path",
|
|
36
|
+
default=str(Path.cwd()),
|
|
37
|
+
help="Path to the kernel workspace containing the patch(es) to review. Uses CWD if not specified. (default: %(default)s)",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
add_review_arguments(review_group)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
ai_group = parser.add_argument_group("AI Review Options")
|
|
44
|
+
add_ai_arguments(ai_group)
|
|
45
|
+
|
|
46
|
+
logging_group = parser.add_argument_group("Logging Options")
|
|
47
|
+
add_logging_arguments(logging_group)
|
|
48
|
+
|
|
49
|
+
return parser.parse_args()
|
|
50
|
+
|
|
51
|
+
def get_patches(repo: Repo, commits: list[Commit]):
|
|
52
|
+
dest_dir = PATCH_PATH / "user"
|
|
53
|
+
dest_dir.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
for idx, commit in enumerate(commits, 1):
|
|
55
|
+
patch_file = dest_dir / f"{idx:04d}-{commit}.patch"
|
|
56
|
+
diff = repo.git.format_patch(f"-1", commit, stdout=True)
|
|
57
|
+
logger.debug(f"Writing patch for commit {commit} to {patch_file}")
|
|
58
|
+
patch_file.write_text(diff)
|
|
59
|
+
|
|
60
|
+
def get_commits(repo: Repo, commits: list[str]) -> list[Commit]:
|
|
61
|
+
"""
|
|
62
|
+
Given a repo and a list of commit refs or a commit range, return a list of Commit objects.
|
|
63
|
+
- If commits is a list of refs (e.g., ["HEAD", "abc123"]) return those commits.
|
|
64
|
+
- If commits is a single string in range format (e.g., "sha1..sha2"), return all commits in that range (inclusive of sha1, exclusive of sha2, like git log).
|
|
65
|
+
"""
|
|
66
|
+
if isinstance(commits, str):
|
|
67
|
+
commits = [commits]
|
|
68
|
+
if len(commits) == 1 and ".." in commits[0]:
|
|
69
|
+
# Range mode
|
|
70
|
+
commit_range = commits[0]
|
|
71
|
+
# git rev-list returns commits in reverse chronological order
|
|
72
|
+
commit_shas = list(repo.git.rev_list(commit_range).splitlines())
|
|
73
|
+
return [repo.commit(sha) for sha in commit_shas]
|
|
74
|
+
else:
|
|
75
|
+
# List of refs/SHAs
|
|
76
|
+
return [repo.commit(ref) for ref in commits]
|
|
77
|
+
|
|
78
|
+
def main():
|
|
79
|
+
|
|
80
|
+
args = parse_args()
|
|
81
|
+
|
|
82
|
+
setup_logger(log_file=args.log_file, log_level=args.log_level)
|
|
83
|
+
|
|
84
|
+
apply_ai_args(args)
|
|
85
|
+
|
|
86
|
+
reviews = get_selected_reviews_from_args(args)
|
|
87
|
+
|
|
88
|
+
if args.install:
|
|
89
|
+
install_missing_dependencies(reviews)
|
|
90
|
+
return
|
|
91
|
+
|
|
92
|
+
repo = Repo(args.repo_path)
|
|
93
|
+
commits = get_commits(repo, args.commits)
|
|
94
|
+
create_git_worktree(repo)
|
|
95
|
+
|
|
96
|
+
for commit in commits:
|
|
97
|
+
logger.info(f"Reviewing commit {commit.hexsha}...")
|
|
98
|
+
review_patch(reviews, commit)
|
|
99
|
+
|
|
100
|
+
if __name__ == "__main__":
|
|
101
|
+
main()
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
|
|
2
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Iterable
|
|
7
|
+
from git.objects.commit import Commit
|
|
8
|
+
# Automatically import all patch review modules so all @register_patch_review classes are registered
|
|
9
|
+
import importlib
|
|
10
|
+
import pkgutil
|
|
11
|
+
from . import static_analysis, ai_review
|
|
12
|
+
|
|
13
|
+
# Import all modules in static_analysis subpackage
|
|
14
|
+
for _, modname, ispkg in pkgutil.iter_modules(static_analysis.__path__):
|
|
15
|
+
if not ispkg:
|
|
16
|
+
importlib.import_module(f"{__name__}.static_analysis.{modname}")
|
|
17
|
+
|
|
18
|
+
# Import all modules in ai_review subpackage
|
|
19
|
+
for _, modname, ispkg in pkgutil.iter_modules(ai_review.__path__):
|
|
20
|
+
if not ispkg:
|
|
21
|
+
importlib.import_module(f"{__name__}.ai_review.{modname}")
|
|
22
|
+
|
|
23
|
+
from ..patch_review.decorators import (
|
|
24
|
+
AVAILABLE_PATCH_REVIEWS,
|
|
25
|
+
LLM_REVIEWS,
|
|
26
|
+
STATIC_ANALYSIS_REVIEWS,
|
|
27
|
+
SHORT_REVIEWS,
|
|
28
|
+
LONG_REVIEWS,
|
|
29
|
+
)
|
|
30
|
+
from .patch_review import PatchReview
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
class PatchReviewResults:
|
|
36
|
+
def __init__(self, commit: Commit):
|
|
37
|
+
self.commit = commit
|
|
38
|
+
self.results: dict[str, str] = {}
|
|
39
|
+
|
|
40
|
+
def __repr__(self):
|
|
41
|
+
return f"PatchReviewResults(commit={self.commit}, results={self.results})"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def run_patch_review(
|
|
45
|
+
selected_reviews: list[type[PatchReview]], commit: Commit
|
|
46
|
+
) -> PatchReviewResults:
|
|
47
|
+
output = PatchReviewResults(commit)
|
|
48
|
+
|
|
49
|
+
for selected_review in selected_reviews:
|
|
50
|
+
logger.debug(f"Initializing review: {selected_review.__name__}")
|
|
51
|
+
cur_review = selected_review(commit)
|
|
52
|
+
|
|
53
|
+
logger.debug(f"Running review: {selected_review.__name__}")
|
|
54
|
+
result = cur_review.run()
|
|
55
|
+
if result:
|
|
56
|
+
logger.info(f"{selected_review.__name__} result:\n{result}")
|
|
57
|
+
else:
|
|
58
|
+
logger.info(f"{selected_review.__name__} found no issues")
|
|
59
|
+
|
|
60
|
+
output.results[selected_review.__name__] = result
|
|
61
|
+
|
|
62
|
+
return output
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def review_patch(reviews: set[str], commit: Commit) -> PatchReviewResults:
|
|
66
|
+
|
|
67
|
+
all_reviews = {cls.__name__: cls for cls in AVAILABLE_PATCH_REVIEWS}
|
|
68
|
+
selected_reviews = [
|
|
69
|
+
all_reviews[name] for name in reviews if name in all_reviews
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
for review_cls in selected_reviews:
|
|
73
|
+
logger.debug(f"Verifying dependencies for: {review_cls.__name__}")
|
|
74
|
+
review_cls.verify_dependencies()
|
|
75
|
+
|
|
76
|
+
results = run_patch_review(selected_reviews, commit)
|
|
77
|
+
|
|
78
|
+
return results
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def install_missing_dependencies(reviews: set[str]) -> None:
|
|
82
|
+
"""
|
|
83
|
+
Install missing dependencies for the specified reviews.
|
|
84
|
+
"""
|
|
85
|
+
all_reviews = {cls.__name__: cls for cls in AVAILABLE_PATCH_REVIEWS}
|
|
86
|
+
selected_reviews = [
|
|
87
|
+
all_reviews[name] for name in reviews if name in all_reviews
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
for review_cls in selected_reviews:
|
|
91
|
+
logger.info(f"Installing dependencies for: {review_cls.__name__}")
|
|
92
|
+
review_cls.verify_dependencies(install=True)
|
|
93
|
+
|
|
94
|
+
logger.info("All specified reviews' dependencies are installed.")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _review_list_str(reviews: Iterable[type[PatchReview]]):
|
|
98
|
+
"""Helper to format review names for help messages"""
|
|
99
|
+
return ", ".join(sorted({cls.__name__ for cls in reviews})) or "(none)"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def add_review_arguments(
|
|
103
|
+
parser_or_group: argparse.ArgumentParser | argparse._ArgumentGroup,
|
|
104
|
+
):
|
|
105
|
+
# Case-insensitive review name handling
|
|
106
|
+
available_review_names = {
|
|
107
|
+
cls.__name__.lower(): cls.__name__ for cls in AVAILABLE_PATCH_REVIEWS
|
|
108
|
+
}
|
|
109
|
+
# For display in help messages
|
|
110
|
+
available_review_choices = sorted([cls.__name__ for cls in AVAILABLE_PATCH_REVIEWS])
|
|
111
|
+
|
|
112
|
+
def _case_insensitive_review(review_name: str) -> str:
|
|
113
|
+
lower_name = review_name.lower()
|
|
114
|
+
if lower_name not in available_review_names:
|
|
115
|
+
# This error message is more consistent with argparse's default
|
|
116
|
+
raise argparse.ArgumentTypeError(
|
|
117
|
+
f"invalid choice: '{review_name}' (choose from {', '.join(available_review_choices)})"
|
|
118
|
+
)
|
|
119
|
+
return available_review_names[lower_name]
|
|
120
|
+
|
|
121
|
+
parser_or_group.add_argument(
|
|
122
|
+
"--reviews",
|
|
123
|
+
nargs="+",
|
|
124
|
+
type=_case_insensitive_review,
|
|
125
|
+
choices=available_review_choices,
|
|
126
|
+
default=available_review_choices,
|
|
127
|
+
help="Space-separated list of reviews to run. (default: %(default)s)",
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
# TODO perhaps add a "fast" mode for reviews that would otherwise take a long time
|
|
131
|
+
parser_or_group.add_argument(
|
|
132
|
+
"--short-reviews",
|
|
133
|
+
action="store_true",
|
|
134
|
+
help=f"Run only short reviews: [`{_review_list_str(SHORT_REVIEWS)}`]. Overrides --reviews.",
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
parser_or_group.add_argument(
|
|
138
|
+
"--install",
|
|
139
|
+
action="store_true",
|
|
140
|
+
help="Install missing dependencies for the specified reviews. This will not run any reviews, only install dependencies.",
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
return parser_or_group
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def get_selected_reviews_from_args(args: argparse.Namespace) -> set[str]:
|
|
147
|
+
"""
|
|
148
|
+
Given parsed args, return the set of review class names to run.
|
|
149
|
+
This logic is shared by all entry points.
|
|
150
|
+
"""
|
|
151
|
+
group_sets: list[set[str]] = []
|
|
152
|
+
if getattr(args, "all_reviews", False):
|
|
153
|
+
group_sets.append(set(cls.__name__ for cls in AVAILABLE_PATCH_REVIEWS))
|
|
154
|
+
if getattr(args, "llm_reviews", False):
|
|
155
|
+
group_sets.append(set(cls.__name__ for cls in LLM_REVIEWS))
|
|
156
|
+
if getattr(args, "static_analysis_reviews", False):
|
|
157
|
+
group_sets.append(set(cls.__name__ for cls in STATIC_ANALYSIS_REVIEWS))
|
|
158
|
+
if getattr(args, "short_reviews", False):
|
|
159
|
+
group_sets.append(set(cls.__name__ for cls in SHORT_REVIEWS))
|
|
160
|
+
if getattr(args, "long_reviews", False):
|
|
161
|
+
group_sets.append(set(cls.__name__ for cls in LONG_REVIEWS))
|
|
162
|
+
|
|
163
|
+
explicit_reviews: set[str] = (
|
|
164
|
+
set(args.reviews) if hasattr(args, "reviews") and args.reviews else set()
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
if group_sets:
|
|
168
|
+
return set().union(*group_sets)
|
|
169
|
+
else:
|
|
170
|
+
# Default: all reviews
|
|
171
|
+
return explicit_reviews
|