Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions packages/bundler-plugins/src/core/cli.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createSentrySDK } from 'sentry';
import type { NormalizedOptions } from './options-mapping';
import type { SetCommitsOptions } from './types';
import { arrayify, getProjects } from './utils';
import { arrayify, getGitRemoteRepository, getProjects, gitRevision } from './utils';

type SentrySDK = ReturnType<typeof createSentrySDK>;
type SentryOptions = NonNullable<Parameters<typeof createSentrySDK>[0]>;
Expand Down Expand Up @@ -86,14 +86,21 @@ export class SentryCliAdapter {
*/
public async setCommits(name: string, setCommitsOptions: SetCommitsOptions): Promise<void> {
const { auto, repo, commit, previousCommit } = setCommitsOptions;
const { vcsRemote } = this.#options.release;

// `--auto` only reads the `origin` remote, so other remotes go through manual mode. CI checkouts
// often lack the named remote; `--auto` then still finds the repository from CI variables.
const remoteRepo = auto === true && vcsRemote !== 'origin' ? getGitRemoteRepository(vcsRemote) : undefined;
const head = remoteRepo ? gitRevision() : undefined;
const remoteCommitSpec = remoteRepo && head ? `${remoteRepo}@${head}` : undefined;

// Manual mode is expressed as `REPO@SHA` (optionally `REPO@PREV..SHA`).
const commitSpec =
repo && commit ? `${repo}@${previousCommit ? `${previousCommit}..${commit}` : commit}` : undefined;
repo && commit ? `${repo}@${previousCommit ? `${previousCommit}..${commit}` : commit}` : remoteCommitSpec;

await this.#sdk.release['set-commits']({
orgVersion: name,
auto: auto === true,
auto: auto === true && !remoteCommitSpec,
commit: commitSpec,
});
}
Expand Down
6 changes: 5 additions & 1 deletion packages/bundler-plugins/src/core/options-mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,11 @@ export function normalizeUserOptions(userOptions: UserOptions): NormalizedOption
ignoreEmpty: true,
ignoreMissing: true,
};
} else if (process.env['VERCEL'] && vercelEnv !== 'production' && !canAutoDetectRepository()) {
} else if (
process.env['VERCEL'] &&
vercelEnv !== 'production' &&
!canAutoDetectRepository(options.release.vcsRemote)
) {
// Vercel's own builders have no git remote and no other CI variables, so `--auto` can only fail there.
// Builds that have either, such as `vercel build` in GitHub Actions, keep `--auto` below.
options.release.setCommits = false;
Expand Down
34 changes: 30 additions & 4 deletions packages/bundler-plugins/src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ export function stringToUUID(str: string): string {
return `${sha256Hash.substring(0, 8)}-${sha256Hash.substring(8, 12)}-4${sha256Hash.substring(13, 16)}-${v4variant}${sha256Hash.substring(17, 20)}-${sha256Hash.substring(20, 32)}`.toLowerCase();
}

function gitRevision(): string | undefined {
export function gitRevision(): string | undefined {
let gitRevision: string | undefined;
try {
gitRevision = childProcess
Expand All @@ -231,23 +231,49 @@ const CI_REPOSITORY_ENV_VARS = [
] as const;

/**
* Whether `set-commits --auto` can find the repository: from the `origin` git remote, or from CI variables.
* Whether commit association can find the repository: from the given git remote, or from CI variables.
*/
export function canAutoDetectRepository(): boolean {
export function canAutoDetectRepository(remote = 'origin'): boolean {
if (
CI_REPOSITORY_ENV_VARS.some(name => process.env[name]) ||
(process.env['NETLIFY'] && process.env['REPOSITORY_URL'])
) {
return true;
}
try {
childProcess.execSync('git remote get-url origin', { stdio: 'ignore', windowsHide: true });
childProcess.execFileSync('git', ['remote', 'get-url', remote], { stdio: 'ignore', windowsHide: true });
return true;
} catch {
return false;
}
}

/**
* Reads the `owner/repo` path of a git remote, e.g. `getsentry/sentry-javascript` for
* `git@github.com:getsentry/sentry-javascript.git`.
*/
export function getGitRemoteRepository(remote: string): string | undefined {
let url: string;
try {
url = childProcess
.execFileSync('git', ['remote', 'get-url', remote], { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })
.toString()
.trim();
} catch {
return undefined;
}

let repoPath: string;
try {
repoPath = new URL(url).pathname;
} catch {
// scp-like syntax, `git@host:owner/repo.git`
repoPath = url.slice(url.indexOf(':') + 1);
}
const repository = repoPath.replace(/^\/+|\/+$/g, '').replace(/\.git$/, '');
return repository.includes('/') ? repository : undefined;
}

/**
* Tries to guess a release name based on environmental data.
*/
Expand Down
48 changes: 48 additions & 0 deletions packages/bundler-plugins/test/core/cli-vcs-remote.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { execFileSync } from 'child_process';
import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { SentryCliAdapter } from '../../src/core/cli';
import { normalizeUserOptions } from '../../src/core/options-mapping';

const { mockSetCommits } = vi.hoisted(() => ({ mockSetCommits: vi.fn() }));

vi.mock('sentry', () => ({
createSentrySDK: () => ({ release: { 'set-commits': mockSetCommits } }),
}));

describe('setCommits with release.vcsRemote', () => {
let workDir: string;
let previousCwd: string;
let head: string;

beforeAll(() => {
workDir = mkdtempSync(join(tmpdir(), 'sentry-vcs-remote-'));
previousCwd = process.cwd();
process.chdir(workDir);
const git = (...args: string[]): string => execFileSync('git', args, { cwd: workDir }).toString().trim();
git('init', '-q');
git('remote', 'add', 'origin', 'https://github.com/example-org/example-app.git');
git('remote', 'add', 'upstream', 'git@github.com:example-org/upstream-app.git');
git('-c', 'user.name=test', '-c', 'user.email=test@example.com', 'commit', '-q', '--allow-empty', '-m', 'init');
head = git('rev-parse', 'HEAD');
});

afterAll(() => {
process.chdir(previousCwd);
rmSync(workDir, { recursive: true, force: true });
});

it('links HEAD through the repository of the named remote', async () => {
const options = normalizeUserOptions({ release: { name: '1.0.0', vcsRemote: 'upstream' } });

await new SentryCliAdapter(options).setCommits('1.0.0', { auto: true });

expect(mockSetCommits).toHaveBeenCalledWith({
orgVersion: '1.0.0',
auto: false,
commit: `example-org/upstream-app@${head}`,
});
});
});
10 changes: 5 additions & 5 deletions packages/bundler-plugins/test/core/option-mappings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ describe('normalizeUserOptions()', () => {
test.each(['preview', 'development', 'staging'])(
'should skip commit association on %s Vercel builds without a git remote',
targetEnv => {
vi.spyOn(childProcess, 'execSync').mockImplementation(() => {
vi.spyOn(childProcess, 'execFileSync').mockImplementation(() => {
throw new Error('fatal: not a git repository');
});
// Only Vercel's variables, so CI variables from the machine running the tests don't leak in.
Expand All @@ -233,8 +233,8 @@ describe('normalizeUserOptions()', () => {
);

test('should keep automatic commit association on preview Vercel builds that have a git remote', () => {
const execSyncSpy = vi
.spyOn(childProcess, 'execSync')
const execFileSyncSpy = vi
.spyOn(childProcess, 'execFileSync')
.mockReturnValue(Buffer.from('https://github.com/my-owner/my-repo.git'));
// Only Vercel's variables, so the git remote is what keeps `--auto`, not CI variables from the test machine.
process.env = {
Expand All @@ -247,14 +247,14 @@ describe('normalizeUserOptions()', () => {

const normalizedOptions = normalizeUserOptions({ release: { name: 'my-release' } });

expect(execSyncSpy).toHaveBeenCalledWith('git remote get-url origin', expect.anything());
expect(execFileSyncSpy).toHaveBeenCalledWith('git', ['remote', 'get-url', 'origin'], expect.anything());
expect(normalizedOptions.release.setCommits).toEqual(expect.objectContaining({ auto: true }));
expect(normalizedOptions.release.setCommits).not.toHaveProperty('commit');
vi.restoreAllMocks();
});

test('should keep automatic commit association on preview Vercel builds in another CI without a git remote', () => {
vi.spyOn(childProcess, 'execSync').mockImplementation(() => {
vi.spyOn(childProcess, 'execFileSync').mockImplementation(() => {
throw new Error('fatal: not a git repository');
});
process.env['VERCEL'] = '1';
Expand Down
Loading