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.
patchwise/__init__.py ADDED
@@ -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
patchwise/main.py ADDED
@@ -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
@@ -0,0 +1,2 @@
1
+ # Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
2
+ # SPDX-License-Identifier: BSD-3-Clause