Skip to content

Commit 791ccca

Browse files
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.Sentry. (By convention, all envelope `sdk.name` values live in Config.Sentry.) If an update 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. -------------------------- Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent f037273 commit 791ccca

5 files changed

Lines changed: 462 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: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
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+
# Fork PRs cannot post comments (read-only GITHUB_TOKEN on pull_request).
5+
name: 'SDK Name Check'
6+
run-name: sdk.name change check (Config.kt)
7+
8+
on:
9+
pull_request:
10+
types: [opened, synchronize, reopened]
11+
12+
concurrency:
13+
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
14+
cancel-in-progress: true
15+
16+
jobs:
17+
files-changed:
18+
name: Detect changed files
19+
runs-on: ubuntu-latest
20+
outputs:
21+
config_kt: ${{ steps.changes.outputs.config_kt }}
22+
sdk_name_check_scripts: ${{ steps.changes.outputs.sdk_name_check_scripts }}
23+
steps:
24+
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
25+
- name: Get changed files
26+
id: changes
27+
uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1
28+
with:
29+
token: ${{ github.token }}
30+
filters: .github/file-filters.yml
31+
32+
sdk-name-check:
33+
name: SDK name check
34+
if: needs.files-changed.outputs.config_kt == 'true' || needs.files-changed.outputs.sdk_name_check_scripts == 'true'
35+
needs: files-changed
36+
runs-on: ubuntu-latest
37+
permissions:
38+
pull-requests: write
39+
steps:
40+
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
41+
with:
42+
fetch-depth: 0
43+
44+
- name: Run detector unit tests
45+
run: python3 -m unittest discover -s scripts -p 'test_detect_sdk_name_changes.py'
46+
47+
- name: Detect SDK name changes
48+
if: needs.files-changed.outputs.config_kt == 'true'
49+
continue-on-error: true
50+
id: detect
51+
run: |
52+
git fetch --no-tags origin \
53+
"${{ github.event.pull_request.base.sha }}" \
54+
"${{ github.event.pull_request.head.sha }}"
55+
changes=$(python3 scripts/detect_sdk_name_changes.py \
56+
--base "${{ github.event.pull_request.base.sha }}" \
57+
--head "${{ github.event.pull_request.head.sha }}")
58+
echo "changes=${changes}" >> "$GITHUB_OUTPUT"
59+
60+
# Fork PRs get a read-only GITHUB_TOKEN (see header); skip comment writes to avoid 403 failures.
61+
- name: Update PR comment
62+
if: needs.files-changed.outputs.config_kt == 'true' && github.event.pull_request.head.repo.full_name == github.repository
63+
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
64+
env:
65+
SDK_NAME_CHANGES: ${{ steps.detect.outputs.changes }}
66+
DETECT_OUTCOME: ${{ steps.detect.outcome }}
67+
with:
68+
script: |
69+
const marker = '<!-- sdk-name-check -->';
70+
71+
const comments = await github.paginate(github.rest.issues.listComments, {
72+
owner: context.repo.owner,
73+
repo: context.repo.repo,
74+
issue_number: context.issue.number,
75+
});
76+
77+
const existing = comments.find(
78+
(comment) =>
79+
comment.body?.includes(marker) &&
80+
comment.user?.type === 'Bot',
81+
);
82+
83+
const upsertComment = async (body) => {
84+
if (existing) {
85+
await github.rest.issues.updateComment({
86+
owner: context.repo.owner,
87+
repo: context.repo.repo,
88+
comment_id: existing.id,
89+
body,
90+
});
91+
return;
92+
}
93+
94+
await github.rest.issues.createComment({
95+
owner: context.repo.owner,
96+
repo: context.repo.repo,
97+
issue_number: context.issue.number,
98+
body,
99+
});
100+
};
101+
102+
if (process.env.DETECT_OUTCOME === 'failure') {
103+
await upsertComment(
104+
[
105+
'### ⚠️ SDK name check failed',
106+
'',
107+
'Could not compare `*SDK_NAME` declarations in `Config.kt`. Use `val FOO_SDK_NAME = "..."` with an optional `$OTHER_SDK_NAME` prefix.',
108+
'',
109+
'See the **Detect SDK name changes** step logs for details.',
110+
'',
111+
marker,
112+
].join('\n'),
113+
);
114+
return;
115+
}
116+
117+
const changes = JSON.parse(process.env.SDK_NAME_CHANGES || '{}');
118+
const added = changes.added || [];
119+
const removed = changes.removed || [];
120+
const sheetUrl = changes.sdk_map_sheet_url;
121+
122+
if (added.length === 0 && removed.length === 0) {
123+
if (existing) {
124+
await github.rest.issues.deleteComment({
125+
owner: context.repo.owner,
126+
repo: context.repo.repo,
127+
comment_id: existing.id,
128+
});
129+
}
130+
return;
131+
}
132+
133+
const formatList = (names) => names.map((name) => `- \`${name}\``).join('\n');
134+
const sections = ['### ⚠️ SDK name changes detected', ''];
135+
136+
if (added.length > 0) {
137+
sections.push(
138+
'This PR adds new `sdk.name` value(s) that will appear in production telemetry:',
139+
'',
140+
formatList(added),
141+
'',
142+
`Please add them to the [sdk_map spreadsheet](${sheetUrl}) so Looker/Hex reporting stays accurate.`,
143+
'',
144+
);
145+
}
146+
147+
if (removed.length > 0) {
148+
sections.push(
149+
'This PR removes `sdk.name` value(s) from production telemetry:',
150+
'',
151+
formatList(removed),
152+
'',
153+
`Please remove them from the [sdk_map spreadsheet](${sheetUrl}).`,
154+
'',
155+
);
156+
}
157+
158+
sections.push(marker);
159+
await upsertComment(sections.join('\n'));

buildSrc/src/main/java/Config.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ object Config {
4040
}
4141

4242
object Sentry {
43+
// .github/workflows/sdk-name-check.yml expects all SDK name declarations to end in `*SDK_NAME`.
4344
val SENTRY_JAVA_SDK_NAME = "sentry.java"
4445
val SENTRY_ANDROID_SDK_NAME = "$SENTRY_JAVA_SDK_NAME.android"
4546
val SENTRY_TIMBER_SDK_NAME = "$SENTRY_ANDROID_SDK_NAME.timber"

scripts/detect_sdk_name_changes.py

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
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+
if "${" in value:
44+
raise ValueError(f"Unsupported brace interpolation in SDK name value: {value}")
45+
46+
def replace(match: re.Match[str]) -> str:
47+
name = match.group(1)
48+
if name not in resolved:
49+
raise ValueError(f"Unknown SDK name constant: {name}")
50+
return resolved[name]
51+
52+
return INTERPOLATION_PATTERN.sub(replace, value)
53+
54+
55+
def find_sdk_name_changes(
56+
base: dict[str, str], head: dict[str, str]
57+
) -> tuple[list[str], list[str]]:
58+
base_values = set(base.values())
59+
head_values = set(head.values())
60+
added = sorted(head_values - base_values)
61+
removed = sorted(base_values - head_values)
62+
return added, removed
63+
64+
65+
def git_show(ref: str, path: str) -> str:
66+
try:
67+
return subprocess.check_output(
68+
["git", "show", f"{ref}:{path}"],
69+
text=True,
70+
stderr=subprocess.PIPE,
71+
)
72+
except subprocess.CalledProcessError as error:
73+
if error.returncode == 128 and "exists on disk, but not in" in error.stderr:
74+
return ""
75+
raise
76+
77+
78+
def read_config_source(base: str | None, head: str | None, config_path: str) -> tuple[str, str]:
79+
if base is None or head is None:
80+
raise ValueError("Both base and head refs are required")
81+
return git_show(base, config_path), git_show(head, config_path)
82+
83+
84+
def format_changes(added: list[str], removed: list[str]) -> str:
85+
return json.dumps(
86+
{
87+
"added": added,
88+
"removed": removed,
89+
"sdk_map_sheet_url": SDK_MAP_SHEET_URL,
90+
},
91+
separators=(",", ":"),
92+
)
93+
94+
95+
def main(argv: list[str] | None = None) -> int:
96+
parser = argparse.ArgumentParser(
97+
description="Print added and removed sdk.name values as JSON."
98+
)
99+
parser.add_argument("--base", help="Git ref for the PR base revision")
100+
parser.add_argument("--head", help="Git ref for the PR head revision")
101+
parser.add_argument("--base-file", type=Path, help="Base Config.kt file")
102+
parser.add_argument("--head-file", type=Path, help="Head Config.kt file")
103+
parser.add_argument("--config-path", default=CONFIG_PATH)
104+
args = parser.parse_args(argv)
105+
106+
try:
107+
if args.base_file and args.head_file:
108+
base_content = args.base_file.read_text(encoding="utf-8")
109+
head_content = args.head_file.read_text(encoding="utf-8")
110+
elif args.base and args.head:
111+
base_content, head_content = read_config_source(
112+
args.base, args.head, args.config_path
113+
)
114+
else:
115+
parser.error("Provide --base/--head or --base-file/--head-file")
116+
117+
base_sdk = parse_sdk_constants(base_content)
118+
head_sdk = parse_sdk_constants(head_content)
119+
except ValueError as error:
120+
print(f"error: {error}", file=sys.stderr)
121+
return 1
122+
except subprocess.CalledProcessError as error:
123+
print(f"error: git command failed: {' '.join(error.cmd)}", file=sys.stderr)
124+
return 1
125+
126+
added, removed = find_sdk_name_changes(base_sdk, head_sdk)
127+
print(format_changes(added, removed))
128+
return 0
129+
130+
131+
if __name__ == "__main__":
132+
sys.exit(main())

0 commit comments

Comments
 (0)