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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
Sentry.wrapExpoAsset(Asset);
```
- Adds tags with Expo Updates context variables to make them searchable and filterable ([#5788](https://github.com/getsentry/sentry-react-native/pull/5788))
- Adds environment configuration in the Expo config plugin. This can be set with the `SENTRY_ENVIRONMENT` env variable or in `sentry.options.json` ([#5796](https://github.com/getsentry/sentry-react-native/pull/5796))
```json
["@sentry/react-native/expo", {
"useNativeInit": true,
"environment": "staging"
}]
```

### Fixes

Expand Down
20 changes: 20 additions & 0 deletions packages/core/plugin/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as fs from 'fs';
import * as path from 'path';
import { warnOnce } from './logger';

export function writeSentryPropertiesTo(filepath: string, sentryProperties: string): void {
if (!fs.existsSync(filepath)) {
Expand All @@ -8,3 +9,22 @@ export function writeSentryPropertiesTo(filepath: string, sentryProperties: stri

fs.writeFileSync(path.resolve(filepath, 'sentry.properties'), sentryProperties);
}

const SENTRY_OPTIONS_FILE_NAME = 'sentry.options.json';

export function writeSentryOptionsEnvironment(projectRoot: string, environment: string): void {
const optionsFilePath = path.resolve(projectRoot, SENTRY_OPTIONS_FILE_NAME);

let options: Record<string, unknown> = {};
if (fs.existsSync(optionsFilePath)) {
try {
options = JSON.parse(fs.readFileSync(optionsFilePath, 'utf8'));
} catch (e) {
warnOnce(`Failed to parse ${SENTRY_OPTIONS_FILE_NAME}: ${e}. The environment will not be set.`);
return;
}
}

options.environment = environment;
fs.writeFileSync(optionsFilePath, `${JSON.stringify(options, null, 2)}\n`);
}
29 changes: 28 additions & 1 deletion packages/core/plugin/src/withSentry.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { ExpoConfig } from '@expo/config-types';
import type { ConfigPlugin } from 'expo/config-plugins';
import { createRunOncePlugin } from 'expo/config-plugins';
import { createRunOncePlugin, withDangerousMod } from 'expo/config-plugins';
import { bold, warnOnce } from './logger';
import { writeSentryOptionsEnvironment } from './utils';
import { PLUGIN_NAME, PLUGIN_VERSION } from './version';
import { withSentryAndroid } from './withSentryAndroid';
import type { SentryAndroidGradlePluginOptions } from './withSentryAndroidGradlePlugin';
Expand All @@ -13,6 +15,7 @@ interface PluginProps {
authToken?: string;
url?: string;
useNativeInit?: boolean;
environment?: string;
experimental_android?: SentryAndroidGradlePluginOptions;
}

Expand All @@ -25,6 +28,10 @@ const withSentryPlugin: ConfigPlugin<PluginProps | void> = (config, props) => {
}

let cfg = config;
const environment = props?.environment ?? process.env.SENTRY_ENVIRONMENT;
if (environment) {
cfg = withSentryOptionsEnvironment(cfg, environment);
}
if (sentryProperties !== null) {
try {
cfg = withSentryAndroid(cfg, { sentryProperties, useNativeInit: props?.useNativeInit });
Expand Down Expand Up @@ -80,6 +87,26 @@ ${project ? `defaults.project=${project}` : missingProjectMessage}
${authToken ? `${existingAuthTokenMessage}\nauth.token=${authToken}` : missingAuthTokenMessage}`;
}

function withSentryOptionsEnvironment(config: ExpoConfig, environment: string): ExpoConfig {
// withDangerousMod requires a platform key, but sentry.options.json is at the project root.
// We apply to both platforms so it works with `expo prebuild --platform ios` or `--platform android`.
let cfg = withDangerousMod(config, [
'android',
mod => {
writeSentryOptionsEnvironment(mod.modRequest.projectRoot, environment);
return mod;
},
]);
cfg = withDangerousMod(cfg, [
'ios',
mod => {
writeSentryOptionsEnvironment(mod.modRequest.projectRoot, environment);
return mod;
},
]);
return cfg;
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const withSentry = createRunOncePlugin(withSentryPlugin, PLUGIN_NAME, PLUGIN_VERSION);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { writeSentryOptionsEnvironment } from '../../plugin/src/utils';

jest.mock('../../plugin/src/logger');

describe('writeSentryOptionsEnvironment', () => {
let tempDir: string;

beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-options-test-'));
});

afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});

test('creates sentry.options.json with environment when file does not exist', () => {
writeSentryOptionsEnvironment(tempDir, 'staging');

const filePath = path.join(tempDir, 'sentry.options.json');
const content = JSON.parse(fs.readFileSync(filePath, 'utf8'));
expect(content).toEqual({ environment: 'staging' });
});

test('sets environment in existing sentry.options.json', () => {
const filePath = path.join(tempDir, 'sentry.options.json');
fs.writeFileSync(filePath, JSON.stringify({ dsn: 'https://key@sentry.io/123', environment: 'production' }));

writeSentryOptionsEnvironment(tempDir, 'staging');

const content = JSON.parse(fs.readFileSync(filePath, 'utf8'));
expect(content.environment).toBe('staging');
expect(content.dsn).toBe('https://key@sentry.io/123');
});

test('adds environment to existing sentry.options.json without environment', () => {
const filePath = path.join(tempDir, 'sentry.options.json');
fs.writeFileSync(filePath, JSON.stringify({ dsn: 'https://key@sentry.io/123' }));

writeSentryOptionsEnvironment(tempDir, 'staging');

const content = JSON.parse(fs.readFileSync(filePath, 'utf8'));
expect(content.environment).toBe('staging');
expect(content.dsn).toBe('https://key@sentry.io/123');
});

test('does not crash and warns when sentry.options.json contains invalid JSON', () => {
const { warnOnce } = require('../../plugin/src/logger');
const filePath = path.join(tempDir, 'sentry.options.json');
fs.writeFileSync(filePath, 'invalid json{{{');

writeSentryOptionsEnvironment(tempDir, 'staging');

expect(warnOnce).toHaveBeenCalledWith(expect.stringContaining('Failed to parse'));
// File should remain unchanged
expect(fs.readFileSync(filePath, 'utf8')).toBe('invalid json{{{');
});
});
Loading