Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: read main activity from AndroidManifest.xml automatically #1967

Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 2 additions & 1 deletion __e2e__/__snapshots__/config.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ exports[`shows up current config without unnecessary output 1`] = `
"android": {
"sourceDir": "<<REPLACED_ROOT>>/TestProject/android",
"appName": "app",
"packageName": "com.testproject"
"packageName": "com.testproject",
"mainActivity": ".MainActivity"
}
}
}
Expand Down
1 change: 1 addition & 0 deletions docs/platforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ type AndroidProjectConfig = {
sourceDir: string;
appName: string;
packageName: string;
mainActivity: string;
dependencyConfiguration?: string;
watchModeCommandParams: string;
};
Expand Down
16 changes: 16 additions & 0 deletions packages/cli-config/src/__tests__/index-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,12 +406,28 @@ test('should convert project sourceDir relative path to absolute', () => {
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.coinbase.android">
<application android:name=".MainApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
`,
'android2/AndroidManifest.xml': `
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.coinbase.android">
<application android:name=".MainApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
`,
});
Expand Down
1 change: 1 addition & 0 deletions packages/cli-platform-android/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"@react-native-community/cli-tools": "12.0.0-alpha.4",
"chalk": "^4.1.2",
"execa": "^5.0.0",
"fast-xml-parser": "^4.2.4",
"glob": "^7.1.3",
"logkitty": "^0.7.1"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ async function runAndroid(_argv: Array<string>, config: Config, args: Flags) {
link.setVersion(config.reactNativeVersion);
}

if (!args.mainActivity && config.project.android?.mainActivity) {
args.mainActivity = config.project.android?.mainActivity;
}

if (args.binaryPath) {
if (args.tasks) {
throw new CLIError(
Expand Down Expand Up @@ -283,7 +287,6 @@ export default {
{
name: '--main-activity <string>',
description: 'Name of the activity to start',
default: 'MainActivity',
szymonrybczak marked this conversation as resolved.
Show resolved Hide resolved
},
{
name: '--deviceId <string>',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ const appBuildGradle = fs.readFileSync(
path.join(__dirname, './files/appbuild.gradle'),
);

const fewActivitiesManifest = fs.readFileSync(
path.join(__dirname, './files/AndroidManifest-few-activities.xml'),
);

const classNameManifest = fs.readFileSync(
path.join(__dirname, './files/AndroidManifest-className.xml'),
);

function generateValidFileStructureForLib(classFileName: string) {
return {
'build.gradle': buildGradle,
Expand Down Expand Up @@ -278,3 +286,15 @@ export const findPackagesClassNameJavaNotValid = [
}
`,
];

export const fewActivities = {
src: {
'AndroidManifest.xml': fewActivitiesManifest,
},
};

export const className = {
src: {
'AndroidManifest.xml': classNameManifest,
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.some.example">
<uses-permission android:name="android.permission.INTERNET" />

<application android:name=".MainApplication">
<activity android:name="com.example.ExampleAppActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<manifest
xmlns:android="http://schemas.android.com/apk/res/android">
<application android:name=".ExampleApplication">
<activity android:name=".ExampleAppActivity">
szymonrybczak marked this conversation as resolved.
Show resolved Hide resolved
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="rntester" android:host="example" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" android:exported="false"/>
</application>
</queries>
</manifest>
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.some.example">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.some.example">
<uses-permission android:name="android.permission.INTERNET" />

<application android:name=".MainApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ exports[`android::getProjectConfig returns an object with android project config
Object {
"appName": "",
"dependencyConfiguration": undefined,
"mainActivity": ".MainActivity",
"packageName": "com.some.example",
"sourceDir": "/flat/android",
"unstable_reactLegacyComponentNames": undefined,
Expand All @@ -15,6 +16,7 @@ exports[`android::getProjectConfig returns an object with android project config
Object {
"appName": "",
"dependencyConfiguration": undefined,
"mainActivity": ".MainActivity",
"packageName": "com.some.example",
"sourceDir": "/multiple/android",
"unstable_reactLegacyComponentNames": undefined,
Expand All @@ -26,6 +28,7 @@ exports[`android::getProjectConfig returns an object with android project config
Object {
"appName": "app",
"dependencyConfiguration": undefined,
"mainActivity": ".MainActivity",
"packageName": "com.some.example",
"sourceDir": "/nested/android",
"unstable_reactLegacyComponentNames": undefined,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import findManifest from '../findManifest';
import getMainActivity from '../getMainActivity';
import * as mocks from '../__fixtures__/android';

jest.mock('path');
jest.mock('fs');

const fs = require('fs');

describe('android::getMainActivity', () => {
beforeAll(() => {
fs.__setMockFilesystem({
empty: {},
valid: {
android: {
app: mocks.valid,
},
},
className: {
android: {
app: mocks.className,
},
},
few: {
android: {
app: mocks.fewActivities,
},
},
});
});

it('returns main activity if file exists in the folder', () => {
const manifestPath = findManifest('/valid');
const manifest = getMainActivity(manifestPath || '');
expect(manifest).not.toBeNull();
expect(typeof manifest).toBe('string');
expect(manifest).toBe('.MainActivity');
});

it('returns main activity if there is few activities', () => {
const manifestPath = findManifest('/few');
const mainActivity = getMainActivity(manifestPath || '');
expect(mainActivity).not.toBeNull();
expect(typeof mainActivity).toBe('string');
expect(mainActivity).toBe('.ExampleAppActivity');
});

it('returns main activity if it is class name', () => {
const manifestPath = findManifest('/className');
const mainActivity = getMainActivity(manifestPath || '');
expect(mainActivity).not.toBeNull();
expect(typeof mainActivity).toBe('string');
expect(mainActivity).toBe('com.example.ExampleAppActivity');
});

it('returns null if file do not exist', () => {
const fakeManifestPath = findManifest('/empty');
expect(getMainActivity(fakeManifestPath || '')).toBeNull();
});
});
106 changes: 106 additions & 0 deletions packages/cli-platform-android/src/config/getMainActivity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import fs from 'fs';
import {XMLParser, XMLValidator} from 'fast-xml-parser';

const MAIN_ACTION = 'android.intent.action.MAIN';
const LAUNCHER = 'android.intent.category.LAUNCHER';

interface Activity {
[x: string]: any;
TMisiukiewicz marked this conversation as resolved.
Show resolved Hide resolved
}

interface IntentFilter {
action:
| {
'@_android:name': string;
}
| {
'@_android:name': string;
}[];
category:
| {
'@_android:name': string;
}
| {
'@_android:name': string;
}[];
szymonrybczak marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Reads the AndroidManifest.xml file and returns the name of the main activity.
*/

export default function getMainActivity(manifestPath: string): string | null {
try {
const xmlParser = new XMLParser({ignoreAttributes: false});
const manifestContent = fs.readFileSync(manifestPath, {encoding: 'utf8'});

if (XMLValidator.validate(manifestContent)) {
const {manifest} = xmlParser.parse(manifestContent);

const application = manifest.application || {};
const activity = application.activity || {};

let activities: Activity[] = [];

if (!Array.isArray(activity)) {
activities = [activity];
} else {
activities = activity;
}

const mainActivity = activities.find((act: Activity) => {
let intentFilters = act['intent-filter'];

if (!intentFilters) {
return false;
}

if (!Array.isArray(intentFilters)) {
intentFilters = [intentFilters];
}

return intentFilters.find((intentFilter: IntentFilter) => {
const {action, category} = intentFilter;

let actions;
let categories;

if (!Array.isArray(action)) {
actions = [action];
} else {
actions = action;
}

if (!Array.isArray(category)) {
categories = [category];
} else {
categories = category;
}

if (actions && categories) {
const parsedActions: string[] = actions.map(
({'@_android:name': name}) => name,
);

const parsedCategories: string[] = categories.map(
({'@_android:name': name}) => name,
);

return (
parsedActions.includes(MAIN_ACTION) &&
parsedCategories.includes(LAUNCHER)
);
}

return false;
});
});

return mainActivity ? mainActivity['@_android:name'] : null;
} else {
return null;
}
} catch {
return null;
}
}
8 changes: 8 additions & 0 deletions packages/cli-platform-android/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {findLibraryName} from './findLibraryName';
import {findComponentDescriptors} from './findComponentDescriptors';
import {findBuildGradle} from './findBuildGradle';
import {CLIError} from '@react-native-community/cli-tools';
import getMainActivity from './getMainActivity';

/**
* Gets android project config by analyzing given folder and taking some
Expand Down Expand Up @@ -59,10 +60,17 @@ export function projectConfig(
);
}

const mainActivity = getMainActivity(manifestPath || '');

if (!mainActivity) {
throw new CLIError(`Main activity not found in ${manifestPath}`);
}

return {
sourceDir,
appName,
packageName,
mainActivity,
dependencyConfiguration: userConfig.dependencyConfiguration,
watchModeCommandParams: userConfig.watchModeCommandParams,
unstable_reactLegacyComponentNames:
Expand Down
1 change: 1 addition & 0 deletions packages/cli-types/src/android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export interface AndroidProjectConfig {
sourceDir: string;
appName: string;
packageName: string;
mainActivity: string;
dependencyConfiguration?: string;
watchModeCommandParams?: string[];
unstable_reactLegacyComponentNames?: string[] | null;
Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6104,6 +6104,13 @@ fast-xml-parser@^4.0.12:
dependencies:
strnum "^1.0.5"

fast-xml-parser@^4.2.4:
version "4.2.4"
resolved "https://registry.yarnpkg.com/fast-xml-parser/-/fast-xml-parser-4.2.4.tgz#6e846ede1e56ad9e5ef07d8720809edf0ed07e9b"
integrity sha512-fbfMDvgBNIdDJLdLOwacjFAPYt67tr31H9ZhWSm45CDAxvd0I6WTlSOUo7K2P/K5sA5JgMKG64PI3DMcaFdWpQ==
dependencies:
strnum "^1.0.5"

fastparse@^1.1.1:
version "1.1.2"
resolved "https://registry.yarnpkg.com/fastparse/-/fastparse-1.1.2.tgz#91728c5a5942eced8531283c79441ee4122c35a9"
Expand Down