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

fix(ios): run-ios command #2173

Merged
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
38 changes: 38 additions & 0 deletions __e2e__/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,41 @@ test('init --platform-name should work for out of tree platform', () => {

expect(dirFiles.length).toBeGreaterThan(0);
});

test('should not create custom config file if installed version is below 0.73', () => {
createCustomTemplateFiles();

runCLI(DIR, ['init', PROJECT_NAME, '--skip-install', '--version', '0.72.0']);

let dirFiles = fs.readdirSync(path.join(DIR, PROJECT_NAME));

expect(dirFiles).not.toContain('react-native.config.js');
});

test('should create custom config file if installed version is latest (starting from 0.73)', () => {
createCustomTemplateFiles();

runCLI(DIR, ['init', PROJECT_NAME, '--skip-install']);

let dirFiles = fs.readdirSync(path.join(DIR, PROJECT_NAME));

expect(dirFiles).toContain('react-native.config.js');
Copy link
Member

Choose a reason for hiding this comment

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

we could also validate what's inside

const fileContent = fs.readFileSync(
path.join(DIR, PROJECT_NAME, 'react-native.config.js'),
'utf8',
);

const configFileContent = `
module.exports = {
project: {
ios: {
automaticPodsInstallation: true
}
}
}`;

//normalize all white-spaces for easier comparision
expect(fileContent.replace(/\s+/g, '')).toEqual(
configFileContent.replace(/\s+/g, ''),
);
});
16 changes: 14 additions & 2 deletions packages/cli-platform-ios/src/commands/runIOS/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import getSimulators from '../../tools/getSimulators';
import {getXcodeProjectAndDir} from '../buildIOS/getXcodeProjectAndDir';
import resolvePods from '../../tools/pods';
import getArchitecture from '../../tools/getArchitecture';
import findXcodeProject from '../../config/findXcodeProject';

export interface FlagsT extends BuildFlags {
simulator?: string;
Expand All @@ -46,7 +47,7 @@ async function runIOS(_: Array<string>, ctx: Config, args: FlagsT) {
link.setPlatform('ios');

let {packager, port} = args;

let installedPods = false;
// check if pods need to be installed
if (ctx.project.ios?.automaticPodsInstallation || args.forcePods) {
const isAppRunningNewArchitecture = ctx.project.ios?.sourceDir
Expand All @@ -57,6 +58,8 @@ async function runIOS(_: Array<string>, ctx: Config, args: FlagsT) {
forceInstall: args.forcePods,
newArchEnabled: isAppRunningNewArchitecture,
});

installedPods = true;
}

if (packager) {
Expand All @@ -79,7 +82,16 @@ async function runIOS(_: Array<string>, ctx: Config, args: FlagsT) {
link.setVersion(ctx.reactNativeVersion);
}

const {xcodeProject, sourceDir} = getXcodeProjectAndDir(ctx.project.ios);
let {xcodeProject, sourceDir} = getXcodeProjectAndDir(ctx.project.ios);

// if project is freshly created, revisit Xcode project to verify Pods are installed correctly.
// This is needed because ctx project is created before Pods are installed, so it might have outdated information.
if (installedPods) {
const recheckXcodeProject = findXcodeProject(fs.readdirSync(sourceDir));
if (recheckXcodeProject) {
xcodeProject = recheckXcodeProject;
}
}

process.chdir(sourceDir);

Expand Down
37 changes: 37 additions & 0 deletions packages/cli-tools/src/__tests__/cacheManager.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import fs from 'fs';
import path from 'path';
import cacheManager from '../cacheManager';
import {cleanup, getTempDirectory} from '../../../../jest/helpers';

const DIR = getTempDirectory('.react-native-cli/cache');
const projectName = 'Project1';
const fullPath = path.join(DIR, projectName);

describe('cacheManager', () => {
beforeEach(() => {
jest.restoreAllMocks();
});

afterEach(() => {
cleanup(DIR);
});

test('should not remove cache if it does not exist', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
jest.spyOn(fs, 'rmSync').mockImplementation(() => {});

cacheManager.removeProjectCache(projectName);

expect(fs.rmSync).not.toHaveBeenCalled();
});

test('should remove cache if it exists', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
jest.spyOn(fs, 'rmSync').mockImplementation(() => {});
jest.spyOn(path, 'resolve').mockReturnValue(fullPath);

cacheManager.removeProjectCache(projectName);

expect(fs.rmSync).toHaveBeenCalledWith(fullPath, {recursive: true});
});
});
20 changes: 20 additions & 0 deletions packages/cli-tools/src/cacheManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import path from 'path';
import fs from 'fs';
import os from 'os';
import appDirs from 'appdirsjs';
import chalk from 'chalk';
import logger from './logger';

type CacheKey = 'eTag' | 'lastChecked' | 'latestVersion' | 'dependencies';
Expand Down Expand Up @@ -48,6 +49,23 @@ function getCacheRootPath() {
return cachePath;
}

function removeProjectCache(name: string) {
const cacheRootPath = getCacheRootPath();
try {
const fullPath = path.resolve(cacheRootPath, name);
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: we can move fullPath outside try catch and re-use it in catch statement.


if (fs.existsSync(fullPath)) {
fs.rmSync(fullPath, {recursive: true});
}
} catch {
logger.error(
`Failed to remove cache for ${name}. If you experience any issues when running freshly initialized project, please remove the "${chalk.underline(
path.join(cacheRootPath, name),
)}" folder manually.`,
);
}
}

function get(name: string, key: CacheKey): string | undefined {
const cache = loadCache(name);
if (cache) {
Expand All @@ -67,4 +85,6 @@ function set(name: string, key: CacheKey, value: string) {
export default {
get,
set,
removeProjectCache,
getCacheRootPath,
};
17 changes: 16 additions & 1 deletion packages/cli/src/commands/init/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {getYarnVersionIfAvailable} from '../../tools/yarn';
import {createHash} from 'crypto';
import createGitRepository from './createGitRepository';
import deepmerge from 'deepmerge';
import semver from 'semver';

const DEFAULT_VERSION = 'latest';

Expand Down Expand Up @@ -57,6 +58,7 @@ interface TemplateOptions {
skipInstall?: boolean;
packageName?: string;
installCocoaPods?: string | boolean;
version?: string;
}

function doesDirectoryExist(dir: string) {
Expand Down Expand Up @@ -111,6 +113,7 @@ async function createFromTemplate({
skipInstall,
packageName,
installCocoaPods,
version,
}: TemplateOptions) {
logger.debug('Initializing new project');
logger.log(banner);
Expand All @@ -133,6 +136,9 @@ async function createFromTemplate({
packageManager = 'npm';
}

// if the project with the name already has cache, remove the cache to avoid problems with pods installation
cacheManager.removeProjectCache(projectName);

const projectDirectory = await setProjectDirectory(directory);

const loader = getLoader({text: 'Downloading template'});
Expand Down Expand Up @@ -171,7 +177,14 @@ async function createFromTemplate({
packageName,
});

createDefaultConfigFile(projectDirectory, loader);
const coerceRnVersion = semver.valid(semver.coerce(version));

if (
version === 'latest' ||
(coerceRnVersion && semver.satisfies(coerceRnVersion, '>=0.73.0'))
) {
createDefaultConfigFile(projectDirectory, loader);
}

const {postInitScript} = templateConfig;
if (postInitScript) {
Expand Down Expand Up @@ -349,6 +362,7 @@ async function createProject(
skipInstall: options.skipInstall,
packageName: options.packageName,
installCocoaPods: options.installPods,
version,
});
}

Expand Down Expand Up @@ -391,6 +405,7 @@ export default (async function initialize(

const root = process.cwd();
const version = options.version || DEFAULT_VERSION;

const directoryName = path.relative(root, options.directory || projectName);

if (options.pm && !checkPackageManagerAvailability(options.pm)) {
Expand Down
Loading