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: add add-platform command #2298

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 12 additions & 6 deletions docs/init.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ module.exports = {

// Path to script, which will be executed after initialization process, but before installing all the dependencies specified in the template. This script runs as a shell script but you can change that (e.g. to Node) by using a shebang (see example custom template).
postInitScript: './script.js',
// We're also using `template.config.js` when adding new platforms to existing project in `add-platform` command. Thanks to value passed to `platformName` we know which folder we should copy to the project.
platformName: 'visionos',
szymonrybczak marked this conversation as resolved.
Show resolved Hide resolved
};
```

Expand All @@ -91,12 +93,16 @@ new Promise((resolve) => {
spinner.start();
// do something
resolve();
}).then(() => {
spinner.succeed();
}).catch(() => {
spinner.fail();
throw new Error('Something went wrong during the post init script execution');
});
})
.then(() => {
spinner.succeed();
})
.catch(() => {
spinner.fail();
throw new Error(
'Something went wrong during the post init script execution',
);
});
```

You can find example custom template [here](https://github.com/Esemesek/react-native-new-template).
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,15 @@
"find-up": "^5.0.0",
"fs-extra": "^8.1.0",
"graceful-fs": "^4.1.3",
"npm-registry-fetch": "^16.1.0",
"prompts": "^2.4.2",
"semver": "^7.5.2"
},
"devDependencies": {
"@types/fs-extra": "^8.1.0",
"@types/graceful-fs": "^4.1.3",
"@types/hapi__joi": "^17.1.6",
"@types/npm-registry-fetch": "^8.0.7",
"@types/prompts": "^2.4.4",
"@types/semver": "^6.0.2",
"slash": "^3.0.0",
Expand Down
262 changes: 262 additions & 0 deletions packages/cli/src/commands/addPlatform/addPlatform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
import {
CLIError,
getLoader,
logger,
prompt,
} from '@react-native-community/cli-tools';
import {Config} from '@react-native-community/cli-types';
import {join} from 'path';
import {readFileSync} from 'fs';
import chalk from 'chalk';
import {install, PackageManager} from './../../tools/packageManager';
import npmFetch from 'npm-registry-fetch';
import semver from 'semver';
import {checkGitInstallation, isGitTreeDirty} from '../init/git';
import {changePlaceholderInTemplate} from '../init/editTemplate';
import {
copyTemplate,
executePostInitScript,
getTemplateConfig,
installTemplatePackage,
} from '../init/template';
import {tmpdir} from 'os';
import {mkdtempSync} from 'graceful-fs';
import {existsSync} from 'fs';
import {getNpmRegistryUrl} from '../../tools/npm';

type Options = {
packageName: string;
version: string;
pm: PackageManager;
title: string;
};

const NPM_REGISTRY_URL = getNpmRegistryUrl();

const getAppName = async (root: string) => {
logger.log(`Reading ${chalk.cyan('name')} from package.json…`);
const pkgJsonPath = join(root, 'package.json');

if (!pkgJsonPath) {
throw new CLIError(`Unable to find package.json inside ${root}`);
}

let name;

try {
name = JSON.parse(readFileSync(pkgJsonPath, 'utf8')).name;
} catch (e) {
throw new CLIError(`Failed to read ${pkgJsonPath} file.`, e as Error);
}

if (!name) {
const appJson = join(root, 'app.json');
if (appJson) {
logger.log(`Reading ${chalk.cyan('name')} from app.json…`);
try {
name = JSON.parse(readFileSync(appJson, 'utf8')).name;
} catch (e) {
throw new CLIError(`Failed to read ${pkgJsonPath} file.`, e as Error);
}
}

if (!name) {
throw new CLIError('Please specify name in package.json or app.json.');
}
}

return name;
};

const getPackageMatchingVersion = async (
packageName: string,
version: string,
) => {
const npmResponse = await npmFetch.json(packageName, {
registry: NPM_REGISTRY_URL,
szymonrybczak marked this conversation as resolved.
Show resolved Hide resolved
});

if ('dist-tags' in npmResponse) {
const distTags = npmResponse['dist-tags'] as Record<string, string>;
if (version in distTags) {
return distTags[version];
}
}

if ('versions' in npmResponse) {
const versions = Object.keys(
npmResponse.versions as Record<string, unknown>,
);
if (versions.length > 0) {
const candidates = versions
.filter((v) => semver.satisfies(v, version))
.sort(semver.rcompare);

if (candidates.length > 0) {
return candidates[0];
}
}
}

throw new Error(
`Cannot find matching version of ${packageName} to react-native${version}, please provide version manually with --version flag.`,
);
};

// From React Native 0.75 template is not longer inside `react-native` core,
// so we need to map package name (fork) to template name

const getTemplateNameFromPackageName = (packageName: string) => {
switch (packageName) {
case '@callstack/react-native-visionos':
case 'react-native-visionos':
return '@callstack/visionos-template';
default:
return packageName;
}
};

async function addPlatform(
[packageName]: string[],
{root, reactNativeVersion}: Config,
{version, pm, title}: Options,
) {
if (!packageName) {
throw new CLIError('Please provide package name e.g. react-native-macos');
}

const templateName = getTemplateNameFromPackageName(packageName);
const isGitAvailable = await checkGitInstallation();

if (isGitAvailable) {
const dirty = await isGitTreeDirty(root);

if (dirty) {
logger.warn(
'Your git tree is dirty. We recommend committing or stashing changes first.',
);
const {proceed} = await prompt({
type: 'confirm',
name: 'proceed',
message: 'Would you like to proceed?',
});

if (!proceed) {
return;
}

logger.info('Proceeding with the installation');
}
}

const projectName = await getAppName(root);

const matchingVersion = await getPackageMatchingVersion(
packageName,
version ?? reactNativeVersion,
);

logger.log(
`Found matching version ${chalk.cyan(matchingVersion)} for ${chalk.cyan(
packageName,
)}`,
);

const loader = getLoader({
text: `Installing ${packageName}@${matchingVersion}`,
});

loader.start();

try {
await install([`${packageName}@${matchingVersion}`], {
packageManager: pm,
silent: true,
root,
});
loader.succeed();
} catch (error) {
loader.fail();
throw new CLIError(
`Failed to install package ${packageName}@${matchingVersion}`,
(error as Error).message,
);
}

loader.start(
`Installing template packages from ${templateName}@0${matchingVersion}`,
);

const templateSourceDir = mkdtempSync(join(tmpdir(), 'rncli-init-template-'));

try {
await installTemplatePackage(
`${templateName}@0${matchingVersion}`,
templateSourceDir,
pm,
);
loader.succeed();
} catch (error) {
loader.fail();
throw new CLIError(
`Failed to install template packages from ${templateName}@0${matchingVersion}`,
(error as Error).message,
);
}

loader.start('Copying template files');

const templateConfig = getTemplateConfig(templateName, templateSourceDir);

if (!templateConfig.platforms) {
throw new CLIError(
`Template ${templateName} is missing "platforms" in its "template.config.js"`,
);
}

for (const platform of templateConfig.platforms) {
if (existsSync(join(root, platform))) {
loader.fail();
throw new CLIError(
`Platform ${platform} already exists in the project. Directory ${join(
root,
platform,
)} is not empty.`,
);
}

await copyTemplate(
templateName,
templateConfig.templateDir,
templateSourceDir,
platform,
);
}

loader.succeed();
loader.start('Processing template');

for (const platform of templateConfig.platforms) {
await changePlaceholderInTemplate({
projectName,
projectTitle: title,
placeholderName: templateConfig.placeholderName,
placeholderTitle: templateConfig.titlePlaceholder,
projectPath: join(root, platform),
});
}

loader.succeed();

const {postInitScript} = templateConfig;
if (postInitScript) {
logger.debug('Executing post init script ');
await executePostInitScript(
templateName,
postInitScript,
templateSourceDir,
);
}
}

export default addPlatform;
23 changes: 23 additions & 0 deletions packages/cli/src/commands/addPlatform/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import addPlatform from './addPlatform';

export default {
func: addPlatform,
name: 'add-platform [packageName]',
description: 'Add new platform to your React Native project.',
options: [
{
name: '--version <string>',
description: 'Pass version of the platform to be added to the project.',
},
{
name: '--pm <string>',
description:
'Use specific package manager to initialize the project. Available options: `yarn`, `npm`, `bun`. Default: `yarn`',
default: 'yarn',
},
{
name: '--title <string>',
description: 'Uses a custom app title name for application',
},
],
};
2 changes: 2 additions & 0 deletions packages/cli/src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import {commands as cleanCommands} from '@react-native-community/cli-clean';
import {commands as doctorCommands} from '@react-native-community/cli-doctor';
import {commands as configCommands} from '@react-native-community/cli-config';
import init from './init';
import addPlatform from './addPlatform';

export const projectCommands = [
...configCommands,
cleanCommands.clean,
doctorCommands.info,
addPlatform,
] as Command[];

export const detachedCommands = [
Expand Down
Loading
Loading