gitlab-watcher 1.0.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,444 @@
1
+ """Issue and MR processing logic."""
2
+
3
+ import logging
4
+ import re
5
+ import shlex
6
+ import subprocess
7
+ from pathlib import Path
8
+ from typing import Callable
9
+
10
+ from .config import ProjectConfig
11
+ from .discord import DiscordWebhook
12
+ from .git_ops import GitOps
13
+ from .gitlab_client import GitLabClient, Issue, MergeRequest, Note
14
+ from .protocols import GitOperations
15
+ from .state import StateManager
16
+
17
+ # Security constants for prompt sanitization
18
+ MAX_PROMPT_LENGTH = 10000
19
+ FORBIDDEN_PATTERNS = [
20
+ r"\$\([^)]+\)", # Command substitution $(...)
21
+ r"`[^`]+`", # Backtick command `...`
22
+ r"\$\{[^}]+\}", # Variable expansion ${...}
23
+ r"\$\w+", # Variable reference $var
24
+ ]
25
+
26
+ # Input validation constants
27
+ MAX_TITLE_LENGTH = 255
28
+ MAX_DESCRIPTION_LENGTH = 50000
29
+ MAX_SLUG_LENGTH = 50
30
+ MAX_BRANCH_LENGTH = 100
31
+
32
+ # Claude CLI timeout
33
+ CLAUDE_CLI_TIMEOUT_SECONDS = 600
34
+
35
+
36
+ class Processor:
37
+ """Processes issues and MR comments."""
38
+
39
+ def __init__(
40
+ self,
41
+ gitlab: GitLabClient,
42
+ discord: DiscordWebhook,
43
+ state: StateManager,
44
+ gitlab_username: str,
45
+ label_in_progress: str,
46
+ label_review: str,
47
+ ai_tool_mode: str = "ollama",
48
+ ai_tool_custom_command: str = "",
49
+ default_branch: str = "master",
50
+ git_factory: Callable[[Path], GitOperations] = GitOps,
51
+ ) -> None:
52
+ """Initialize processor.
53
+
54
+ Args:
55
+ gitlab: GitLab API client
56
+ discord: Discord webhook client
57
+ state: State manager
58
+ gitlab_username: GitLab username for filtering comments
59
+ label_in_progress: Label for in-progress issues
60
+ label_review: Label for issues under review
61
+ ai_tool_mode: AI tool mode ("ollama", "direct", "custom", "opencode", or "opencode-custom")
62
+ ai_tool_custom_command: Custom command for AI tool (used when mode is "custom")
63
+ default_branch: Default branch name (default: "master")
64
+ git_factory: Factory function to create GitOperations instances (for dependency injection)
65
+ """
66
+ self.gitlab = gitlab
67
+ self.discord = discord
68
+ self.state = state
69
+ self.gitlab_username = gitlab_username
70
+ self.label_in_progress = label_in_progress
71
+ self.label_review = label_review
72
+ self.ai_tool_mode = ai_tool_mode
73
+ self.ai_tool_custom_command = ai_tool_custom_command
74
+ self.default_branch = default_branch
75
+ self.git_factory = git_factory
76
+ self.logger = logging.getLogger(__name__)
77
+
78
+ def _sanitize_prompt(self, prompt: str) -> str:
79
+ """Sanitize prompt to prevent command injection.
80
+
81
+ Args:
82
+ prompt: The raw prompt string
83
+
84
+ Returns:
85
+ Sanitized prompt string
86
+
87
+ Raises:
88
+ ValueError: If prompt contains forbidden patterns
89
+ """
90
+ if len(prompt) > MAX_PROMPT_LENGTH:
91
+ prompt = prompt[:MAX_PROMPT_LENGTH]
92
+
93
+ for pattern in FORBIDDEN_PATTERNS:
94
+ if re.search(pattern, prompt):
95
+ raise ValueError(f"Prompt contains forbidden pattern: {pattern}")
96
+
97
+ return prompt
98
+
99
+ def _validate_issue_title(self, title: str) -> str:
100
+ """Validate and sanitize issue title.
101
+
102
+ Args:
103
+ title: The raw issue title
104
+
105
+ Returns:
106
+ Validated and sanitized title
107
+
108
+ Raises:
109
+ ValueError: If title is empty or invalid
110
+ """
111
+ if not title or not title.strip():
112
+ raise ValueError("Issue title cannot be empty")
113
+
114
+ # Truncate to max length
115
+ title = title[:MAX_TITLE_LENGTH]
116
+
117
+ # Remove control characters
118
+ title = "".join(c for c in title if c.isprintable())
119
+
120
+ return title.strip()
121
+
122
+ def _validate_branch_name(self, branch: str) -> str:
123
+ """Validate and sanitize branch name.
124
+
125
+ Args:
126
+ branch: The proposed branch name
127
+
128
+ Returns:
129
+ Validated branch name
130
+ """
131
+ branch = branch.strip()
132
+
133
+ if not branch:
134
+ return "auto-branch"
135
+
136
+ # Remove problematic characters for git branch names
137
+ branch = re.sub(r"[^\w\-/.]", "-", branch)
138
+
139
+ # Remove consecutive hyphens
140
+ while "--" in branch:
141
+ branch = branch.replace("--", "-")
142
+
143
+ # Remove leading/trailing hyphens and dots
144
+ branch = branch.strip("-.")
145
+
146
+ # Truncate to max length
147
+ if len(branch) > MAX_BRANCH_LENGTH:
148
+ branch = branch[:MAX_BRANCH_LENGTH]
149
+
150
+ return branch or "auto-branch"
151
+
152
+ def _run_claude(self, prompt: str, repo_path: Path) -> tuple[bool, str]:
153
+ """Run AI tool CLI with a prompt based on configured mode.
154
+
155
+ Args:
156
+ prompt: The prompt for AI tool
157
+ repo_path: Path to the repository
158
+
159
+ Returns:
160
+ Tuple of (success, output)
161
+ """
162
+ # Sanitize prompt to prevent command injection
163
+ try:
164
+ safe_prompt = self._sanitize_prompt(prompt)
165
+ except ValueError as e:
166
+ return False, f"Prompt validation failed: {e}"
167
+
168
+ # Build command based on mode
169
+ if self.ai_tool_mode == "ollama":
170
+ cmd = [
171
+ "ollama",
172
+ "launch",
173
+ "claude",
174
+ "--",
175
+ "-p",
176
+ "--permission-mode",
177
+ "acceptEdits",
178
+ safe_prompt,
179
+ ]
180
+ elif self.ai_tool_mode == "direct":
181
+ cmd = ["claude", "-p", "--permission-mode", "acceptEdits", safe_prompt]
182
+ elif self.ai_tool_mode == "opencode":
183
+ cmd = ["opencode", safe_prompt]
184
+ elif self.ai_tool_mode == "custom":
185
+ if not self.ai_tool_custom_command:
186
+ return False, "AI_TOOL_CUSTOM_COMMAND not set for custom mode"
187
+ # Split first, then substitute to preserve multi-word values
188
+ cmd_parts = shlex.split(self.ai_tool_custom_command)
189
+ cmd = [
190
+ part.replace("{prompt}", safe_prompt).replace("{cwd}", str(repo_path))
191
+ for part in cmd_parts
192
+ ]
193
+ else:
194
+ return False, f"Unknown AI_TOOL_MODE: {self.ai_tool_mode}"
195
+
196
+ try:
197
+ env = {"CLAUDECODE": ""}
198
+ result = subprocess.run(
199
+ cmd,
200
+ cwd=repo_path,
201
+ capture_output=True,
202
+ text=True,
203
+ env=env,
204
+ timeout=CLAUDE_CLI_TIMEOUT_SECONDS,
205
+ )
206
+ return result.returncode == 0, result.stdout + result.stderr
207
+ except subprocess.TimeoutExpired:
208
+ return False, "Claude timed out"
209
+ except FileNotFoundError:
210
+ return False, "Claude CLI not found"
211
+
212
+ def process_issue(
213
+ self,
214
+ project: ProjectConfig,
215
+ issue: Issue,
216
+ ) -> bool:
217
+ """Process an issue: create branch, run Claude, push, create MR.
218
+
219
+ Args:
220
+ project: Project configuration
221
+ issue: The issue to process
222
+
223
+ Returns:
224
+ True if successful, False otherwise
225
+ """
226
+ git = self.git_factory(project.path)
227
+
228
+ # Validate issue title
229
+ try:
230
+ validated_title = self._validate_issue_title(issue.title)
231
+ except ValueError as e:
232
+ self.logger.error(f"Invalid issue title: {e}")
233
+ self.discord.notify_error(
234
+ project.name,
235
+ f"Invalid issue title: {e}",
236
+ )
237
+ self.state.set_processing(project.project_id, False)
238
+ return False
239
+
240
+ # Generate and validate branch name
241
+ slug = GitOps.generate_slug(validated_title, max_length=MAX_SLUG_LENGTH)
242
+ branch = self._validate_branch_name(f"{issue.iid}-{slug}")
243
+
244
+ self.logger.info(
245
+ f"[{project.name}] Processing issue #{issue.iid}: {validated_title}"
246
+ )
247
+ self.logger.debug(f"[{project.name}] Creating branch: {branch}")
248
+
249
+ self.discord.notify_issue_started(
250
+ project.name,
251
+ validated_title,
252
+ issue.web_url,
253
+ branch,
254
+ )
255
+
256
+ # Add "In progress" label
257
+ self.gitlab.update_issue_labels(
258
+ project.project_id,
259
+ issue.iid,
260
+ issue.labels + [self.label_in_progress],
261
+ )
262
+
263
+ # Create branch
264
+ git.fetch()
265
+ git.checkout(self.default_branch)
266
+ git.pull()
267
+
268
+ if not git.checkout(branch, create=True):
269
+ self.discord.notify_error(
270
+ project.name,
271
+ f"Could not create branch `{branch}`",
272
+ )
273
+ self.state.set_processing(project.project_id, False)
274
+ return False
275
+
276
+ # Build prompt for Claude (truncate description if too long)
277
+ description = issue.description or ""
278
+ if len(description) > MAX_DESCRIPTION_LENGTH:
279
+ description = description[:MAX_DESCRIPTION_LENGTH]
280
+
281
+ prompt = f"""You are working on issue #{issue.iid}: {validated_title}
282
+
283
+ Issue description:
284
+ {description}
285
+
286
+ Please complete this task. Make the necessary changes and commit them.
287
+ Write commit messages in English.
288
+ Do not use conventional commit prefixes like feat:, fix:, etc.
289
+ Do not add Co-Authored-By signature to commits."""
290
+
291
+ # Run Claude
292
+ success, output = self._run_claude(prompt, project.path)
293
+
294
+ if success:
295
+ # Push branch
296
+ git.push("origin", branch, set_upstream=True)
297
+
298
+ # Create MR
299
+ mr = self.gitlab.create_merge_request(
300
+ project.project_id,
301
+ source_branch=branch,
302
+ target_branch=self.default_branch,
303
+ title=issue.title,
304
+ description=f"{issue.description}\n\nCloses #{issue.iid}",
305
+ )
306
+
307
+ if mr:
308
+ # Move issue to Review
309
+ self.gitlab.update_issue_labels(
310
+ project.project_id,
311
+ issue.iid,
312
+ [self.label_review],
313
+ )
314
+ self.discord.notify_mr_created(
315
+ project.name,
316
+ issue.title,
317
+ mr.web_url,
318
+ issue.iid,
319
+ )
320
+ else:
321
+ self.discord.notify_error(
322
+ project.name,
323
+ "Changes done but MR creation failed",
324
+ )
325
+ else:
326
+ self.discord.notify_error(
327
+ project.name,
328
+ f"Processing failed for issue #{issue.iid}",
329
+ output,
330
+ )
331
+
332
+ self.state.set_processing(project.project_id, False)
333
+ return success
334
+
335
+ def process_comment(
336
+ self,
337
+ project: ProjectConfig,
338
+ mr: MergeRequest,
339
+ comment: str,
340
+ ) -> bool:
341
+ """Process an MR comment: checkout branch, run Claude, push.
342
+
343
+ Args:
344
+ project: Project configuration
345
+ mr: The merge request
346
+ comment: The comment to process
347
+
348
+ Returns:
349
+ True if successful, False otherwise
350
+ """
351
+ git = self.git_factory(project.path)
352
+
353
+ self.discord.send(
354
+ f"🤖 **Processing Comment** [{project.name}]\n"
355
+ f"[{mr.title}]({mr.web_url})\n\n"
356
+ f"Starting to work on: {comment}"
357
+ )
358
+
359
+ # Switch to MR branch
360
+ git.fetch()
361
+ if not git.checkout(mr.source_branch):
362
+ self.discord.notify_error(
363
+ project.name,
364
+ f"Could not checkout branch `{mr.source_branch}`",
365
+ )
366
+ self.state.set_processing(project.project_id, False)
367
+ return False
368
+
369
+ git.pull("origin", mr.source_branch)
370
+
371
+ # Build prompt for Claude
372
+ prompt = f"""You are working on a merge request titled: {mr.title}
373
+ Branch: {mr.source_branch}
374
+
375
+ A reviewer left this feedback:
376
+ {comment}
377
+
378
+ Please address this feedback. Make the necessary changes and commit them.
379
+ Write commit messages in English.
380
+ Do not use conventional commit prefixes like feat:, fix:, etc.
381
+ Do not add Co-Authored-By signature to commits."""
382
+
383
+ # Run Claude
384
+ success, output = self._run_claude(prompt, project.path)
385
+
386
+ if success:
387
+ # Push changes
388
+ git.push("origin", mr.source_branch)
389
+ self.discord.notify_changes_applied(
390
+ project.name,
391
+ mr.title,
392
+ mr.web_url,
393
+ )
394
+ else:
395
+ self.discord.notify_error(
396
+ project.name,
397
+ f"Processing failed for MR !{mr.iid}",
398
+ output,
399
+ )
400
+
401
+ self.state.set_processing(project.project_id, False)
402
+ return success
403
+
404
+ def cleanup_after_merge(
405
+ self,
406
+ project: ProjectConfig,
407
+ branch: str,
408
+ mr_title: str,
409
+ mr_url: str,
410
+ ) -> None:
411
+ """Cleanup after MR merge: switch to default branch, delete branch.
412
+
413
+ Args:
414
+ project: Project configuration
415
+ branch: The merged branch name
416
+ mr_title: The MR title
417
+ mr_url: The MR URL
418
+ """
419
+ git = self.git_factory(project.path)
420
+
421
+ self.discord.notify_mr_merged(project.name, mr_title, mr_url)
422
+
423
+ # Switch to default branch and pull
424
+ git.checkout(self.default_branch)
425
+ git.pull()
426
+
427
+ # Delete branch
428
+ if branch:
429
+ git.delete_branch(branch, force=True)
430
+ self.discord.notify_cleanup_complete(project.name, branch)
431
+
432
+ # Reset state
433
+ self.state.reset(project.project_id)
434
+
435
+
436
+ __all__ = [
437
+ "Processor",
438
+ "MAX_PROMPT_LENGTH",
439
+ "MAX_TITLE_LENGTH",
440
+ "MAX_DESCRIPTION_LENGTH",
441
+ "MAX_SLUG_LENGTH",
442
+ "MAX_BRANCH_LENGTH",
443
+ "CLAUDE_CLI_TIMEOUT_SECONDS",
444
+ ]
@@ -0,0 +1,96 @@
1
+ """Protocol definitions for dependency injection."""
2
+
3
+ from pathlib import Path
4
+ from typing import Protocol
5
+
6
+
7
+ class GitOperations(Protocol):
8
+ """Protocol for Git operations.
9
+
10
+ This protocol defines the interface for Git operations,
11
+ allowing for dependency injection and easier testing.
12
+ """
13
+
14
+ def fetch(self, remote: str = "origin") -> bool:
15
+ """Fetch from remote.
16
+
17
+ Args:
18
+ remote: Remote name
19
+
20
+ Returns:
21
+ True if successful, False otherwise
22
+ """
23
+ ...
24
+
25
+ def checkout(self, branch: str, create: bool = False) -> bool:
26
+ """Checkout a branch.
27
+
28
+ Args:
29
+ branch: Branch name
30
+ create: Create branch if it doesn't exist
31
+
32
+ Returns:
33
+ True if successful, False otherwise
34
+ """
35
+ ...
36
+
37
+ def pull(self, remote: str = "origin", branch: str | None = None) -> bool:
38
+ """Pull from remote.
39
+
40
+ Args:
41
+ remote: Remote name
42
+ branch: Branch name (optional)
43
+
44
+ Returns:
45
+ True if successful, False otherwise
46
+ """
47
+ ...
48
+
49
+ def push(
50
+ self,
51
+ remote: str = "origin",
52
+ branch: str | None = None,
53
+ set_upstream: bool = False,
54
+ ) -> bool:
55
+ """Push to remote.
56
+
57
+ Args:
58
+ remote: Remote name
59
+ branch: Branch name (optional, uses current branch if None)
60
+ set_upstream: Set upstream flag
61
+
62
+ Returns:
63
+ True if successful, False otherwise
64
+ """
65
+ ...
66
+
67
+ def delete_branch(self, branch: str, force: bool = False) -> bool:
68
+ """Delete a branch.
69
+
70
+ Args:
71
+ branch: Branch name
72
+ force: Force delete
73
+
74
+ Returns:
75
+ True if successful, False otherwise
76
+ """
77
+ ...
78
+
79
+ def get_current_branch(self) -> str | None:
80
+ """Get current branch name.
81
+
82
+ Returns:
83
+ Current branch name or None if not on a branch
84
+ """
85
+ ...
86
+
87
+ def get_remote_url(self) -> str | None:
88
+ """Get remote URL.
89
+
90
+ Returns:
91
+ Remote URL or None if not configured
92
+ """
93
+ ...
94
+
95
+
96
+ __all__ = ["GitOperations"]