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

refactor(cli-platform-apple): move installing and launching app logic to separate function #2234

Merged
merged 2 commits into from
Jan 3, 2024
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
100 changes: 13 additions & 87 deletions packages/cli-platform-apple/src/commands/runCommand/getBuildPath.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,14 @@
import child_process from 'child_process';
import {IOSProjectInfo} from '@react-native-community/cli-types';
import {CLIError, logger} from '@react-native-community/cli-tools';
import chalk from 'chalk';
import {CLIError} from '@react-native-community/cli-tools';
import path from 'path';
import {BuildSettings} from './getBuildSettings';

export async function getBuildPath(
xcodeProject: IOSProjectInfo,
mode: string,
buildOutput: string,
scheme: string,
target: string | undefined,
buildSettings: BuildSettings,
isCatalyst: boolean = false,
) {
const buildSettings = child_process.execFileSync(
'xcodebuild',
[
xcodeProject.isWorkspace ? '-workspace' : '-project',
xcodeProject.name,
'-scheme',
scheme,
'-sdk',
getPlatformName(buildOutput),
'-configuration',
mode,
'-showBuildSettings',
'-json',
],
{encoding: 'utf8'},
);

const {targetBuildDir, executableFolderPath} = await getTargetPaths(
buildSettings,
scheme,
target,
);
const targetBuildDir = buildSettings.TARGET_BUILD_DIR;
const executableFolderPath = buildSettings.EXECUTABLE_FOLDER_PATH;
const fullProductName = buildSettings.FULL_PRODUCT_NAME;

if (!targetBuildDir) {
throw new CLIError('Failed to get the target build directory.');
Expand All @@ -42,63 +18,13 @@ export async function getBuildPath(
throw new CLIError('Failed to get the app name.');
}

return `${targetBuildDir}${
isCatalyst ? '-maccatalyst' : ''
}/${executableFolderPath}`;
}

async function getTargetPaths(
buildSettings: string,
scheme: string,
target: string | undefined,
) {
const settings = JSON.parse(buildSettings);

const targets = settings.map(
({target: settingsTarget}: any) => settingsTarget,
);

let selectedTarget = targets[0];

if (target) {
if (!targets.includes(target)) {
logger.info(
`Target ${chalk.bold(target)} not found for scheme ${chalk.bold(
scheme,
)}, automatically selected target ${chalk.bold(selectedTarget)}`,
);
} else {
selectedTarget = target;
}
}

// Find app in all building settings - look for WRAPPER_EXTENSION: 'app',

const targetIndex = targets.indexOf(selectedTarget);

const wrapperExtension =
settings[targetIndex].buildSettings.WRAPPER_EXTENSION;

if (wrapperExtension === 'app') {
return {
targetBuildDir: settings[targetIndex].buildSettings.TARGET_BUILD_DIR,
executableFolderPath:
settings[targetIndex].buildSettings.EXECUTABLE_FOLDER_PATH,
};
if (!fullProductName) {
throw new CLIError('Failed to get product name.');
szymonrybczak marked this conversation as resolved.
Show resolved Hide resolved
}

return {};
}

function getPlatformName(buildOutput: string) {
// Xcode can sometimes escape `=` with a backslash or put the value in quotes
const platformNameMatch = /export PLATFORM_NAME\\?="?(\w+)"?$/m.exec(
buildOutput,
);
if (!platformNameMatch) {
throw new CLIError(
'Couldn\'t find "PLATFORM_NAME" variable in xcodebuild output. Please report this issue and run your project with Xcode instead.',
);
if (isCatalyst) {
return path.join(targetBuildDir, '-maccatalyst', executableFolderPath);
} else {
return path.join(targetBuildDir, executableFolderPath);
}
return platformNameMatch[1];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import {CLIError, logger} from '@react-native-community/cli-tools';
import {IOSProjectInfo} from '@react-native-community/cli-types';
import chalk from 'chalk';
import child_process from 'child_process';

export type BuildSettings = {
TARGET_BUILD_DIR: string;
INFOPLIST_PATH: string;
EXECUTABLE_FOLDER_PATH: string;
FULL_PRODUCT_NAME: string;
};

export async function getBuildSettings(
xcodeProject: IOSProjectInfo,
mode: string,
buildOutput: string,
scheme: string,
target?: string,
): Promise<BuildSettings | null> {
const buildSettings = child_process.execFileSync(
'xcodebuild',
[
xcodeProject.isWorkspace ? '-workspace' : '-project',
xcodeProject.name,
'-scheme',
scheme,
'-sdk',
getPlatformName(buildOutput),
'-configuration',
mode,
'-showBuildSettings',
'-json',
],
{encoding: 'utf8'},
);

const settings = JSON.parse(buildSettings);
szymonrybczak marked this conversation as resolved.
Show resolved Hide resolved

const targets = settings.map(
({target: settingsTarget}: any) => settingsTarget,
szymonrybczak marked this conversation as resolved.
Show resolved Hide resolved
);

let selectedTarget = targets[0];

if (target) {
if (!targets.includes(target)) {
logger.info(
`Target ${chalk.bold(target)} not found for scheme ${chalk.bold(
scheme,
)}, automatically selected target ${chalk.bold(selectedTarget)}`,
);
} else {
selectedTarget = target;
}
}

// Find app in all building settings - look for WRAPPER_EXTENSION: 'app',
const targetIndex = targets.indexOf(selectedTarget);
const targetSettings = settings[targetIndex].buildSettings;

const wrapperExtension = targetSettings.WRAPPER_EXTENSION;

if (wrapperExtension === 'app') {
return settings[targetIndex].buildSettings;
}

return null;
}

function getPlatformName(buildOutput: string) {
// Xcode can sometimes escape `=` with a backslash or put the value in quotes
const platformNameMatch = /export PLATFORM_NAME\\?="?(\w+)"?$/m.exec(
buildOutput,
);
if (!platformNameMatch) {
throw new CLIError(
'Couldn\'t find "PLATFORM_NAME" variable in xcodebuild output. Please report this issue and run your project with Xcode instead.',
);
}
return platformNameMatch[1];
}
107 changes: 107 additions & 0 deletions packages/cli-platform-apple/src/commands/runCommand/installApp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import child_process from 'child_process';
import {CLIError, logger} from '@react-native-community/cli-tools';
import {IOSProjectInfo} from '@react-native-community/cli-types';
import chalk from 'chalk';
import {getBuildPath} from './getBuildPath';
import {getBuildSettings} from './getBuildSettings';
import path from 'path';

function handleLaunchResult(
success: boolean,
errorMessage: string,
errorDetails = '',
) {
if (success) {
logger.success('Successfully launched the app');
} else {
logger.error(errorMessage, errorDetails);
}
}

type Options = {
buildOutput: any;
Copy link
Member

@thymikee thymikee Dec 27, 2023

Choose a reason for hiding this comment

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

Let's add some basic type. According to data flow this can be undefined and I'm not sure if it's handled properly

xcodeProject: IOSProjectInfo;
mode: string;
scheme: string;
target?: string;
udid: string;
binaryPath?: string;
};

export default async function installApp({
buildOutput,
xcodeProject,
mode,
scheme,
target,
udid,
binaryPath,
}: Options) {
let appPath = binaryPath;

const buildSettings = await getBuildSettings(
xcodeProject,
mode,
buildOutput,
scheme,
target,
);

if (!buildSettings) {
throw new CLIError('Failed to get build settings for your project');
}

if (!appPath) {
appPath = await getBuildPath(buildSettings);
}

if (!buildSettings) {
throw new CLIError('Failed to get build settings for your project');
}
Comment on lines +58 to +60
Copy link
Collaborator Author

@szymonrybczak szymonrybczak Jan 2, 2024

Choose a reason for hiding this comment

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

That's also not the most informative error ever, soon in a separate PR I'll fix all errors in this place :)


const targetBuildDir = buildSettings.TARGET_BUILD_DIR;
const infoPlistPath = buildSettings.INFOPLIST_PATH;

if (!infoPlistPath) {
throw new CLIError('Failed to find Info.plist');
}

if (!targetBuildDir) {
throw new CLIError('Failed to get target build directory.');
}

logger.info(`Installing "${chalk.bold(appPath)}`);

if (udid && appPath) {
child_process.spawnSync('xcrun', ['simctl', 'install', udid, appPath], {
stdio: 'inherit',
});
}

const bundleID = child_process
.execFileSync(
'/usr/libexec/PlistBuddy',
[
'-c',
'Print:CFBundleIdentifier',
path.join(targetBuildDir, infoPlistPath),
],
{encoding: 'utf8'},
)
.trim();

logger.info(`Launching "${chalk.bold(bundleID)}"`);

let result = child_process.spawnSync('xcrun', [
'simctl',
'launch',
udid,
bundleID,
]);

handleLaunchResult(
result.status === 0,
'Failed to launch the app on simulator',
result.stderr.toString(),
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import chalk from 'chalk';
import {buildProject} from '../buildCommand/buildProject';
import {getBuildPath} from './getBuildPath';
import {FlagsT} from './createRun';
import {getBuildSettings} from './getBuildSettings';

export async function runOnDevice(
selectedDevice: Device,
Expand Down Expand Up @@ -45,14 +46,18 @@ export async function runOnDevice(
args,
);

const appPath = await getBuildPath(
const buildSettings = await getBuildSettings(
xcodeProject,
mode,
buildOutput,
scheme,
args.target,
true,
);

if (!buildSettings) {
throw new CLIError('Failed to get build settings for your project');
}

const appPath = await getBuildPath(buildSettings, true);
const appProcess = child_process.spawn(`${appPath}/${scheme}`, [], {
detached: true,
stdio: 'ignore',
Expand All @@ -70,13 +75,18 @@ export async function runOnDevice(
args,
);

appPath = await getBuildPath(
const buildSettings = await getBuildSettings(
xcodeProject,
mode,
buildOutput,
scheme,
args.target,
);

if (!buildSettings) {
throw new CLIError('Failed to get build settings for your project');
}

appPath = await getBuildPath(buildSettings);
} else {
appPath = args.binaryPath;
}
Expand Down
Loading