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,3 @@
1
+ """GitLab Watcher - Monitor projects and process issues/MRs automatically."""
2
+
3
+ __version__ = "1.0.0"
@@ -0,0 +1,6 @@
1
+ """Entry point for `python -m gitlab_watcher`."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,76 @@
1
+ """Simple time-based cache implementation."""
2
+
3
+ from datetime import datetime, timedelta
4
+ from typing import Any, Generic, Optional, TypeVar
5
+
6
+ T = TypeVar('T')
7
+
8
+
9
+ class TimedCache(Generic[T]):
10
+ """Simple time-based cache that expires entries after a TTL.
11
+
12
+ This cache stores values with timestamps and automatically invalidates
13
+ entries that exceed the time-to-live duration.
14
+ """
15
+
16
+ def __init__(self, ttl_seconds: float = 30.0) -> None:
17
+ """Initialize the cache.
18
+
19
+ Args:
20
+ ttl_seconds: Time-to-live in seconds for cache entries
21
+ """
22
+ self._cache: dict[str, tuple[datetime, T]] = {}
23
+ self._ttl = timedelta(seconds=ttl_seconds)
24
+
25
+ def get(self, key: str) -> Optional[T]:
26
+ """Get a value from cache if not expired.
27
+
28
+ Args:
29
+ key: Cache key
30
+
31
+ Returns:
32
+ Cached value if found and not expired, None otherwise
33
+ """
34
+ if key not in self._cache:
35
+ return None
36
+
37
+ timestamp, value = self._cache[key]
38
+
39
+ # Check if entry has expired
40
+ if datetime.now() - timestamp > self._ttl:
41
+ del self._cache[key]
42
+ return None
43
+
44
+ return value
45
+
46
+ def set(self, key: str, value: T) -> None:
47
+ """Store a value in cache.
48
+
49
+ Args:
50
+ key: Cache key
51
+ value: Value to cache
52
+ """
53
+ self._cache[key] = (datetime.now(), value)
54
+
55
+ def invalidate(self, key: str) -> None:
56
+ """Remove a specific entry from cache.
57
+
58
+ Args:
59
+ key: Cache key to invalidate
60
+ """
61
+ self._cache.pop(key, None)
62
+
63
+ def clear(self) -> None:
64
+ """Remove all entries from cache."""
65
+ self._cache.clear()
66
+
67
+ def size(self) -> int:
68
+ """Return number of entries in cache (including expired ones).
69
+
70
+ Returns:
71
+ Number of cached entries
72
+ """
73
+ return len(self._cache)
74
+
75
+
76
+ __all__ = ["TimedCache"]
gitlab_watcher/cli.py ADDED
@@ -0,0 +1,24 @@
1
+ """Click CLI entry point."""
2
+
3
+ import click
4
+
5
+ from .config import DEFAULT_CONFIG_PATH
6
+ from .watcher import Watcher
7
+
8
+
9
+ @click.command()
10
+ @click.option(
11
+ "--config",
12
+ "-c",
13
+ default=DEFAULT_CONFIG_PATH,
14
+ help="Path to config file",
15
+ )
16
+ @click.option("--verbose", "-v", is_flag=True, help="Verbose output")
17
+ def main(config: str, verbose: bool) -> None:
18
+ """GitLab Watcher - Monitor projects and process issues/MRs."""
19
+ watcher = Watcher(config_path=config, verbose=verbose)
20
+ watcher.run()
21
+
22
+
23
+ if __name__ == "__main__":
24
+ main()
@@ -0,0 +1,233 @@
1
+ """Configuration handling with bash config compatibility."""
2
+
3
+ import os
4
+ import re
5
+ import shlex
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+ # Default configuration file path
11
+ DEFAULT_CONFIG_PATH = os.path.expanduser("~/.config/gitlab-watcher/config.conf")
12
+
13
+
14
+ @dataclass
15
+ class ProjectConfig:
16
+ """Configuration for a monitored project."""
17
+
18
+ project_id: int
19
+ path: Path
20
+ name: str
21
+ default_branch: str = "master"
22
+
23
+
24
+ @dataclass
25
+ class Config:
26
+ """Global configuration loaded from bash-style config file."""
27
+
28
+ gitlab_url: str = ""
29
+ gitlab_token: str = ""
30
+ discord_webhook: str = ""
31
+ label_in_progress: str = "In progress"
32
+ label_review: str = "Review"
33
+ gitlab_username: str = "claude"
34
+ poll_interval: int = 30
35
+ ai_tool_mode: str = "ollama"
36
+ ai_tool_custom_command: str = ""
37
+ default_branch: str = "master"
38
+ project_dirs: list[str] = field(default_factory=list)
39
+ projects: list[ProjectConfig] = field(default_factory=list)
40
+
41
+
42
+ def parse_bash_config(config_path: Path) -> dict[str, str | list[str]]:
43
+ """Parse bash-style config file into a dictionary.
44
+
45
+ Handles:
46
+ - Simple key=value assignments
47
+ - Bash arrays: KEY=(val1 val2 "quoted val") - single or multi-line
48
+ - Comments (lines starting with #)
49
+ - Quoted values
50
+ """
51
+ result: dict[str, str | list[str]] = {}
52
+ content = config_path.read_text()
53
+
54
+ lines = content.splitlines()
55
+ i = 0
56
+
57
+ while i < len(lines):
58
+ line = lines[i].strip()
59
+
60
+ # Skip empty lines and comments
61
+ if not line or line.startswith("#"):
62
+ i += 1
63
+ continue
64
+
65
+ # Handle bash arrays: KEY=(...)
66
+ array_start = re.match(r"^(\w+)=\($", line)
67
+ if array_start:
68
+ key = array_start.group(1)
69
+ values: list[str] = []
70
+ i += 1
71
+
72
+ # Collect array values until closing parenthesis
73
+ while i < len(lines):
74
+ array_line = lines[i].strip()
75
+
76
+ # Skip comments
77
+ if array_line.startswith("#"):
78
+ i += 1
79
+ continue
80
+
81
+ # Check for closing parenthesis
82
+ if array_line == ")":
83
+ i += 1
84
+ break
85
+
86
+ if array_line:
87
+ # Parse array values using shlex
88
+ values.extend(shlex.split(array_line))
89
+
90
+ i += 1
91
+
92
+ result[key] = values
93
+ continue
94
+
95
+ # Handle inline bash arrays: KEY=(val1 val2)
96
+ inline_array = re.match(r"^(\w+)=\((.+)\)$", line)
97
+ if inline_array:
98
+ key = inline_array.group(1)
99
+ values_str = inline_array.group(2)
100
+
101
+ # Parse array values using shlex
102
+ result[key] = shlex.split(values_str)
103
+ i += 1
104
+ continue
105
+
106
+ # Handle simple key=value
107
+ simple_match = re.match(r"^(\w+)=(.*)$", line)
108
+ if simple_match:
109
+ key = simple_match.group(1)
110
+ value_str = simple_match.group(2).strip()
111
+
112
+ # Parse simple values using shlex
113
+ parts = shlex.split(value_str)
114
+ if parts:
115
+ result[key] = parts[0]
116
+ else:
117
+ result[key] = ""
118
+
119
+ i += 1
120
+
121
+ return result
122
+
123
+
124
+ def extract_project_id(project_file_path: Path) -> Optional[int]:
125
+ """Extract Project ID from PROJECT.md, AGENTS.md, or CLAUDE.md file.
126
+
127
+ Supports formats like:
128
+ - Project ID: 31
129
+ - Project ID: **31**
130
+ - project_id: 31
131
+ """
132
+ if not project_file_path.exists():
133
+ return None
134
+
135
+ content = project_file_path.read_text()
136
+
137
+ match = re.search(r"(?i)project[_\s]*id:?\s*\*{0,2}(\d+)\*{0,2}", content)
138
+ if match:
139
+ return int(match.group(1))
140
+
141
+ return None
142
+
143
+
144
+ def load_config(config_path: str) -> Config:
145
+ """Load configuration from file and discover projects."""
146
+ config_file = Path(config_path).expanduser()
147
+
148
+ if not config_file.exists():
149
+ raise FileNotFoundError(f"Config file not found: {config_file}")
150
+
151
+ raw_config = parse_bash_config(config_file)
152
+
153
+ # Helper function to safely convert config values
154
+ def get_str(key: str, default: str = "") -> str:
155
+ value = raw_config.get(key, default)
156
+ if isinstance(value, list) and value:
157
+ return str(value[0])
158
+ return str(value)
159
+
160
+ def get_int(key: str, default: int = 0) -> int:
161
+ value = raw_config.get(key, str(default))
162
+ if isinstance(value, list) and value:
163
+ return int(str(value[0]))
164
+ return int(str(value))
165
+
166
+ config = Config(
167
+ gitlab_url=get_str("GITLAB_URL"),
168
+ gitlab_token=get_str("GITLAB_TOKEN"),
169
+ discord_webhook=get_str("DISCORD_WEBHOOK"),
170
+ label_in_progress=get_str("LABEL_IN_PROGRESS", "In progress"),
171
+ label_review=get_str("LABEL_REVIEW", "Review"),
172
+ gitlab_username=get_str("GITLAB_USERNAME", "claude"),
173
+ poll_interval=get_int("POLL_INTERVAL", 30),
174
+ ai_tool_mode=get_str("AI_TOOL_MODE", "ollama"),
175
+ ai_tool_custom_command=get_str("AI_TOOL_CUSTOM_COMMAND"),
176
+ )
177
+
178
+ # Get project directories
179
+ project_dirs = raw_config.get("PROJECT_DIRS", [])
180
+ if isinstance(project_dirs, str):
181
+ project_dirs = [project_dirs]
182
+
183
+ config.project_dirs = project_dirs
184
+
185
+ # Discover projects
186
+ seen_ids: set[int] = set()
187
+
188
+ for project_dir in project_dirs:
189
+ project_path = Path(project_dir).expanduser()
190
+
191
+ if project_dir.strip().startswith("#"):
192
+ continue
193
+
194
+ if not project_path.exists():
195
+ continue
196
+
197
+ project_id = None
198
+ for filename in ["PROJECT.md", "AGENTS.md", "CLAUDE.md"]:
199
+ project_file = project_path / filename
200
+ project_id = extract_project_id(project_file)
201
+ if project_id is not None:
202
+ break
203
+
204
+ if project_id is None:
205
+ continue
206
+
207
+ if project_id in seen_ids:
208
+ continue
209
+
210
+ seen_ids.add(project_id)
211
+
212
+ config.projects.append(
213
+ ProjectConfig(
214
+ project_id=project_id,
215
+ path=project_path,
216
+ name=project_path.name,
217
+ )
218
+ )
219
+
220
+ if not config.projects:
221
+ raise ValueError("No valid projects found in configuration")
222
+
223
+ return config
224
+
225
+
226
+ __all__ = [
227
+ "DEFAULT_CONFIG_PATH",
228
+ "ProjectConfig",
229
+ "Config",
230
+ "parse_bash_config",
231
+ "extract_project_id",
232
+ "load_config",
233
+ ]
@@ -0,0 +1,112 @@
1
+ """Discord webhook notifications."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ import requests
6
+
7
+
8
+ @dataclass
9
+ class DiscordWebhook:
10
+ """Discord webhook client."""
11
+
12
+ webhook_url: str
13
+
14
+ def send(self, content: str) -> bool:
15
+ """Send a message to Discord.
16
+
17
+ Args:
18
+ content: The message content
19
+
20
+ Returns:
21
+ True if successful, False otherwise
22
+ """
23
+ if not self.webhook_url:
24
+ return True # No webhook configured, skip silently
25
+
26
+ try:
27
+ response = requests.post(
28
+ self.webhook_url,
29
+ json={"content": content},
30
+ headers={"Content-Type": "application/json"},
31
+ timeout=10,
32
+ )
33
+ return response.status_code == 204
34
+ except requests.RequestException:
35
+ return False
36
+
37
+ def notify_issue_started(
38
+ self,
39
+ project_name: str,
40
+ issue_title: str,
41
+ issue_url: str,
42
+ branch: str,
43
+ ) -> bool:
44
+ """Notify that issue processing has started."""
45
+ return self.send(
46
+ f"🚀 **Starting Issue** [{project_name}]\n"
47
+ f"[{issue_title}]({issue_url})\n\n"
48
+ f"Branch: `{branch}`"
49
+ )
50
+
51
+ def notify_mr_created(
52
+ self,
53
+ project_name: str,
54
+ issue_title: str,
55
+ mr_url: str,
56
+ issue_iid: int,
57
+ ) -> bool:
58
+ """Notify that an MR has been created."""
59
+ return self.send(
60
+ f"✅ **MR Created** [{project_name}]\n"
61
+ f"[{issue_title}]({mr_url})\n\n"
62
+ f"Issue #{issue_iid} completed. Waiting for review."
63
+ )
64
+
65
+ def notify_changes_applied(
66
+ self,
67
+ project_name: str,
68
+ mr_title: str,
69
+ mr_url: str,
70
+ ) -> bool:
71
+ """Notify that MR feedback has been applied."""
72
+ return self.send(
73
+ f"✅ **Changes Applied** [{project_name}]\n"
74
+ f"[{mr_title}]({mr_url})\n\n"
75
+ f"Feedback has been addressed and changes pushed."
76
+ )
77
+
78
+ def notify_mr_merged(
79
+ self,
80
+ project_name: str,
81
+ mr_title: str,
82
+ mr_url: str,
83
+ ) -> bool:
84
+ """Notify that an MR has been merged."""
85
+ return self.send(
86
+ f"✅ **MR Merged** [{project_name}]\n"
87
+ f"[{mr_title}]({mr_url})\n\n"
88
+ f"MR was merged. Running cleanup..."
89
+ )
90
+
91
+ def notify_cleanup_complete(
92
+ self,
93
+ project_name: str,
94
+ branch: str,
95
+ ) -> bool:
96
+ """Notify that cleanup has completed."""
97
+ return self.send(
98
+ f"🧹 **Cleanup complete** [{project_name}]\n"
99
+ f"Branch `{branch}` deleted, master updated."
100
+ )
101
+
102
+ def notify_error(
103
+ self,
104
+ project_name: str,
105
+ message: str,
106
+ details: str | None = None,
107
+ ) -> bool:
108
+ """Notify about an error."""
109
+ content = f"❌ **Error** [{project_name}]\n{message}"
110
+ if details:
111
+ content += f"\n\nError: {details}"
112
+ return self.send(content)
@@ -0,0 +1,106 @@
1
+ """Custom exceptions for GitLab Watcher."""
2
+
3
+
4
+ class GitLabWatcherError(Exception):
5
+ """Base exception for GitLab Watcher errors."""
6
+ pass
7
+
8
+
9
+ class GitLabError(GitLabWatcherError):
10
+ """Base exception for GitLab client errors."""
11
+
12
+ def __init__(self, message: str) -> None:
13
+ """Initialize GitLab error.
14
+
15
+ Args:
16
+ message: Error message
17
+ """
18
+ self.message = message
19
+ super().__init__(message)
20
+
21
+
22
+ class GitLabConnectionError(GitLabError):
23
+ """Network connection error when communicating with GitLab."""
24
+
25
+ def __init__(self, message: str = "Failed to connect to GitLab") -> None:
26
+ """Initialize connection error.
27
+
28
+ Args:
29
+ message: Error message
30
+ """
31
+ super().__init__(message)
32
+
33
+
34
+ class GitLabAPIError(GitLabError):
35
+ """GitLab API returned an error response."""
36
+
37
+ def __init__(self, status_code: int, message: str) -> None:
38
+ """Initialize API error.
39
+
40
+ Args:
41
+ status_code: HTTP status code
42
+ message: Error message
43
+ """
44
+ self.status_code = status_code
45
+ super().__init__(f"GitLab API error {status_code}: {message}")
46
+
47
+
48
+ class GitLabNotFoundError(GitLabAPIError):
49
+ """Resource not found (HTTP 404)."""
50
+
51
+ def __init__(self, resource_type: str, resource_id: str | int) -> None:
52
+ """Initialize not found error.
53
+
54
+ Args:
55
+ resource_type: Type of resource (e.g., "issue", "merge request")
56
+ resource_id: Resource identifier
57
+ """
58
+ super().__init__(404, f"{resource_type} {resource_id} not found")
59
+
60
+
61
+ class GitLabRateLimitError(GitLabAPIError):
62
+ """Rate limit exceeded (HTTP 429)."""
63
+
64
+ def __init__(self, retry_after: int | None = None) -> None:
65
+ """Initialize rate limit error.
66
+
67
+ Args:
68
+ retry_after: Seconds to wait before retrying
69
+ """
70
+ self.retry_after = retry_after
71
+ message = "Rate limit exceeded"
72
+ if retry_after:
73
+ message += f", retry after {retry_after} seconds"
74
+ super().__init__(429, message)
75
+
76
+
77
+ class GitLabAuthenticationError(GitLabAPIError):
78
+ """Authentication failed (HTTP 401)."""
79
+
80
+ def __init__(self) -> None:
81
+ """Initialize authentication error."""
82
+ super().__init__(401, "Authentication failed. Check your GitLab token.")
83
+
84
+
85
+ class GitLabForbiddenError(GitLabAPIError):
86
+ """Access forbidden (HTTP 403)."""
87
+
88
+ def __init__(self, resource: str = "resource") -> None:
89
+ """Initialize forbidden error.
90
+
91
+ Args:
92
+ resource: The resource that was accessed
93
+ """
94
+ super().__init__(403, f"Access forbidden to {resource}")
95
+
96
+
97
+ __all__ = [
98
+ "GitLabWatcherError",
99
+ "GitLabError",
100
+ "GitLabConnectionError",
101
+ "GitLabAPIError",
102
+ "GitLabNotFoundError",
103
+ "GitLabRateLimitError",
104
+ "GitLabAuthenticationError",
105
+ "GitLabForbiddenError",
106
+ ]
@@ -0,0 +1,138 @@
1
+ """Git operations via subprocess."""
2
+
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+
7
+ class GitOps:
8
+ """Git operations using subprocess."""
9
+
10
+ def __init__(self, repo_path: Path) -> None:
11
+ """Initialize Git operations for a repository.
12
+
13
+ Args:
14
+ repo_path: Path to the git repository
15
+ """
16
+ self.repo_path = repo_path
17
+
18
+ def _run(self, *args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
19
+ """Run a git command in the repository."""
20
+ return subprocess.run(
21
+ ["git"] + list(args),
22
+ cwd=self.repo_path,
23
+ capture_output=True,
24
+ text=True,
25
+ check=check,
26
+ )
27
+
28
+ def fetch(self, remote: str = "origin") -> bool:
29
+ """Fetch from remote."""
30
+ try:
31
+ self._run("fetch", remote)
32
+ return True
33
+ except subprocess.CalledProcessError:
34
+ return False
35
+
36
+ def checkout(self, branch: str, create: bool = False) -> bool:
37
+ """Checkout a branch, optionally creating it."""
38
+ try:
39
+ if create:
40
+ self._run("checkout", "-b", branch)
41
+ else:
42
+ self._run("checkout", branch)
43
+ return True
44
+ except subprocess.CalledProcessError:
45
+ return False
46
+
47
+ def pull(self, remote: str = "origin", branch: str | None = None) -> bool:
48
+ """Pull from remote."""
49
+ try:
50
+ if branch:
51
+ self._run("pull", remote, branch)
52
+ else:
53
+ self._run("pull")
54
+ return True
55
+ except subprocess.CalledProcessError:
56
+ return False
57
+
58
+ def push(
59
+ self,
60
+ remote: str = "origin",
61
+ branch: str | None = None,
62
+ set_upstream: bool = False,
63
+ ) -> bool:
64
+ """Push to remote."""
65
+ try:
66
+ args = ["push"]
67
+ if set_upstream and branch:
68
+ args.extend(["-u", remote, branch])
69
+ elif branch:
70
+ args.extend([remote, branch])
71
+ else:
72
+ args.append(remote)
73
+
74
+ self._run(*args)
75
+ return True
76
+ except subprocess.CalledProcessError:
77
+ return False
78
+
79
+ def delete_branch(self, branch: str, force: bool = False) -> bool:
80
+ """Delete a local branch."""
81
+ try:
82
+ args = ["branch"]
83
+ if force:
84
+ args.append("-D")
85
+ else:
86
+ args.append("-d")
87
+ args.append(branch)
88
+
89
+ self._run(*args, check=False)
90
+ return True
91
+ except subprocess.CalledProcessError:
92
+ return False
93
+
94
+ def branch_exists(self, branch: str) -> bool:
95
+ """Check if a branch exists locally."""
96
+ try:
97
+ self._run("rev-parse", "--verify", branch, check=False)
98
+ return True
99
+ except subprocess.CalledProcessError:
100
+ return False
101
+
102
+ def get_current_branch(self) -> str | None:
103
+ """Get the current branch name."""
104
+ try:
105
+ result = self._run("rev-parse", "--abbrev-ref", "HEAD")
106
+ return result.stdout.strip() or None
107
+ except subprocess.CalledProcessError:
108
+ return None
109
+
110
+ def get_remote_url(self, remote: str = "origin") -> str | None:
111
+ """Get the remote URL."""
112
+ try:
113
+ result = self._run("config", "--get", f"remote.{remote}.url")
114
+ return result.stdout.strip() or None
115
+ except subprocess.CalledProcessError:
116
+ return None
117
+
118
+ @staticmethod
119
+ def generate_slug(title: str, max_length: int = 30) -> str:
120
+ """Generate a URL-safe slug from a title.
121
+
122
+ Args:
123
+ title: The title to slugify
124
+ max_length: Maximum length of the slug
125
+
126
+ Returns:
127
+ A URL-safe slug
128
+ """
129
+ slug = title.lower()
130
+ # Replace non-alphanumeric with hyphens
131
+ slug = "".join(c if c.isalnum() else "-" for c in slug)
132
+ # Remove consecutive hyphens
133
+ while "--" in slug:
134
+ slug = slug.replace("--", "-")
135
+ # Remove leading/trailing hyphens
136
+ slug = slug.strip("-")
137
+ # Truncate
138
+ return slug[:max_length]