Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement codacy import source (#71221)

Tom Owers0a1e80f2daf5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 220a8fc3ecc9..83a1714451b9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -114,6 +114,7 @@ the row lists both.
| churnkey | HTTP | requests | ✅ |
| coassemble | HTTP | requests | ✅ |
| coda | HTTP | requests | ✅ |
+| codacy | HTTP | requests | ✅ |
| codefresh | HTTP | requests | ✅ |
| cody | HTTP (CSV reports) | requests | ✅ |
| cohere | HTTP | requests | ✅ |
@@ -607,7 +608,6 @@ doesn't conflict with concurrent PRs.
- cloudbeds
- coassemble
- cockroachdb
-- codacy
- codecov
- confluent_cloud
- constant_contact
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/canonical_descriptions.py
new file mode 100644
index 000000000000..488865e4fd50
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/canonical_descriptions.py
@@ -0,0 +1,132 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the official Codacy API v3 reference (https://api.codacy.com/api/api-docs).
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "organizations": {
+ "description": "Organizations on Codacy that the account API token belongs to, across Git providers.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listuserorganizations",
+ "columns": {
+ "identifier": "Codacy identifier of the organization.",
+ "remoteIdentifier": "Unique identifier of the organization on the Git provider.",
+ "name": "Name of the organization on the Git provider.",
+ "provider": "Git provider hosting the organization (gh for GitHub, gl for GitLab, bb for Bitbucket).",
+ "created": "Timestamp when the organization was added to Codacy.",
+ "type": "Type of the organization (e.g. Organization, User).",
+ "joinMode": "How new members join the organization on Codacy.",
+ "avatar": "URL of the organization's avatar image.",
+ },
+ },
+ "repositories": {
+ "description": "Repositories in the configured organization, with the most recent analysis snapshot: quality grade, issue counts, complexity, duplication, coverage, and lines of code.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listorganizationrepositorieswithanalysis",
+ "columns": {
+ "repositoryId": "Codacy identifier for the repository.",
+ "provider": "Git provider hosting the repository (gh for GitHub, gl for GitLab, bb for Bitbucket).",
+ "owner": "Name of the organization that owns the repository.",
+ "name": "Name of the repository.",
+ "fullPath": "Full path of the repository on the Git provider.",
+ "visibility": "Visibility of the repository (Public, Private, or LoginPublic).",
+ "remoteIdentifier": "Unique identifier of the repository on the Git provider.",
+ "lastUpdated": "Timestamp when the repository was last updated on the Git provider.",
+ "languages": "List of the programming languages in the repository.",
+ "grade": "Quality grade of the repository as a number between 100 (highest) and 0 (lowest).",
+ "gradeLetter": "Quality grade of the repository as a letter between A (highest) and F (lowest).",
+ "issuesPercentage": "Percentage of the repository's lines of code with issues.",
+ "issuesCount": "Number of issues in the repository.",
+ "loc": "Lines of code of the repository.",
+ "complexFilesPercentage": "Percentage of complex files in the repository.",
+ "complexFilesCount": "Number of complex files in the repository.",
+ "duplicationPercentage": "Percentage of duplicated lines in the repository.",
+ "coverage": "Test coverage information for the most recent analyzed commit.",
+ "lastAnalysedCommit": "Most recent commit analyzed by Codacy.",
+ "selectedBranch": "Branch the analysis snapshot refers to.",
+ },
+ },
+ "files": {
+ "description": "Most recent analysis information for the files in each repository: per-file grade, issue count, complexity, duplication, and coverage. Files ignored on Codacy aren't returned.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listfiles",
+ "columns": {
+ "repository": "Name of the repository the file belongs to.",
+ "fileId": "Identifier of the file in a specific branch and commit.",
+ "branchId": "Identifier for the branch the file belongs to.",
+ "path": "Relative path of the file in the repository.",
+ "totalIssues": "Number of issues in the file.",
+ "complexity": "Complexity level of the file.",
+ "grade": "Quality grade of the file as a number between 100 (highest) and 0 (lowest).",
+ "gradeLetter": "Quality grade of the file as a letter between A (highest) and F (lowest).",
+ "coverageWithDecimals": "Test coverage percentage of the file.",
+ "duplication": "Number of duplicated lines in the file.",
+ "linesOfCode": "Lines of code in the file.",
+ "sourceLinesOfCode": "Coverable lines of code in the file.",
+ "numberOfMethods": "Number of methods in the file.",
+ },
+ },
+ "issues": {
+ "description": "Current issues that Codacy found in each repository's main branch, as shown on the repository Issues page.",
+ "docs_url": "https://api.codacy.com/api/api-docs#searchrepositoryissues",
+ "columns": {
+ "repository": "Name of the repository the issue belongs to.",
+ "issueId": "ID of the issue.",
+ "resultDataId": "Stable ID for the issue.",
+ "filePath": "Path of the file where the issue was found.",
+ "fileId": "Identifier of the file where the issue was found.",
+ "patternInfo": "Details of the code pattern that detected the issue, including category and severity level.",
+ "toolInfo": "Details of the tool that detected the issue.",
+ "lineNumber": "Line where the issue was found.",
+ "message": "Detailed cause of the issue.",
+ "suggestion": "The suggested fix for the issue.",
+ "language": "Language of the file where the issue was found.",
+ "lineText": "Contents of the line where the issue was found.",
+ "commitInfo": "Details of the commit that originated the issue.",
+ },
+ },
+ "pull_requests": {
+ "description": "Pull requests in each repository with Codacy's analysis results: new and fixed issues, complexity and duplication deltas, coverage, and whether the pull request is up to the quality standards.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listrepositorypullrequests",
+ "columns": {
+ "repository": "Name of the repository the pull request belongs to.",
+ "id": "Codacy identifier of the pull request.",
+ "number": "Number of the pull request on the Git provider.",
+ "updated": "Timestamp when the pull request was last updated.",
+ "status": "Pull request status.",
+ "title": "Title of the pull request.",
+ "owner": "Author of the pull request.",
+ "headCommitSha": "Commit SHA of the pull request head.",
+ "commonAncestorCommitSha": "Commit SHA of the common ancestor with the target branch.",
+ "originBranch": "Source branch of the pull request.",
+ "targetBranch": "Target branch of the pull request.",
+ "gitHref": "URL to the pull request on the Git provider.",
+ "isUpToStandards": "True if metrics are at or above the quality gate thresholds.",
+ "isAnalysing": "True if Codacy is still analyzing the pull request.",
+ "newIssues": "Number of issues introduced by the pull request.",
+ "fixedIssues": "Number of issues fixed by the pull request.",
+ "deltaComplexity": "Difference in cyclomatic complexity introduced by the pull request.",
+ "deltaClonesCount": "Difference in number of duplicated blocks of code introduced by the pull request.",
+ "coverage": "Coverage analysis for the pull request.",
+ "quality": "Quality gate analysis for the pull request.",
+ },
+ },
+ "commits": {
+ "description": "Analysis results for the commits in each repository's main branch on Codacy, including quality and coverage gate outcomes per commit.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listrepositorycommits",
+ "columns": {
+ "repository": "Name of the repository the commit belongs to.",
+ "sha": "Commit SHA.",
+ "id": "Internal Codacy commit identifier.",
+ "commitTimestamp": "Timestamp when the commit was created.",
+ "authorName": "Name of the commit author.",
+ "authorEmail": "Email address of the commit author.",
+ "message": "Commit message.",
+ "startedAnalysis": "Timestamp when Codacy started the last analysis of the commit.",
+ "endedAnalysis": "Timestamp when Codacy finished the last analysis of the commit.",
+ "isMergeCommit": "True if the commit is a merge commit.",
+ "gitHref": "URL to the commit on the Git provider.",
+ "parents": "SHA-1 hashes of the parents of the commit.",
+ "quality": "Quality gate analysis results for the commit, including new and fixed issues.",
+ "coverage": "Coverage analysis results for the commit.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/codacy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/codacy.py
new file mode 100644
index 000000000000..d23297d3753b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/codacy.py
@@ -0,0 +1,223 @@
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.settings import CODACY_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+
+CODACY_BASE_URL = "https://api.codacy.com/api/v3"
+# Documented maximum page size for v3 list endpoints.
+DEFAULT_PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class CodacyRetryableError(Exception):
+ pass
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "api-token": api_token,
+ "Accept": "application/json",
+ }
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ CodacyRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ method: str,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ if method == "POST":
+ # searchRepositoryIssues takes its filters in the body; an empty filter returns every
+ # current issue. Pagination params stay in the query string.
+ response = session.post(url, headers=headers, json={}, timeout=REQUEST_TIMEOUT_SECONDS)
+ else:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Codacy Cloud rate-limits at 2500 requests per 5 minutes per IP, surfacing as 429/503/504.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CodacyRetryableError(f"Codacy API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # 404 during a repository fan-out is expected (repository removed from Codacy mid-sync)
+ # and handled by the caller; anything else is a hard failure.
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"Codacy API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ return f"{CODACY_BASE_URL}{path}?{urlencode(params)}"
+
+
+def _paginate(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ path: str,
+ method: str = "GET",
+ extra_params: Optional[dict[str, str]] = None,
+ max_pages: Optional[int] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield one list of items per page, following Codacy's cursor pagination.
+
+ Each response carries `pagination.cursor` pointing at the next batch; the final page
+ omits the cursor (verified against the live API).
+ """
+ cursor: Optional[str] = None
+ page_count = 0
+
+ while True:
+ params: dict[str, Any] = {"limit": DEFAULT_PAGE_SIZE, **(extra_params or {})}
+ if cursor:
+ params["cursor"] = cursor
+
+ data = _fetch_page(session, method, _build_url(path, params), headers, logger)
+ items = data.get("data", [])
+ if items:
+ yield items
+
+ cursor = (data.get("pagination") or {}).get("cursor")
+ if not cursor or not items:
+ break
+
+ page_count += 1
+ if max_pages is not None and page_count >= max_pages:
+ logger.warning(f"Codacy: page cap reached for path={path}, max_pages={max_pages}; results truncated")
+ break
+
+
+def _normalize_item(endpoint: str, item: dict[str, Any], repository: Optional[str] = None) -> dict[str, Any]:
+ """Lift the envelope's entity object to the top level and stamp the repository name onto
+ fan-out rows, so primary keys are plain top-level columns."""
+ if endpoint == "repositories":
+ nested = item.pop("repository", None) or {}
+ return {**nested, **item}
+ if endpoint == "pull_requests":
+ nested = item.pop("pullRequest", None) or {}
+ return {"repository": repository, **nested, **item}
+ if endpoint == "commits":
+ nested = item.pop("commit", None) or {}
+ return {"repository": repository, **nested, **item}
+ if repository is not None:
+ return {"repository": repository, **item}
+ return item
+
+
+def _iter_repository_names(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ provider: str,
+ organization: str,
+) -> Iterator[str]:
+ path = f"/organizations/{provider}/{organization}/repositories"
+ for page in _paginate(session, headers, logger, path):
+ for repository in page:
+ name = repository.get("name")
+ if name:
+ yield name
+
+
+def get_rows(
+ api_token: str,
+ provider: str,
+ organization: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint_config = CODACY_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+ # One session reused across every page (and repository) so urllib3 keeps the connection
+ # alive instead of re-handshaking per request. The token rides the custom `api-token`
+ # header, which the capture pipeline's name-based denylist doesn't know, so redact it
+ # by value.
+ session = make_tracked_session(redact_values=(api_token,))
+
+ if not endpoint_config.fan_out_per_repository:
+ path = endpoint_config.path.format(provider=provider, organization=organization)
+ for page in _paginate(session, headers, logger, path, endpoint_config.method, endpoint_config.extra_params):
+ yield [_normalize_item(endpoint, item) for item in page]
+ return
+
+ for repository in _iter_repository_names(session, headers, logger, provider, organization):
+ path = endpoint_config.path.format(provider=provider, organization=organization, repository=repository)
+ try:
+ for page in _paginate(
+ session,
+ headers,
+ logger,
+ path,
+ endpoint_config.method,
+ endpoint_config.extra_params,
+ max_pages=endpoint_config.max_pages_per_repository,
+ ):
+ yield [_normalize_item(endpoint, item, repository=repository) for item in page]
+ except requests.HTTPError as exc:
+ # A repository removed from Codacy between enumeration and this fetch 404s; skip it
+ # rather than failing the whole sync. Anything else is re-raised.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Codacy: repository {repository} not found while fetching {endpoint}, skipping")
+ else:
+ raise
+
+
+def codacy_source(
+ api_token: str,
+ provider: str,
+ organization: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ endpoint_config = CODACY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ provider=provider,
+ organization=organization,
+ endpoint=endpoint,
+ logger=logger,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ sort_mode=endpoint_config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
+def validate_credentials(api_token: str) -> bool:
+ url = _build_url("/user/organizations", {"limit": 1})
+ try:
+ response = make_tracked_session(redact_values=(api_token,)).get(
+ url, headers=_get_headers(api_token), timeout=10
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/settings.py
new file mode 100644
index 000000000000..97d22a60d4fc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/settings.py
@@ -0,0 +1,82 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class CodacyEndpointConfig:
+ name: str
+ # Path template with {provider}, {organization}, and (for fan-out endpoints) {repository}
+ path: str
+ # searchRepositoryIssues is the one POST list endpoint; pagination still rides the query string.
+ method: Literal["GET", "POST"] = "GET"
+ # Composite keys include the repository name for fan-out children, whose ids are only
+ # unique within a repository.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Fan-out: fetched once per repository in the configured organization.
+ fan_out_per_repository: bool = False
+ # Stable datetime field to partition by (never a mutable field like `updated`).
+ partition_key: Optional[str] = None
+ sort_mode: Literal["asc", "desc"] = "asc"
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Hard cap on pages fetched per repository in a fan-out, to bound runaway pagination.
+ # A structured warning is logged if the cap is reached.
+ max_pages_per_repository: int = 1000
+
+
+CODACY_ENDPOINTS: dict[str, CodacyEndpointConfig] = {
+ "organizations": CodacyEndpointConfig(
+ name="organizations",
+ # Lists every organization the token's account belongs to, across Git providers.
+ path="/user/organizations",
+ primary_keys=["provider", "remoteIdentifier"],
+ ),
+ "repositories": CodacyEndpointConfig(
+ name="repositories",
+ # The /analysis listing carries the per-repository quality snapshot (grade, issues,
+ # complexity, duplication, coverage, LOC) alongside the repository metadata.
+ path="/analysis/organizations/{provider}/{organization}/repositories",
+ primary_keys=["provider", "owner", "name"],
+ ),
+ "files": CodacyEndpointConfig(
+ name="files",
+ path="/organizations/{provider}/{organization}/repositories/{repository}/files",
+ fan_out_per_repository=True,
+ # `fileId` identifies a file in a specific branch and commit, so it changes across
+ # analyses; the repository-relative path is the stable identity of a file row.
+ primary_keys=["repository", "path"],
+ ),
+ "issues": CodacyEndpointConfig(
+ name="issues",
+ path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/issues/search",
+ method="POST",
+ fan_out_per_repository=True,
+ primary_keys=["repository", "resultDataId"],
+ ),
+ "pull_requests": CodacyEndpointConfig(
+ name="pull_requests",
+ path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/pull-requests",
+ fan_out_per_repository=True,
+ primary_keys=["repository", "number"],
+ # The API returns pull requests last-updated first (verified against the live API).
+ sort_mode="desc",
+ extra_params={"includeNotAnalyzed": "true"},
+ ),
+ "commits": CodacyEndpointConfig(
+ name="commits",
+ # Analysis results for the commits in the repository's main branch on Codacy.
+ path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/commits",
+ fan_out_per_repository=True,
+ primary_keys=["repository", "sha"],
+ partition_key="commitTimestamp",
+ # The API returns commits newest-first (verified against the live API).
+ sort_mode="desc",
+ ),
+}
+
+ENDPOINTS = tuple(CODACY_ENDPOINTS.keys())
+
+# Codacy's v3 list endpoints expose no server-side updated-since/created-since filters
+# (pagination is cursor+limit only), so every endpoint is full refresh.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in CODACY_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/source.py
index ad49ef3d0b8f..3b7b570db29a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/source.py
@@ -1,30 +1,152 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.codacy import (
+ codacy_source,
+ validate_credentials as validate_codacy_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CodacySourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class CodacySource(SimpleSource[CodacySourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CODACY
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The token is sent to api.codacy.com against <provider>/<organization>, so retargeting
+ # either segment must force re-entry of the token rather than reusing the preserved one.
+ return ["provider", "organization"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CODACY,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Codacy",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["code quality", "static analysis", "code coverage"],
+ caption="""Enter your Codacy account API token to automatically pull your Codacy code quality data into the PostHog Data warehouse.
+
+You can generate an account API token in your [Codacy account settings](https://app.codacy.com/account/access-management). The token grants access to the organizations and repositories your Codacy account can see.
+""",
iconPath="/static/services/codacy.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/codacy",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Account API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="provider",
+ label="Git provider",
+ required=True,
+ defaultValue="gh",
+ options=[
+ SourceFieldSelectConfigOption(label="GitHub", value="gh"),
+ SourceFieldSelectConfigOption(label="GitLab", value="gl"),
+ SourceFieldSelectConfigOption(label="Bitbucket", value="bb"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="organization",
+ label="Organization name",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-organization",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.codacy.com": "Your Codacy API token is invalid or has been revoked. Generate a new account API token in your Codacy account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.codacy.com": "Your Codacy API token does not have access to this organization or repository. Check your Codacy account permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CodacySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # No v3 list endpoint exposes a server-side updated-since filter, so every table is
+ # full refresh (the per-organization snapshots are small enough for periodic full pulls).
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: CodacySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_codacy_credentials(config.api_token):
+ return True, None
+
+ return False, "Invalid Codacy API token"
+
+ def source_for_pipeline(self, config: CodacySourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return codacy_source(
+ api_token=config.api_token,
+ provider=config.provider,
+ organization=config.organization,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy.py
new file mode 100644
index 000000000000..451df86837f5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy.py
@@ -0,0 +1,313 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy import codacy
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.codacy import (
+ CodacyRetryableError,
+ _fetch_page,
+ codacy_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.settings import CODACY_ENDPOINTS, ENDPOINTS
+
+BASE = "https://api.codacy.com/api/v3"
+REPOS_URL = f"{BASE}/organizations/gh/acme/repositories?limit=100"
+
+
+def _response_with_status(status_code: int) -> requests.Response:
+ response = requests.Response()
+ response.status_code = status_code
+ return response
+
+
+def _collect(monkeypatch: Any, endpoint: str, pages: dict[str, Any]) -> list[dict]:
+ """Run get_rows against URL-keyed fixtures; a request for an unexpected URL fails loudly."""
+
+ def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger: Any) -> dict:
+ result = pages[url]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(codacy, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for batch in get_rows(api_token="token", provider="gh", organization="acme", endpoint=endpoint, logger=MagicMock()):
+ rows.extend(batch)
+ return rows
+
+
+class TestPagination:
+ def test_follows_cursor_until_final_page_omits_it(self, monkeypatch: Any) -> None:
+ orgs_url = f"{BASE}/user/organizations?limit=100"
+ pages = {
+ orgs_url: {
+ "data": [{"provider": "gh", "remoteIdentifier": "1", "name": "acme"}],
+ "pagination": {"cursor": "c2", "limit": 100},
+ },
+ f"{BASE}/user/organizations?limit=100&cursor=c2": {
+ "data": [{"provider": "gl", "remoteIdentifier": "2", "name": "acme-gl"}],
+ "pagination": {"limit": 100},
+ },
+ }
+ rows = _collect(monkeypatch, "organizations", pages)
+ assert [row["remoteIdentifier"] for row in rows] == ["1", "2"]
+
+ def test_stops_on_empty_page_even_if_cursor_present(self, monkeypatch: Any) -> None:
+ # A page with no items but a cursor must terminate, not loop forever.
+ pages = {
+ f"{BASE}/user/organizations?limit=100": {"data": [], "pagination": {"cursor": "c2", "limit": 100}},
+ }
+ assert _collect(monkeypatch, "organizations", pages) == []
+
+ def test_page_cap_truncates_fan_out_pagination(self, monkeypatch: Any) -> None:
+ files_endpoint = CODACY_ENDPOINTS["files"]
+ monkeypatch.setattr(files_endpoint, "max_pages_per_repository", 2)
+
+ files_base = f"{BASE}/organizations/gh/acme/repositories/repo-a/files"
+ # Every page advertises another cursor; without the cap this would page forever.
+ pages: dict[str, dict[str, Any]] = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ f"{files_base}?limit=100": {"data": [{"path": "a.py"}], "pagination": {"cursor": "c2"}},
+ f"{files_base}?limit=100&cursor=c2": {"data": [{"path": "b.py"}], "pagination": {"cursor": "c3"}},
+ f"{files_base}?limit=100&cursor=c3": {"data": [{"path": "c.py"}], "pagination": {"cursor": "c4"}},
+ }
+ logger = MagicMock()
+
+ def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger_: Any) -> dict:
+ return pages[url]
+
+ monkeypatch.setattr(codacy, "_fetch_page", fake_fetch)
+ rows: list[dict] = []
+ for batch in get_rows(api_token="token", provider="gh", organization="acme", endpoint="files", logger=logger):
+ rows.extend(batch)
+
+ assert [row["path"] for row in rows] == ["a.py", "b.py"]
+ logger.warning.assert_called_once()
+
+
+class TestFanOut:
+ def test_fans_out_over_repositories_and_stamps_repository_onto_rows(self, monkeypatch: Any) -> None:
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}, {"name": "repo-b"}], "pagination": {}},
+ f"{BASE}/organizations/gh/acme/repositories/repo-a/files?limit=100": {
+ "data": [{"path": "src/main.py", "gradeLetter": "A"}],
+ "pagination": {},
+ },
+ f"{BASE}/organizations/gh/acme/repositories/repo-b/files?limit=100": {
+ "data": [{"path": "src/main.py", "gradeLetter": "C"}],
+ "pagination": {},
+ },
+ }
+ rows = _collect(monkeypatch, "files", pages)
+ # The repository name makes the ["repository", "path"] primary key unique table-wide:
+ # both repositories legitimately contain the same path.
+ assert rows == [
+ {"repository": "repo-a", "path": "src/main.py", "gradeLetter": "A"},
+ {"repository": "repo-b", "path": "src/main.py", "gradeLetter": "C"},
+ ]
+
+ def test_repository_removed_mid_sync_is_skipped(self, monkeypatch: Any) -> None:
+ not_found = requests.HTTPError(response=_response_with_status(404))
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}, {"name": "gone"}, {"name": "repo-b"}], "pagination": {}},
+ f"{BASE}/organizations/gh/acme/repositories/repo-a/files?limit=100": {
+ "data": [{"path": "a.py"}],
+ "pagination": {},
+ },
+ f"{BASE}/organizations/gh/acme/repositories/gone/files?limit=100": not_found,
+ f"{BASE}/organizations/gh/acme/repositories/repo-b/files?limit=100": {
+ "data": [{"path": "b.py"}],
+ "pagination": {},
+ },
+ }
+ rows = _collect(monkeypatch, "files", pages)
+ assert [(row["repository"], row["path"]) for row in rows] == [("repo-a", "a.py"), ("repo-b", "b.py")]
+
+ def test_non_404_http_error_propagates(self, monkeypatch: Any) -> None:
+ forbidden = requests.HTTPError(response=_response_with_status(403))
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ f"{BASE}/organizations/gh/acme/repositories/repo-a/files?limit=100": forbidden,
+ }
+ with pytest.raises(requests.HTTPError):
+ _collect(monkeypatch, "files", pages)
+
+
+class TestNormalization:
+ def test_repositories_lift_nested_repository_to_top_level(self, monkeypatch: Any) -> None:
+ # The ["provider", "owner", "name"] primary key only works if the nested `repository`
+ # entity is lifted to top-level columns.
+ pages = {
+ f"{BASE}/analysis/organizations/gh/acme/repositories?limit=100": {
+ "data": [
+ {
+ "repository": {"provider": "gh", "owner": "acme", "name": "repo-a", "repositoryId": 1},
+ "gradeLetter": "B",
+ "issuesCount": 12,
+ }
+ ],
+ "pagination": {},
+ },
+ }
+ rows = _collect(monkeypatch, "repositories", pages)
+ assert rows == [
+ {
+ "provider": "gh",
+ "owner": "acme",
+ "name": "repo-a",
+ "repositoryId": 1,
+ "gradeLetter": "B",
+ "issuesCount": 12,
+ }
+ ]
+
+ def test_pull_requests_lift_nested_pull_request_and_keep_analysis_fields(self, monkeypatch: Any) -> None:
+ pr_url = (
+ f"{BASE}/analysis/organizations/gh/acme/repositories/repo-a/pull-requests?limit=100&includeNotAnalyzed=true"
+ )
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ pr_url: {
+ "data": [
+ {
+ "pullRequest": {"number": 5, "repository": "repo-a", "updated": "2026-06-02T14:47:46Z"},
+ "isUpToStandards": True,
+ "isAnalysing": False,
+ "newIssues": 2,
+ }
+ ],
+ "pagination": {},
+ },
+ }
+ rows = _collect(monkeypatch, "pull_requests", pages)
+ assert rows == [
+ {
+ "repository": "repo-a",
+ "number": 5,
+ "updated": "2026-06-02T14:47:46Z",
+ "isUpToStandards": True,
+ "isAnalysing": False,
+ "newIssues": 2,
+ }
+ ]
+
+ def test_commits_lift_nested_commit_and_stamp_repository(self, monkeypatch: Any) -> None:
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ f"{BASE}/analysis/organizations/gh/acme/repositories/repo-a/commits?limit=100": {
+ "data": [
+ {
+ "commit": {"sha": "abc123", "commitTimestamp": "2026-03-25T10:29:59Z"},
+ "quality": {"newIssues": 0},
+ }
+ ],
+ "pagination": {},
+ },
+ }
+ rows = _collect(monkeypatch, "commits", pages)
+ assert rows == [
+ {
+ "repository": "repo-a",
+ "sha": "abc123",
+ "commitTimestamp": "2026-03-25T10:29:59Z",
+ "quality": {"newIssues": 0},
+ }
+ ]
+
+
+class TestFetchPage:
+ def _json_response(self, status_code: int, payload: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = payload or {}
+ if status_code >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(response=response)
+ return response
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("gateway_timeout", 504)])
+ def test_transient_statuses_are_retried_until_success(self, _name: str, status_code: int) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ self._json_response(status_code),
+ self._json_response(200, {"data": []}),
+ ]
+ with patch.object(_fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = _fetch_page(session, "GET", f"{BASE}/user/organizations", {}, MagicMock())
+ assert result == {"data": []}
+ assert session.get.call_count == 2
+
+ def test_unauthorized_fails_immediately_without_retry(self) -> None:
+ # Retrying a bad token can never succeed; it must surface as a hard HTTPError so
+ # get_non_retryable_errors can disable the source.
+ session = MagicMock()
+ session.get.return_value = self._json_response(401)
+ with patch.object(_fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(requests.HTTPError):
+ _fetch_page(session, "GET", f"{BASE}/user/organizations", {}, MagicMock())
+ assert session.get.call_count == 1
+
+ def test_retryable_error_reraised_after_exhausting_attempts(self) -> None:
+ session = MagicMock()
+ session.get.return_value = self._json_response(503)
+ with patch.object(_fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(CodacyRetryableError):
+ _fetch_page(session, "GET", f"{BASE}/user/organizations", {}, MagicMock())
+ assert session.get.call_count == 5
+
+ def test_issues_search_posts_an_empty_filter_body(self) -> None:
+ # searchRepositoryIssues is POST-only; sending a GET (or omitting the JSON body) breaks
+ # the one endpoint that isn't a plain GET list.
+ session = MagicMock()
+ session.post.return_value = self._json_response(200, {"data": []})
+ result = _fetch_page(session, "POST", f"{BASE}/analysis/.../issues/search", {}, MagicMock())
+ assert result == {"data": []}
+ session.post.assert_called_once()
+ assert session.post.call_args.kwargs["json"] == {}
+ session.get.assert_not_called()
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid_token", 200, True), ("invalid_token", 401, False), ("forbidden", 403, False)])
+ def test_status_code_mapping(self, _name: str, status_code: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status_code)
+ with patch.object(codacy, "make_tracked_session", return_value=session):
+ assert validate_credentials("token") is expected
+
+ def test_connection_error_returns_false(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(codacy, "make_tracked_session", return_value=session):
+ assert validate_credentials("token") is False
+
+
+class TestSourceResponse:
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ def test_primary_keys_match_endpoint_settings(self, endpoint: str) -> None:
+ response = codacy_source(
+ api_token="token", provider="gh", organization="acme", endpoint=endpoint, logger=MagicMock()
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == CODACY_ENDPOINTS[endpoint].primary_keys
+
+ def test_fan_out_children_include_repository_in_primary_key(self) -> None:
+ # A fan-out child keyed without the repository would multi-match on merge once two
+ # repositories share an id (e.g. the same file path), degrading every subsequent sync.
+ for endpoint, config in CODACY_ENDPOINTS.items():
+ if config.fan_out_per_repository:
+ assert config.primary_keys[0] == "repository", endpoint
+
+ def test_commits_partition_on_stable_commit_timestamp(self) -> None:
+ response = codacy_source(
+ api_token="token", provider="gh", organization="acme", endpoint="commits", logger=MagicMock()
+ )
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["commitTimestamp"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy_source.py
new file mode 100644
index 000000000000..88933790083a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy_source.py
@@ -0,0 +1,91 @@
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import (
+ ExternalDataSourceType as SchemaExternalDataSourceType,
+ SourceFieldInputConfig,
+ SourceFieldSelectConfig,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.source import CodacySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CodacySourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> CodacySourceConfig:
+ return CodacySourceConfig(api_token="token", provider="gh", organization="acme")
+
+
+class TestCodacySource:
+ def setup_method(self) -> None:
+ self.source = CodacySource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CODACY
+
+ def test_source_is_visible_to_users(self) -> None:
+ config = self.source.get_source_config
+ assert config.name == SchemaExternalDataSourceType.CODACY
+ assert not config.unreleasedSource
+
+ def test_source_config_collects_token_provider_and_organization(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert [field.name for field in fields] == ["api_token", "provider", "organization"]
+
+ api_token = fields[0]
+ assert isinstance(api_token, SourceFieldInputConfig)
+ assert api_token.secret is True
+
+ provider = fields[1]
+ assert isinstance(provider, SourceFieldSelectConfig)
+ assert [option.value for option in provider.options] == ["gh", "gl", "bb"]
+
+ def test_connection_host_fields_force_token_reentry_on_target_change(self) -> None:
+ # provider and organization pick the Codacy tenant the stored token queries; listing them
+ # forces the update serializer to require the token again when the target changes, instead
+ # of silently reusing the preserved secret against a different organization.
+ assert self.source.connection_host_fields == ["provider", "organization"]
+
+ def test_get_schemas_lists_every_endpoint_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(_config(), team_id=1)
+ assert [schema.name for schema in schemas] == list(ENDPOINTS)
+ # Codacy exposes no server-side updated-since filters, so advertising incremental or
+ # append modes would produce silently wrong (never-updating) tables.
+ assert all(schema.supports_incremental is False for schema in schemas)
+ assert all(schema.supports_append is False for schema in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(_config(), team_id=1, names=["files", "commits"])
+ assert {schema.name for schema in schemas} == {"files", "commits"}
+
+ def test_get_documented_tables_lists_static_catalog(self) -> None:
+ # lists_tables_without_credentials powers the public docs table catalog; it must work
+ # with a placeholder config and no network.
+ tables = self.source.get_documented_tables()
+ assert [table["name"] for table in tables] == list(ENDPOINTS)
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.codacy.source.validate_codacy_credentials")
+ def test_validate_credentials_maps_transport_result(self, mock_validate: MagicMock) -> None:
+ mock_validate.return_value = True
+ assert self.source.validate_credentials(_config(), team_id=1) == (True, None)
+
+ mock_validate.return_value = False
+ ok, error = self.source.validate_credentials(_config(), team_id=1)
+ assert ok is False
+ assert error == "Invalid Codacy API token"
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.codacy.source.codacy_source")
+ def test_source_for_pipeline_plumbs_config_and_schema(self, mock_codacy_source: MagicMock) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "files"
+
+ response = self.source.source_for_pipeline(_config(), inputs)
+
+ assert response is mock_codacy_source.return_value
+ mock_codacy_source.assert_called_once_with(
+ api_token="token",
+ provider="gh",
+ organization="acme",
+ endpoint="files",
+ logger=inputs.logger,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index eb143a235b91..485cf7ce8b5d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -915,7 +915,9 @@ class CodaSourceConfig(config.Config):
@config.config
class CodacySourceConfig(config.Config):
- pass
+ api_token: str
+ organization: str
+ provider: Literal["gh", "gl", "bb"] = config.value(default="gh")
@config.config