patchwise 0.2.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.
@@ -0,0 +1,204 @@
1
+ # Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ import argparse
5
+ from getpass import getpass
6
+ import re
7
+ import textwrap
8
+ import os
9
+ import typing as t
10
+ import urllib3
11
+ import litellm, httpx
12
+ urllib3.disable_warnings()
13
+
14
+ from ...patch_review.patch_review import PatchReview
15
+ from ..patch_review import Dependency
16
+
17
+ DEFAULT_MODEL = "Pro"
18
+ DEFAULT_API_BASE = "https://api.openai.com/v1"
19
+ API_KEY_NAME = "OPENAI_API_KEY"
20
+
21
+ def get_api_key(name: str = API_KEY_NAME) -> str:
22
+ """
23
+ Returns the environment variable value, caching it after the first retrieval.
24
+ """
25
+ if not hasattr(get_api_key, name):
26
+ env_var = os.environ.get(name)
27
+ if not env_var:
28
+ try:
29
+ env_var = getpass(f"Please enter your {name}: ").strip()
30
+ except Exception:
31
+ raise RuntimeError(f"{name} is not set and user input failed.")
32
+ if not env_var:
33
+ raise RuntimeError(f"{name} is required but was not provided.")
34
+ setattr(get_api_key, name, env_var)
35
+ return getattr(get_api_key, name)
36
+
37
+ class ModelProviderDependency(Dependency):
38
+ def check(self) -> None:
39
+ get_api_key(self.name) # Ensure the API key is available
40
+
41
+ class AiReview(PatchReview):
42
+ api_key: str
43
+ model: str = DEFAULT_MODEL
44
+ api_base: str = DEFAULT_API_BASE
45
+
46
+ DEPENDENCIES = [ModelProviderDependency("OPENAI_API_KEY")]
47
+
48
+ def format_chat_response(self, text: str) -> str:
49
+ """
50
+ Line wraps the given text at 75 columns but skips commit tags.
51
+ """
52
+ def split_text_into_paragraphs(text: str) -> list[str]:
53
+ """
54
+ Splits the input text into paragraphs, treating each bullet
55
+ point line as a separate paragraph.
56
+ """
57
+ lines = text.split('\n')
58
+ paragraphs = []
59
+ current = []
60
+ bullet_pattern = re.compile(r"""
61
+ ^\s* # Optional leading whitespace
62
+ (
63
+ [*+\->] # Unordered bullet characters
64
+ | # OR
65
+ \d+[.)-] # Numbered bullets like 1. or 2)
66
+ | # OR
67
+ \d+(\.\d+)+ # Decimal bullets like 1.1 or 1.2.3
68
+ )
69
+ \s* # At least one space after the bullet
70
+ """, re.VERBOSE)
71
+
72
+ for line in lines:
73
+ line_stripped = line.strip()
74
+ if line_stripped == '' or line_stripped == '```' \
75
+ or line_stripped == '\'\'\'' or line_stripped == '\"\"\"' \
76
+ or bullet_pattern.match(line_stripped) != None:
77
+ if len(current) > 0:
78
+ paragraphs.append('\n'.join(current))
79
+ current = []
80
+ paragraphs.append(line)
81
+ else:
82
+ current.append(line)
83
+ if len(current) > 0:
84
+ paragraphs.append('\n'.join(current))
85
+
86
+ return paragraphs
87
+
88
+ def is_commit_tag(text: str) -> bool:
89
+ """
90
+ Checks if the given text starts with a commit tag.
91
+ The TAGS list includes tags from the Kernel documentation
92
+ https://www.kernel.org/doc/html/latest/process/submitting-patches.html
93
+ and additional tags like "Change-Id".
94
+ """
95
+ TAGS = {
96
+ # Upstream tags
97
+ "Acked-by:",
98
+ "Cc:",
99
+ "Closes:",
100
+ "Co-developed-by:",
101
+ "Fixes:",
102
+ "From:",
103
+ "Link:",
104
+ "Reported-by:",
105
+ "Reviewed-by:",
106
+ "Signed-off-by:",
107
+ "Suggested-by:",
108
+ "Tested-by:",
109
+
110
+ # Additional tags
111
+ "(cherry picked from commit",
112
+ "Change-Id",
113
+ "Git-Commit:",
114
+ "Git-repo",
115
+ "Git-Repo:",
116
+ }
117
+
118
+ return any(text.startswith(tag) for tag in TAGS)
119
+
120
+ def is_quote(text):
121
+ return text.startswith(">")
122
+
123
+ paragraphs = split_text_into_paragraphs(text)
124
+
125
+ wrapped_paragraphs = [
126
+ textwrap.fill(
127
+ p,
128
+ width=75,
129
+ break_long_words=False, # to preserve links
130
+ ) if not (is_commit_tag(p.strip()) or is_quote(p.strip())) else p \
131
+ for p in paragraphs
132
+ ]
133
+
134
+ return '\n'.join(wrapped_paragraphs)
135
+
136
+ def provider_api_call(
137
+ self,
138
+ user_prompt: str,
139
+ system_prompt: t.Optional[str] = None
140
+ ) -> str:
141
+ messages = [{"content": user_prompt, "role": "user"}]
142
+ if system_prompt:
143
+ messages.append({"content": system_prompt, "role": "system"})
144
+
145
+ self.logger.debug(f"Making API call with model: {self.model}, api_base: {AiReview.api_base}")
146
+
147
+ response = litellm.completion(
148
+ model=self.model,
149
+ api_base=AiReview.api_base,
150
+ messages=messages,
151
+ stream=False,
152
+ )
153
+
154
+ return response.choices[0].message.content
155
+
156
+ def setup(self):
157
+ self.model = AiReview.model
158
+
159
+ os.environ["OTEL_SDK_DISABLED"] = "true"
160
+ os.environ[API_KEY_NAME] = get_api_key(API_KEY_NAME)
161
+
162
+ litellm.client_session = httpx.Client(verify=False)
163
+
164
+ self.diff = self.repo.git.diff(self.base_commit, self.commit).strip()
165
+ if not self.diff:
166
+ self.logger.error("Failed to retrieve diff.")
167
+
168
+ self.commit_message = self.repo.commit(self.commit).message.rstrip()
169
+ if not self.commit_message:
170
+ self.logger.error("Failed to retrieve commit message.")
171
+
172
+ def add_ai_arguments(
173
+ parser_or_group: argparse.ArgumentParser | argparse._ArgumentGroup,
174
+ ):
175
+ parser_or_group.add_argument(
176
+ "--model",
177
+ default=f"openai/{AiReview.model}",
178
+ help="The AI model to use for review. (default: %(default)s)"
179
+ )
180
+ parser_or_group.add_argument(
181
+ "--provider",
182
+ default=DEFAULT_API_BASE,
183
+ help="The base URL for the AI model API. (default: %(default)s)"
184
+ )
185
+ parser_or_group.add_argument(
186
+ "--api-key",
187
+ help=f"The API key for the AI model API. If not provided, it will be read from the environment variable `{API_KEY_NAME}`."
188
+ )
189
+ # parser_or_group.add_argument(
190
+ # "--review-threshold",
191
+ # type=float,
192
+ # default=0.5,
193
+ # help="The threshold for review confidence. (default: %(default)s)"
194
+ # )
195
+
196
+ def apply_ai_args(args: argparse.Namespace) -> None:
197
+ """
198
+ Applies AI-related arguments to the AiReview class.
199
+ This function is called after parsing command line arguments.
200
+ """
201
+ AiReview.model = args.model
202
+ AiReview.api_base = args.provider
203
+ if args.api_key:
204
+ AiReview.api_key = args.api_key
@@ -0,0 +1,60 @@
1
+ # Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ from ...patch_review.decorators import register_llm_review, register_short_review
5
+ from .ai_review import AiReview
6
+
7
+
8
+ @register_llm_review
9
+ @register_short_review
10
+ class LLMCommitAudit(AiReview):
11
+
12
+ DEPENDENCIES = getattr(AiReview, "DEPENDENCIES", [])
13
+
14
+ PROMPT_TEMPLATE = """
15
+ **Prompt:**
16
+ You are an AI language model tasked with evaluating commit text for patches sent to the Linux Kernel. Your goal is to ensure that the commit text adheres to the Linux Kernel's guidelines. Specifically, you should focus on the following areas:
17
+
18
+ Justification of Code Changes: Ensure that the commit text clearly explains why the code changes are necessary.
19
+ Correct Imperative Tense: Verify that the commit text is written in the correct imperative tense.
20
+ Problem Description: Confirm that the commit text sufficiently describes the problem that the code changes aim to address.
21
+ Additionally, your suggestions should avoid making the commit text overly detailed or verbose.
22
+
23
+ **Commit Text:**
24
+
25
+ ```
26
+ {commit_text}
27
+ ```
28
+
29
+ **Patch Details:**
30
+
31
+ ```
32
+ {diff}
33
+ ```
34
+
35
+ **Output:**
36
+
37
+ The format of the output should be as follows:
38
+ - A short review.
39
+ - Rewrite the commit text in imperative mode as needed and incorporates suggestions.
40
+ - Briefly describe the changes made to the commit text.
41
+ - A list of suggestions the author can take to make the commit text even better after incorporating your revisions.
42
+ Do not provide a rating.
43
+ The output should use only ASCII characters.
44
+ """
45
+
46
+ def setup(self) -> None:
47
+ super().setup()
48
+
49
+ def run(self) -> str:
50
+ formatted_prompt = LLMCommitAudit.PROMPT_TEMPLATE.format(
51
+ diff=self.diff,
52
+ commit_text=str(self.commit_message),
53
+ )
54
+
55
+ result = self.provider_api_call(
56
+ formatted_prompt,
57
+ self.model,
58
+ )
59
+
60
+ return self.format_chat_response(result)
@@ -0,0 +1,50 @@
1
+ # Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ from typing import Type, List, Any
5
+ from .static_analysis.static_analysis import StaticAnalysis
6
+ from .ai_review.ai_review import AiReview
7
+ from .patch_review import PatchReview
8
+
9
+
10
+ # Registries for different review types
11
+ AVAILABLE_PATCH_REVIEWS: List[Type[PatchReview]] = []
12
+ LLM_REVIEWS: List[Type[AiReview]] = []
13
+ STATIC_ANALYSIS_REVIEWS: List[Type[StaticAnalysis]] = []
14
+ SHORT_REVIEWS: List[Type[PatchReview]] = []
15
+ LONG_REVIEWS: List[Type[PatchReview]] = []
16
+
17
+
18
+ # Decorators for each review type
19
+ def register_patch_review(cls: Type[Any]) -> Type[Any]:
20
+ if cls not in AVAILABLE_PATCH_REVIEWS:
21
+ AVAILABLE_PATCH_REVIEWS.append(cls)
22
+ return cls
23
+
24
+
25
+ def register_llm_review(cls: Type[Any]) -> Type[Any]:
26
+ if cls not in LLM_REVIEWS:
27
+ LLM_REVIEWS.append(cls)
28
+ register_patch_review(cls)
29
+ return cls
30
+
31
+
32
+ def register_static_analysis_review(cls: Type[Any]) -> Type[Any]:
33
+ if cls not in STATIC_ANALYSIS_REVIEWS:
34
+ STATIC_ANALYSIS_REVIEWS.append(cls)
35
+ register_patch_review(cls)
36
+ return cls
37
+
38
+
39
+ def register_short_review(cls: Type[Any]) -> Type[Any]:
40
+ if cls not in SHORT_REVIEWS:
41
+ SHORT_REVIEWS.append(cls)
42
+ register_patch_review(cls)
43
+ return cls
44
+
45
+
46
+ def register_long_review(cls: Type[Any]) -> Type[Any]:
47
+ if cls not in LONG_REVIEWS:
48
+ LONG_REVIEWS.append(cls)
49
+ register_patch_review(cls)
50
+ return cls
@@ -0,0 +1,122 @@
1
+ # Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ from git import Repo, RemoteProgress, GitCommandError
5
+ from pathlib import Path
6
+ import logging
7
+ import shutil
8
+ from tqdm import tqdm
9
+ from .. import KERNEL_PATH, PACKAGE_NAME
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ BRANCH_NAME = f"{PACKAGE_NAME}-linux-next-stable"
15
+
16
+ class TqdmFetchProgress(RemoteProgress):
17
+ def __init__(self):
18
+ super().__init__()
19
+ self.pbar = None
20
+
21
+ def update(self, op_code, cur_count, max_count=None, message=''):
22
+ if max_count:
23
+ if self.pbar is None:
24
+ self.pbar = tqdm(
25
+ total=max_count,
26
+ unit="obj",
27
+ desc="Fetching",
28
+ leave=True,
29
+ colour="green",
30
+ )
31
+ self.pbar.n = cur_count
32
+ self.pbar.refresh()
33
+ if cur_count >= max_count:
34
+ self.pbar.close()
35
+ self.pbar = None
36
+ else:
37
+ pass
38
+ elif self.pbar is None:
39
+ self.pbar = tqdm(
40
+ unit="obj",
41
+ desc="Fetching",
42
+ leave=True,
43
+ colour="green",
44
+ )
45
+ self.pbar.n = cur_count
46
+ self.pbar.refresh()
47
+ else:
48
+ pass
49
+
50
+
51
+ def fetch_and_branch(repo: Repo) -> None:
52
+ git_url = "git://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git"
53
+ http_url = "https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git"
54
+
55
+ if PACKAGE_NAME not in [remote.name for remote in repo.remotes]:
56
+ repo.create_remote(PACKAGE_NAME, git_url)
57
+ try:
58
+ repo.remotes[PACKAGE_NAME].set_url(git_url)
59
+ repo.remotes[PACKAGE_NAME].fetch("stable", progress=TqdmFetchProgress())
60
+ except GitCommandError as git_error:
61
+ logger.warning("git: Failed, trying https:")
62
+ repo.remotes[PACKAGE_NAME].set_url(http_url)
63
+ try:
64
+ repo.remotes[PACKAGE_NAME].fetch("stable", progress=TqdmFetchProgress())
65
+ except GitCommandError as http_error:
66
+ logger.error("https: Failed, exiting...")
67
+ raise
68
+
69
+ # Force-create the branch at FETCH_HEAD, do not check it out
70
+ repo.git.branch('-f', BRANCH_NAME, 'FETCH_HEAD')
71
+
72
+ def init_kernel_tree(path: Path = KERNEL_PATH) -> Repo:
73
+
74
+ path.mkdir(parents=True, exist_ok=True)
75
+
76
+ repo = Repo.init(path)
77
+
78
+ fetch_and_branch(repo)
79
+
80
+ return repo
81
+
82
+ def create_git_worktree(repo: Repo, branch_name: str = BRANCH_NAME, worktree_path: Path = KERNEL_PATH):
83
+ """
84
+ Create a new git worktree at worktree_path from repo_path using branch_name.
85
+ If the worktree already exists at worktree_path, do nothing (reentrant).
86
+ """
87
+ # Prune worktrees first
88
+ try:
89
+ repo.git.worktree("prune")
90
+ except GitCommandError as e:
91
+ logger.warning(f"Could not prune worktrees: {e}")
92
+
93
+ fetch_and_branch(repo)
94
+
95
+ # Check if the path exists and if it's a worktree
96
+ if worktree_path.exists():
97
+ is_worktree = False
98
+ try:
99
+ worktrees = repo.git.worktree("list", "--porcelain").split("\n")
100
+ for line in worktrees:
101
+ if line.startswith("worktree "):
102
+ wt_path = line.split(" ", 1)[1].strip()
103
+ if Path(wt_path).resolve() == worktree_path.resolve():
104
+ is_worktree = True
105
+ break
106
+ except GitCommandError as e:
107
+ logger.warning(f"Could not list worktrees: {e}")
108
+
109
+ if is_worktree:
110
+ logger.info(f"Worktree already exists at {worktree_path}")
111
+ return
112
+ else:
113
+ logger.info(f"Directory {worktree_path} exists but is not a worktree, removing it.")
114
+ shutil.rmtree(worktree_path)
115
+
116
+ # Create the worktree
117
+ try:
118
+ repo.git.worktree("add", str(worktree_path), branch_name)
119
+ logger.info(f"Created worktree at {worktree_path} for branch {branch_name}")
120
+ except GitCommandError as e:
121
+ logger.error(f"Failed to create worktree: {e}")
122
+ raise