Fetch the content of a file from the GitLab repository at the given ref (tag, branch, or commit SHA). If `ref` is None, uses self.ref. Strategy: 1) Try the RAW endpoint (returns bytes of the file) 2) Fallback to the JSON endpoint (returns base64-encoded
(self, file_path: str, *, ref: str | None = None)
| 177 | self.ref = ref |
| 178 | |
| 179 | def get_file_content(self, file_path: str, *, ref: str | None = None) -> str | None: |
| 180 | """ |
| 181 | Fetch the content of a file from the GitLab repository at the given ref |
| 182 | (tag, branch, or commit SHA). If `ref` is None, uses self.ref. |
| 183 | |
| 184 | Strategy: |
| 185 | 1) Try the RAW endpoint (returns bytes of the file) |
| 186 | 2) Fallback to the JSON endpoint (returns base64-encoded content) |
| 187 | |
| 188 | Returns: |
| 189 | File content as UTF-8 string, or None if file not found. |
| 190 | """ |
| 191 | raw_url: Final = self._file_raw_url(file_path, ref=ref) |
| 192 | |
| 193 | try: |
| 194 | resp: Final = self.http_handler.get(raw_url, headers=self.headers) |
| 195 | if resp.status_code == 404: |
| 196 | # Fallback to JSON endpoint |
| 197 | return self._get_file_content_via_json(file_path, ref=ref) |
| 198 | resp.raise_for_status() |
| 199 | |
| 200 | ctype: Final = (resp.headers.get("content-type") or "").lower() |
| 201 | if ctype.startswith("text/") or "charset=" in ctype or ctype.startswith("application/json"): |
| 202 | return resp.text |
| 203 | try: |
| 204 | return resp.content.decode("utf-8") |
| 205 | except Exception: |
| 206 | return resp.content.decode("utf-8", errors="replace") |
| 207 | |
| 208 | except Exception as e: |
| 209 | status: Final = getattr(getattr(e, "response", None), "status_code", None) |
| 210 | if status == 404: |
| 211 | return None |
| 212 | if status == 403: |
| 213 | raise Exception( |
| 214 | f"Access denied to file '{file_path}'. Check your GitLab permissions for project '{self.project}'." |
| 215 | ) |
| 216 | if status == 401: |
| 217 | raise Exception("Authentication failed. Check your GitLab token and auth_method.") |
| 218 | raise Exception(f"Failed to fetch file '{file_path}': {e}") |
| 219 | |
| 220 | def _get_file_content_via_json(self, file_path: str, *, ref: str | None = None) -> str | None: |
| 221 | """ |