Skip to content

Commit

Permalink
fix: improve error managemenet
Browse files Browse the repository at this point in the history
  • Loading branch information
rams23 committed Apr 21, 2023
1 parent 8f19297 commit 3a30268
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 46 deletions.
21 changes: 0 additions & 21 deletions LICENSE

This file was deleted.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@xtreamsrl/react-native-incremental-cli",
"version": "0.1.0",
"version": "0.1.1",
"description": "React Native CLI that caches native builds and speedup your development and release cycle",
"author": "Luca Micieli",
"bin": {
Expand Down
9 changes: 7 additions & 2 deletions src/application/androidUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,15 @@ export function getAppBuildFolder(flavorName?: string, release?: boolean) {
}

export function getAndroidIndexJsPath() {
const androidSpecific = path.join(getProjectRootDir(), 'src', 'application', 'index.android.js');
const androidSpecific = path.join(getProjectRootDir(), 'index.android.js');
if (fs.existsSync(androidSpecific)) {
return androidSpecific;
} else {
return path.join(getProjectRootDir(), 'src', 'application', 'index.js');
return path.join(getProjectRootDir(), 'index.js');
}
}

export function checkBuildPresent(buildFlavor?: string, release?: boolean) {
const appPath = getAppBuildFolder(buildFlavor, release);
return fs.existsSync(appPath);
}
22 changes: 15 additions & 7 deletions src/application/buildAndroid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import {
getUberSignJava,
} from './utils';
import { getAndroidFlavors } from './config';
import { getAndroidIndexJsPath, getAppBuildFolder } from './androidUtils';
import { checkBuildPresent, getAndroidIndexJsPath, getAppBuildFolder } from './androidUtils';
import fs from 'fs';
import logger from './logger';

function capitalize(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
Expand Down Expand Up @@ -64,7 +65,7 @@ async function rebuildIncrementallyTheApk(
await executeCommandAsync(`cp ${signedApkPath} ${apkPath}`);
}

async function rebuildIncrementally(buildType: string | undefined) {
async function rebuildIncrementally(buildType: string | undefined, release: boolean = false) {
const tempRNBundleDir = `${getRootDestinationFolder()}/tmp_${(Math.random() * 1000).toFixed(0)}`;

const tempAssetBundle = path.join(tempRNBundleDir, 'bundle_output');
Expand All @@ -74,6 +75,7 @@ async function rebuildIncrementally(buildType: string | undefined) {
fs.mkdirSync(tempAssetBundle, { recursive: true });
fs.mkdirSync(tempAssetBundle, { recursive: true });

logger.info('Creating new bundle and assets');
executeCommand(
`node ./node_modules/react-native/cli.js bundle \
--platform android \
Expand All @@ -83,15 +85,17 @@ async function rebuildIncrementally(buildType: string | undefined) {
--assets-dest ${resOutput}`,
{ cwd: getProjectRootDir() },
);
logger.info('Rebuilding apks');

const buildFolder = getAppBuildFolder(buildType, release);

await Promise.all(
fs
.readdirSync(getAppBuildFolder(buildType))
.readdirSync(buildFolder)
.filter(f => f.endsWith('.apk'))
.map(async apkFileName => {
console.log(`rebuilding ${apkFileName}`);
if (apkFileName.endsWith('.apk')) {
const apkPath = path.join(getAppBuildFolder(buildType), apkFileName);
const apkPath = path.join(buildFolder, apkFileName);

return rebuildIncrementallyTheApk(apkPath, bundleOutput, resOutput, tempAssetBundle);
}
Expand Down Expand Up @@ -122,9 +126,13 @@ export async function buildAndroid(
const androidFolder = path.join(getProjectRootDir(), 'android');

if (incrementalBuild) {
// todo check previous build existance
if (!checkBuildPresent(flavorName, release)) {
throw new Error(
`No build found for ${flavorName} ${release ? 'release' : 'debug'}. Unable to do incremental build`,
);
}
// create a temp directory
await rebuildIncrementally(flavorName);
await rebuildIncrementally(flavorName, release);
} else {
const gradleBuildTask = getBuildTask(gradleFlavor, release);

Expand Down
3 changes: 3 additions & 0 deletions src/application/buildIos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,16 @@ function _buildIos(buildType?: string, platform: IosPlatform = iosBuildPlatforms
-scheme "${buildFlavor.scheme}" \
-configuration ${buildFlavor.config} \
-sdk ${platform.name} \
-archivePath '${archivePath}' \
-derivedDataPath ${iosFolder}/DerivedData/${appName} \
${platform.buildCmd}
`;

executeCommand(buildCommand);

if (platform.buildCmd === 'build') {
// todo handle Debug/release
// todo app name now is not right this must be "PRODUCT_NAME = "Bilty DEV";" inside the workspace
const source = `${iosFolder}/DerivedData/${appName}/build/Products/Debug-${platform.name}/${appName}.${platform.ext}`;
const { destinationDir, destination } = getIosBuildDestination(platform, buildFlavor.flavorDir);

Expand Down
19 changes: 7 additions & 12 deletions src/application/runAndroid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import adb from '@react-native-community/cli-platform-android/build/commands/run
import _getAdbPath from '@react-native-community/cli-platform-android/build/commands/runAndroid/getAdbPath';
import tryLaunchEmulator from '@react-native-community/cli-platform-android/build/commands/runAndroid/tryLaunchEmulator';
import { buildAndroid } from './buildAndroid';
import { getAppBuildFolder } from './androidUtils';
import { checkBuildPresent, getAppBuildFolder } from './androidUtils';
import path from 'path';
import logger from './logger';

Expand All @@ -28,11 +28,6 @@ function getBootedDevices() {
return String(output).trim().split('\n');
}

function checkBuildPresent(buildType?: string) {
const appPath = getAppBuildFolder(buildType);
return fs.existsSync(appPath);
}

export function findBestApkInFolder(dir: string, arc?: string) {
const files = fs.readdirSync(dir);
// todo debug
Expand Down Expand Up @@ -99,30 +94,30 @@ function installAndLaunch(port: string, deviceId: string, buildType: string | un
launchApp(deviceId, appIdentifier);
}

export async function runApp(buildType?: string, port = '8081') {
if (!checkBuildPresent(buildType)) {
export async function runApp(buildFlavor?: string, port = '8081') {
if (!checkBuildPresent(buildFlavor)) {
logger.info('Build not present, starting build');
await buildAndroid(buildType);
await buildAndroid(buildFlavor);
} else {
logger.info('Build already present, skipping build');
}

// todo improvement: if there is only one device, use it directly
const device = await listAndroidDevices();

const appIdentifier = getBundleIdentifier(getAppBuildFolder(buildType));
const appIdentifier = getBundleIdentifier(getAppBuildFolder(buildFlavor));

if (!device) {
throw new Error('No android devices available');
} else {
if (device.connected) {
installAndLaunch(port, device.deviceId!, buildType, appIdentifier);
installAndLaunch(port, device.deviceId!, buildFlavor, appIdentifier);
} else {
const newEmulatorPort = await getAvailableDevicePort();
const emulator = `emulator-${newEmulatorPort}`;
const result = await tryLaunchEmulator(getAdbPath(), device.readableName, newEmulatorPort);
if (result.success) {
installAndLaunch(port, emulator, buildType, appIdentifier);
installAndLaunch(port, emulator, buildFlavor, appIdentifier);
}
}
}
Expand Down
22 changes: 20 additions & 2 deletions src/application/runIos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,33 @@ function checkBuildPresent(buildType: string, target: any) {

function installApp(deviceUdid: string, buildType: string, target: any) {
const { destination } = getIosBuildDestination(target, buildType);
executeCommand(`xcrun simctl install ${deviceUdid} ${destination}`);
const res = childProcess.execSync(`xcrun simctl install ${deviceUdid} ${destination}`, { encoding: 'utf-8' });
console.log('res', res);
}

function launchApp(deviceUid: string, bundleId: string) {
childProcess.execSync(`xcrun simctl launch ${deviceUid} ${bundleId}`);
}

function isErrorWithStderr(e: unknown): e is { stderr: { toString(): string } } {
if (typeof e === 'object' && e !== null && 'stderr' in e) {
return typeof (e as any).stderr.toString === 'function';
}
return false;
}

function launchDevice(deviceUid: string) {
executeCommand(['xcrun', 'simctl', 'boot', deviceUid].join(' '));
try {
childProcess.execSync(['xcrun', 'simctl', 'boot', deviceUid].join(' '));
} catch (e) {
if (isErrorWithStderr(e)) {
const err = e.stderr.toString();
if (err.includes('Unable to boot device in current state: Booted')) {
return;
}
}
throw e;
}
}

async function promptForDeviceSelection(allDevices: Device[]): Promise<Device[]> {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default class Build extends Command {
ios: Flags.boolean({ char: 'i', description: 'Generate ios native build' }),
android: Flags.boolean({ char: 'a', description: 'Generate android native build' }),
flavor: Flags.string({ char: 'f', description: 'Specify flavor to build' }),
release: Flags.boolean({ description: 'Optimized release build' }),
release: Flags.boolean({ description: 'Optimized release build', default: false }),
incremental: Flags.boolean({ char: 'I', description: 'Incremental build', default: false }),
};

Expand Down

0 comments on commit 3a30268

Please sign in to comment.