Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.

feat(build): collect git/VCS metadata for build upload - #1174

Merged
BYK merged 4 commits into
mainfrom
byk/feat/build-vcs-metadata
Jul 2, 2026
Merged

BYK merged 4 commits into
mainfrom
byk/feat/build-vcs-metadata

Conversation

@BYK

@BYK BYK commented Jul 2, 2026

Copy link
Copy Markdown
Member

Third PR of the build/Emerge workstream (after build download #1170, build upload #1172). Brings build upload to VCS parity and lays the groundwork snapshots will reuse.

What

build upload now attaches VCS metadata to the assemble request. Per the server's flattened VcsInfo, these are top-level body fields (omit-if-empty): head_sha, base_sha, provider, head_repo_name, base_repo_name, head_ref, base_ref, pr_number.

Precedence (mirrors the legacy collect_git_metadata):

  • Explicit flags always win: --head-sha, --base-sha, --vcs-provider, --head-repo-name, --base-repo-name, --head-ref, --base-ref, --pr-number.
  • Auto-collection runs in CI (unless --no-git-metadata) or when --force-git-metadata is set:
    • GitHub Actions env: GITHUB_HEAD_REF/GITHUB_BASE_REF (pull_request), GITHUB_REPOSITORY, PR number from GITHUB_REF (refs/pull/N/merge), head ref from GITHUB_REF_NAME for pushes.
    • Local git: HEAD sha, current branch, remote → provider + repo name, and a best-effort merge-base for base_sha.
  • Base is dropped when it equals head and both were auto-inferred (meaningless comparison), matching legacy.

Files

  • src/lib/build/vcs.ts — collectVcsMetadata, isCi, vcsInfoToBody (per-field resolver helpers keep complexity low).
  • src/lib/git.ts — additive helpers: getRemoteUrl, getCurrentBranch, getMergeBase (execFile, no shell; match the module's existing style).
  • src/lib/api/preprod-artifacts.ts — BuildUploadMetadata.vcs flattened into the assemble body.
  • src/commands/build/upload.ts — 10 git flags + collection wired in.
  • Tests (15 new): flag precedence, GitHub Actions PR inference, base==head skip, vcsInfoToBody mapping, and a command-level assertion that flags reach the body.

Notes / follow-ups

  • base_repo_name fork auto-detection and non-GitHub CI providers are not yet inferred (explicit flags still work); a follow-up can extend inference. base_sha auto-inference is best-effort (skipped on shallow clones / unknown refs).

typecheck, lint, check:deps, check:fragments all pass.

Ports `collect_git_metadata`: `build upload` now attaches VCS metadata to the
assemble request (flattened top-level fields: head_sha, base_sha, provider,
head_repo_name, base_repo_name, head_ref, base_ref, pr_number).

Explicit flags always win (--head-sha, --base-sha, --vcs-provider,
--head-repo-name, --base-repo-name, --head-ref, --base-ref, --pr-number). When
auto-collection is enabled — in CI unless --no-git-metadata, or forced via
--force-git-metadata — values are inferred from GitHub Actions env vars
(GITHUB_HEAD_REF/BASE_REF/REPOSITORY/REF) and the local git repo (HEAD sha,
current branch, remote provider/repo, merge-base for base_sha). Base is dropped
when it equals head and both were auto-inferred (matches legacy).

New: src/lib/build/vcs.ts (collectVcsMetadata, isCi, vcsInfoToBody) + git.ts
helpers (getRemoteUrl, getCurrentBranch, getMergeBase).
@github-actions

github-actions Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://cli.sentry.dev/_preview/pr-1174/

Built to branch gh-pages at 2026-07-02 17:15 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

Comment thread src/commands/build/upload.ts Resolved
Comment thread src/lib/build/vcs.ts Resolved
Comment thread src/lib/build/vcs.ts Resolved
@github-actions

github-actions Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Codecov Results 📊

❌ Patch coverage is 75.20%. Project has 5174 uncovered lines.
❌ Project coverage is 81.59%. Comparing base (base) to head (head).

Files with missing lines (3)
File Patch % Lines
src/lib/build/vcs.ts 90.91% ⚠️ 9 Missing and 10 partials
src/lib/git.ts 0.00% ⚠️ 17 Missing
src/commands/build/upload.ts 37.50% ⚠️ 5 Missing and 1 partials
Coverage diff
@@            Coverage Diff             @@
##          main       #PR       +/-##
==========================================
- Coverage    81.62%    81.59%    -0.03%
==========================================
  Files          404       405        +1
  Lines        27978     28103      +125
  Branches     18176     18308      +132
==========================================
+ Hits         22835     22929       +94
- Misses        5143      5174       +31
- Partials      1870      1881       +11

Generated by Codecov Action

Self-review findings:
- H1 (high): read PR head/base SHAs from GITHUB_EVENT_PATH first. On
  pull_request runs `git rev-parse HEAD` is the ephemeral merge commit (not the
  PR head) and shallow clones break merge-base, so the event payload
  (pull_request.{head,base}.sha) is authoritative — matches the legacy CLI.
- base_sha auto now uses merge-base with the remote default branch
  (refs/remotes/origin/HEAD); base_ref falls back to the default branch too.
- M3: a present-but-empty --head-sha/--base-sha explicitly clears and suppresses
  auto-inference (matches parse_sha_allow_empty).
- M4: validate --head-sha/--base-sha as 40-char hex SHA-1.
- M5: --pr-number must be a non-negative integer.
- M6: *.ghe.com → provider "github_enterprise".
- L1: head_repo_name comes from the git remote only (matches legacy).
- L2: error when --force-git-metadata and --no-git-metadata are combined.
- L4: getMergeBase rejects option-like ("-"-prefixed) refs.
- Tests: event-payload SHAs, empty-clear, SHA/pr-number validation, SCP + GHE
  provider parsing, base lowercasing, top-level vcs flatten in the assemble body.
@BYK

BYK commented Jul 2, 2026

Copy link
Copy Markdown
Member Author

Self-review (subagent-assisted) + fixes

Reviewed against the legacy Rust. One real correctness blocker found and fixed, plus validation hardening:

H1 (was broken for the headline use case): on GitHub Actions pull_request runs, actions/checkout checks out the ephemeral merge commit, so git rev-parse HEAD is not the PR head, and default shallow clones break merge-base. Now reads GITHUB_EVENT_PATH → pull_request.{head,base}.sha first (matches legacy find_head_sha/find_base_sha), falling back to git. base_sha auto also uses merge-base with the remote default branch.

Also fixed: empty --head-sha/--base-sha = explicit clear (suppresses auto); 40-hex SHA validation; --pr-number must be a non-negative integer; *.ghe.com → github_enterprise; head_repo_name from git remote only (legacy parity); error on --force-git-metadata + --no-git-metadata; getMergeBase rejects --prefixed refs. Added tests incl. event-payload SHAs and the top-level vcs flatten in the assemble body.

Documented follow-ups (explicit flags cover these today): full base_ref/base_repo_name git inference for fork PRs and non-GitHub CI providers is best-effort; a follow-up can extend it.

Comment thread src/lib/build/vcs.ts Resolved
Comment thread src/lib/build/vcs.ts
Comment on lines +229 to +235
function resolveHeadRepoName(
flags: VcsFlags,
cwd: string,
auto: boolean
): string | undefined {
return flags["head-repo-name"] || (auto ? getRepositoryName(cwd) : undefined);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: The resolveHeadRepoName function doesn't use the GITHUB_REPOSITORY environment variable in GitHub Actions. It incorrectly relies on parsing the git remote URL, which can be unreliable.
Severity: MEDIUM

Suggested Fix

Update the resolveHeadRepoName function to accept an env parameter. Add logic to check for env.GITHUB_ACTIONS and env.GITHUB_REPOSITORY and use that value if available. This will align the implementation with the documented behavior and other similar functions like githubHeadRef().

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: src/lib/build/vcs.ts#L229-L235

Potential issue: The `resolveHeadRepoName` function is intended to infer the repository
name from the `GITHUB_REPOSITORY` environment variable when running in GitHub Actions,
as stated in the PR description. However, the implementation does not accept an `env`
parameter and instead calls `getRepositoryName(cwd)`, which parses the git remote URL.
This can lead to an incorrect repository name being reported in environments with
non-standard git configurations, such as forks or mirrors, because the remote URL may
not match the canonical repository name provided by `GITHUB_REPOSITORY`. The associated
test passes only because `getRepositoryName` is mocked to return the expected value,
hiding the bug.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intentional: head_repo_name is derived from the git remote only, matching the legacy CLI (collect_git_metadata → get_repo_from_remote_preserve_case on the remote URL — it never consults GITHUB_REPOSITORY). In GitHub Actions the origin remote is configured by actions/checkout, so the git-remote path already covers that case; adding GITHUB_REPOSITORY would diverge from the port source and could disagree with provider (which is remote-derived). Keeping remote-only for parity.

- isCi: treat "false"/"0" (and "") as not-in-CI so a local `CI=false` doesn't
  silently enable git-metadata collection.
- resolveBaseSha: honor an explicit/known base ref for the merge-base (was
  always using the remote default branch), falling back to origin/HEAD.

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 64c68eb. Configure here.

Comment thread src/lib/build/vcs.ts
if (!auto) {
return undefined;
}
return readGithubEventSha("head", env) ?? tryGitHeadSha(cwd);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR head falls back merge commit

Medium Severity

On GitHub Actions pull_request runs, resolveHeadSha falls back to git rev-parse HEAD whenever the event payload does not yield a valid head SHA (missing GITHUB_EVENT_PATH, parse failure, or invalid pull_request.head.sha). That checkout is the ephemeral merge commit, not the PR head, so uploads can report the wrong head_sha despite the module documenting that event SHAs are authoritative for PRs.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 64c68eb. Configure here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Working as intended — this matches the legacy CLI, whose find_head_sha uses the identical fallback (event payload → git rev-parse HEAD). On real GitHub Actions pull_request runs GITHUB_EVENT_PATH is always set and points at a valid payload, so the authoritative pull_request.head.sha path is taken; the git fallback only fires when the payload is genuinely absent/corrupt, where there is no better source (both git HEAD and GITHUB_SHA are the merge commit). Declining to add speculative HEAD^2 parsing that the port source doesn't do.

@BYK
BYK merged commit 504316f into main Jul 2, 2026
32 checks passed
@BYK
BYK deleted the byk/feat/build-vcs-metadata branch July 2, 2026 17:29
BYK added a commit that referenced this pull request Jul 2, 2026
Fourth PR of the **build/Emerge** workstream (after `build download`
#1170, `build upload` #1172, VCS metadata #1174). Establishes the
**`snapshots`** command group and its first subcommand.

## `snapshots download`
Downloads baseline snapshot images from Sentry's preprod system and
extracts them locally. **Sentry SaaS only.**

- **Resolve the snapshot**: `--snapshot-id <id>` (direct) or `--app-id
<app>` → latest baseline (optional `--branch`; `--project` numeric ID
for org auth tokens). The two ID flags are mutually exclusive;
`--branch` requires `--app-id`.
- **Ensure the archive is built**: checks status, and if not ready
triggers a build and polls (2s interval, 5-min timeout via
`TimeoutError`).
- **Download + extract**: downloads the archive ZIP and extracts images
to `--output` (default `./snapshots-base/`), with **Zip-Slip
protection** (entries escaping the output dir are skipped).

## Files
- `src/lib/api/preprod-artifacts.ts` — `getLatestBaseSnapshot` (404 →
`null`), `getSnapshotArchiveReady`, `triggerSnapshotArchiveBuild`,
`waitForSnapshotArchive`, `downloadSnapshotArchive` (auth dropped
cross-origin on the storage redirect).
- `src/lib/snapshots/archive.ts` — `extractZipToDir` (fflate,
path-traversal safe).
- `src/commands/snapshots/{download,index}.ts` + `app.ts` registration.
- Tests (11 new): extraction incl. Zip-Slip; API incl. 404→null and
trigger→poll→ready; command flag validation + app-id resolution + real
extraction.

## Follow-ups (not in this PR)
`snapshots diff` (needs an image-diff dependency decision — native
`odiff` vs pure-JS); `snapshots upload` (blocked on the objectstore
session).

`typecheck`, `lint`, `check:deps`, `check:fragments` all pass.
BYK added a commit that referenced this pull request Jul 3, 2026
Extends `build upload` (Android APK/AAB, PRs #1172/#1174) to **iOS** —
XCArchive and IPA.

## What
- **XCArchive** (a directory): zipped under its basename
(`MyApp.xcarchive/…`) + a root `.sentry-cli-metadata.txt`, mirroring the
legacy `normalize_directory`.
- **IPA** (a file): converted **in-memory** to an XCArchive layout —
`Payload/<app>.app/…` →
`archive.xcarchive/Products/Applications/<app>.app/…` plus a generated
`archive.xcarchive/Info.plist` — mirroring `ipa_to_xcarchive` +
`normalize_directory`. Requires exactly one `.app`.

Both use STORE + a fixed mtime so identical inputs produce identical
bytes (chunk dedup on re-upload).

## Cross-platform (intentional divergence from the Rust CLI)
The legacy CLI gated iOS to **Apple Silicon** solely because
`handle_asset_catalogs` parses `Assets.car` via native macOS CoreUI
(`apple_catalog_parsing`). Per the agreed scope we **skip `.car`
parsing**, and with that removed the entire iOS path (`ipa_to_xcarchive`
is pure zip + a static plist string; `normalize_directory` is a plain
directory walk) is portable — so iOS upload ships on **all platforms**,
no Apple-Silicon gate.

## Documented limitations
- No `Assets.car` asset-catalog parsing → server sees the raw `.car`,
not a per-image breakdown.
- Directory symlinks are followed and stored as target content (not
preserved as symlink entries); Unix permissions are not preserved (a
`zipSync` limitation). iOS `.app` bundles are typically flat, so this is
rarely material.
- In-memory normalization (same as the Android path) — a very large
XCArchive with dSYMs could hit Node's ~2 GiB Buffer cap;
streaming-to-temp-file is a noted follow-up.

## Tests
Lib: XCArchive dir → zip structure + determinism; IPA → XCArchive
structure + generated Info.plist + `Assets.car` passed through verbatim;
`extractIpaAppName` for 0/1/≥2 `.app`. Command: XCArchive directory +
IPA both reach `uploadBuild`; obsolete "not supported" cases replaced.

`typecheck`, `lint`, `check:deps`, `check:fragments` pass; 44 build
tests pass.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant