Skip to content

Commit 09b02fe

Browse files
committed
chore(ci): Warn on updated SDK names in PRs
Introduces a sdk-name-check workflow that detects new, removed, or modified SDK name constants in Config.kt. If one is found, the workflow posts an issue comment on the PR, similar to what we currently do for dangerous code changes. Helps us ensure that the [sdk_name spreadsheet](https://docs.google.com/spreadsheets/d/1hqFhytQuHMvuOz1XD0kCXg6x0ViflHrpjW7nNhvzYmU/edit?gid=334165604#gid=334165604) used for Looker/Hex queries stays fresh.
1 parent f037273 commit 09b02fe

5 files changed

Lines changed: 429 additions & 0 deletions

File tree

‎.github/file-filters.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,11 @@ high_risk_code: &high_risk_code
1010

1111
# Class used by hybrid SDKs
1212
- "sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java"
13+
14+
config_kt:
15+
- "buildSrc/src/main/java/Config.kt"
16+
17+
sdk_name_check_scripts:
18+
- ".github/workflows/sdk-name-check.yml"
19+
- "scripts/detect_sdk_name_changes.py"
20+
- "scripts/test_detect_sdk_name_changes.py"
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# When sdk.name values are added, removed, or updated in Config.kt, posts a PR comment
2+
# reminding authors to update the sdk_map spreadsheet for Looker/Hex reporting.
3+
# Warn-only: does not block merge. See scripts/detect_sdk_name_changes.py.
4+
name: 'SDK Name Check'
5+
run-name: sdk.name change check (Config.kt)
6+
7+
on:
8+
pull_request:
9+
types: [opened, synchronize, reopened]
10+
11+
concurrency:
12+
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
13+
cancel-in-progress: true
14+
15+
jobs:
16+
files-changed:
17+
name: Detect changed files
18+
runs-on: ubuntu-latest
19+
outputs:
20+
config_kt: ${{ steps.changes.outputs.config_kt }}
21+
sdk_name_check_scripts: ${{ steps.changes.outputs.sdk_name_check_scripts }}
22+
steps:
23+
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
24+
- name: Get changed files
25+
id: changes
26+
uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1
27+
with:
28+
token: ${{ github.token }}
29+
filters: .github/file-filters.yml
30+
31+
sdk-name-check:
32+
name: ${{ needs.files-changed.outputs.config_kt == 'true' && 'SDK name check' || 'SDK name detector tests' }}
33+
if: needs.files-changed.outputs.config_kt == 'true' || needs.files-changed.outputs.sdk_name_check_scripts == 'true'
34+
needs: files-changed
35+
runs-on: ubuntu-latest
36+
permissions:
37+
pull-requests: write
38+
steps:
39+
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
40+
with:
41+
fetch-depth: ${{ needs.files-changed.outputs.config_kt == 'true' && 0 || 1 }}
42+
43+
- name: Run detector unit tests
44+
run: python3 -m unittest discover -s scripts -p 'test_detect_sdk_name_changes.py'
45+
46+
- name: Detect SDK name changes
47+
if: needs.files-changed.outputs.config_kt == 'true'
48+
id: detect
49+
run: |
50+
changes=$(python3 scripts/detect_sdk_name_changes.py \
51+
--base "${{ github.event.pull_request.base.sha }}" \
52+
--head "${{ github.sha }}")
53+
echo "changes=${changes}" >> "$GITHUB_OUTPUT"
54+
55+
- name: Update PR comment
56+
if: needs.files-changed.outputs.config_kt == 'true'
57+
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
58+
env:
59+
SDK_NAME_CHANGES: ${{ steps.detect.outputs.changes }}
60+
with:
61+
script: |
62+
const marker = '<!-- sdk-name-check -->';
63+
const changes = JSON.parse(process.env.SDK_NAME_CHANGES || '{}');
64+
const added = changes.added || [];
65+
const removed = changes.removed || [];
66+
const sheetUrl = changes.sdk_map_sheet_url;
67+
68+
const { data: comments } = await github.rest.issues.listComments({
69+
owner: context.repo.owner,
70+
repo: context.repo.repo,
71+
issue_number: context.issue.number,
72+
});
73+
74+
const existing = comments.find(
75+
(comment) =>
76+
comment.body?.includes(marker) &&
77+
comment.user?.type === 'Bot',
78+
);
79+
80+
if (added.length === 0 && removed.length === 0) {
81+
if (existing) {
82+
await github.rest.issues.deleteComment({
83+
owner: context.repo.owner,
84+
repo: context.repo.repo,
85+
comment_id: existing.id,
86+
});
87+
}
88+
return;
89+
}
90+
91+
const formatList = (names) => names.map((name) => `- \`${name}\``).join('\n');
92+
const sections = ['### ⚠️ SDK name changes detected', ''];
93+
94+
if (added.length > 0) {
95+
sections.push(
96+
'This PR adds new `sdk.name` value(s) that will appear in production telemetry:',
97+
'',
98+
formatList(added),
99+
'',
100+
`Please add them to the [sdk_map spreadsheet](${sheetUrl}) so Looker/Hex reporting stays accurate.`,
101+
'',
102+
);
103+
}
104+
105+
if (removed.length > 0) {
106+
sections.push(
107+
'This PR removes `sdk.name` value(s) from production telemetry:',
108+
'',
109+
formatList(removed),
110+
'',
111+
`Please remove them from the [sdk_map spreadsheet](${sheetUrl}).`,
112+
'',
113+
);
114+
}
115+
116+
sections.push(marker);
117+
const body = sections.join('\n');
118+
119+
if (existing) {
120+
await github.rest.issues.updateComment({
121+
owner: context.repo.owner,
122+
repo: context.repo.repo,
123+
comment_id: existing.id,
124+
body,
125+
});
126+
return;
127+
}
128+
129+
await github.rest.issues.createComment({
130+
owner: context.repo.owner,
131+
repo: context.repo.repo,
132+
issue_number: context.issue.number,
133+
body,
134+
});

‎buildSrc/src/main/java/Config.kt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ object Config {
4040
}
4141

4242
object Sentry {
43+
// New *SDK_NAME constants are checked by .github/workflows/sdk-name-check.yml. When making changes, be sure to update the sdk_map
44+
// spreadsheet used for Looker/Hex reporting:
45+
// https://docs.google.com/spreadsheets/d/1hqFhytQuHMvuOz1XD0kCXg6x0ViflHrpjW7nNhvzYmU/edit?gid=334165604#gid=334165604
4346
val SENTRY_JAVA_SDK_NAME = "sentry.java"
4447
val SENTRY_ANDROID_SDK_NAME = "$SENTRY_JAVA_SDK_NAME.android"
4548
val SENTRY_TIMBER_SDK_NAME = "$SENTRY_ANDROID_SDK_NAME.timber"

‎scripts/detect_sdk_name_changes.py‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
#!/usr/bin/env python3
2+
"""Detect added and removed sdk.name values in Config.kt between two revisions."""
3+
4+
from __future__ import annotations
5+
6+
import argparse
7+
import json
8+
import re
9+
import subprocess
10+
import sys
11+
from pathlib import Path
12+
13+
CONFIG_PATH = "buildSrc/src/main/java/Config.kt"
14+
SDK_MAP_SHEET_URL = (
15+
"https://docs.google.com/spreadsheets/d/1hqFhytQuHMvuOz1XD0kCXg6x0ViflHrpjW7nNhvzYmU/"
16+
"edit?gid=334165604"
17+
)
18+
SDK_NAME_PATTERN = re.compile(r"^\s*val (\w+SDK_NAME) = (.+)$")
19+
STRING_LITERAL = re.compile(r'^"((?:[^"\\]|\\.)*)"$')
20+
INTERPOLATION_PATTERN = re.compile(r"\$([A-Za-z0-9_]+)")
21+
22+
23+
def parse_sdk_constants(content: str) -> dict[str, str]:
24+
"""Return mapping of constant name to resolved sdk.name string."""
25+
resolved: dict[str, str] = {}
26+
for line in content.splitlines():
27+
match = SDK_NAME_PATTERN.match(line)
28+
if not match:
29+
continue
30+
name, rhs = match.group(1), match.group(2).strip()
31+
resolved[name] = resolve_rhs(rhs, resolved)
32+
return resolved
33+
34+
35+
def resolve_rhs(rhs: str, resolved: dict[str, str]) -> str:
36+
literal = STRING_LITERAL.match(rhs)
37+
if not literal:
38+
raise ValueError(f"Cannot parse SDK name assignment: {rhs}")
39+
return expand_interpolation(literal.group(1), resolved)
40+
41+
42+
def expand_interpolation(value: str, resolved: dict[str, str]) -> str:
43+
def replace(match: re.Match[str]) -> str:
44+
name = match.group(1)
45+
if name not in resolved:
46+
raise ValueError(f"Unknown SDK name constant: {name}")
47+
return resolved[name]
48+
49+
return INTERPOLATION_PATTERN.sub(replace, value)
50+
51+
52+
def find_sdk_name_changes(
53+
base: dict[str, str], head: dict[str, str]
54+
) -> tuple[list[str], list[str]]:
55+
base_values = set(base.values())
56+
head_values = set(head.values())
57+
added = sorted(head_values - base_values)
58+
removed = sorted(base_values - head_values)
59+
return added, removed
60+
61+
62+
def git_merge_base(base: str, head: str) -> str:
63+
return subprocess.check_output(
64+
["git", "merge-base", base, head],
65+
text=True,
66+
stderr=subprocess.PIPE,
67+
).strip()
68+
69+
70+
def git_show(ref: str, path: str) -> str:
71+
try:
72+
return subprocess.check_output(
73+
["git", "show", f"{ref}:{path}"],
74+
text=True,
75+
stderr=subprocess.PIPE,
76+
)
77+
except subprocess.CalledProcessError as error:
78+
if error.returncode == 128 and "exists on disk, but not in" in error.stderr:
79+
return ""
80+
raise
81+
82+
83+
def read_config_source(base: str | None, head: str | None, config_path: str) -> tuple[str, str]:
84+
if base is None or head is None:
85+
raise ValueError("Both base and head refs are required")
86+
merge_base = git_merge_base(base, head)
87+
return git_show(merge_base, config_path), git_show(head, config_path)
88+
89+
90+
def format_changes(added: list[str], removed: list[str]) -> str:
91+
return json.dumps(
92+
{
93+
"added": added,
94+
"removed": removed,
95+
"sdk_map_sheet_url": SDK_MAP_SHEET_URL,
96+
},
97+
separators=(",", ":"),
98+
)
99+
100+
101+
def main(argv: list[str] | None = None) -> int:
102+
parser = argparse.ArgumentParser(
103+
description="Print added and removed sdk.name values as JSON."
104+
)
105+
parser.add_argument("--base", help="Git ref for the PR base revision")
106+
parser.add_argument("--head", help="Git ref for the PR head revision")
107+
parser.add_argument("--base-file", type=Path, help="Base Config.kt file")
108+
parser.add_argument("--head-file", type=Path, help="Head Config.kt file")
109+
parser.add_argument("--config-path", default=CONFIG_PATH)
110+
args = parser.parse_args(argv)
111+
112+
if args.base_file and args.head_file:
113+
base_content = args.base_file.read_text(encoding="utf-8")
114+
head_content = args.head_file.read_text(encoding="utf-8")
115+
elif args.base and args.head:
116+
base_content, head_content = read_config_source(
117+
args.base, args.head, args.config_path
118+
)
119+
else:
120+
parser.error("Provide --base/--head or --base-file/--head-file")
121+
122+
try:
123+
base_sdk = parse_sdk_constants(base_content)
124+
head_sdk = parse_sdk_constants(head_content)
125+
except ValueError as error:
126+
print(f"error: {error}", file=sys.stderr)
127+
return 1
128+
129+
added, removed = find_sdk_name_changes(base_sdk, head_sdk)
130+
print(format_changes(added, removed))
131+
return 0
132+
133+
134+
if __name__ == "__main__":
135+
sys.exit(main())

0 commit comments

Comments
 (0)