Skip to content

Commit

Permalink
Sync latest cli-plugin-metro changes (#38944)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: #38944

- Update `cli-commands` package to reflect latest source `react-native-community/cli-plugin-metro` changes.
	- react-native-community/cli#2021
	- react-native-community/cli#2024
	- react-native-community/cli#2043
	- react-native-community/cli#2047

### To do

WARNING: ~~This PR is non-functional until the next CLI alpha is published and bumped in `package.json` — since it depends on corresponding new APIs in `react-native-community/cli-tools` (react-native-community/cli#2021). This package (and the upcoming work which integrates it) has been tested against locally linked copies of latest CLI.~~

- [x] Bump CLI dependencies when next alpha published.
- [x] Ensure Metro bump from `0.77.0` to `0.78.0` is consistently applied with this.

Changelog: [Internal]

Reviewed By: motiz88

Differential Revision: D48066179

fbshipit-source-id: c47d14af132089796724f0375f3795488a90f88d
  • Loading branch information
huntie authored and facebook-github-bot committed Aug 14, 2023
1 parent 23bc1d2 commit e312065
Show file tree
Hide file tree
Showing 10 changed files with 215 additions and 211 deletions.
28 changes: 28 additions & 0 deletions flow-typed/npm/@react-native-community/cli-tools_v12.x.x.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,38 @@
*/

declare module '@react-native-community/cli-tools' {
declare export function addInteractionListener(
callback: (options: {pause: boolean, canEscape?: boolean}) => void,
): void;

declare export class CLIError extends Error {
constructor(msg: string, originalError?: Error | mixed | string): this;
}

declare export function getPidFromPort(port: number): number | null;

declare export function handlePortUnavailable(
initialPort: number,
projectRoot: string,
initialPackager?: boolean,
): Promise<{
port: number,
packager: boolean,
}>;

declare export function hookStdout(callback: Function): () => void;

declare export function isPackagerRunning(
packagerPort: string | number | void,
): Promise<
| {
status: 'running',
root: string,
}
| 'not_running'
| 'unrecognized',
>;

declare export const logger: $ReadOnly<{
success: (...message: Array<string>) => void,
info: (...message: Array<string>) => void,
Expand All @@ -29,6 +55,8 @@ declare module '@react-native-community/cli-tools' {
enable: () => void,
}>;

declare export function logAlreadyRunningBundler(port: number): void;

declare export function resolveNodeModuleDir(
root: string,
packageName: string,
Expand Down
7 changes: 0 additions & 7 deletions packages/community-cli-plugin/launchPackager.bat

This file was deleted.

10 changes: 0 additions & 10 deletions packages/community-cli-plugin/launchPackager.command

This file was deleted.

4 changes: 1 addition & 3 deletions packages/community-cli-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@
"./package.json": "./package.json"
},
"files": [
"dist",
"launchPackager.bat",
"launchPackager.command"
"dist"
],
"dependencies": {
"@react-native-community/cli-server-api": "12.0.0-alpha.9",
Expand Down
2 changes: 0 additions & 2 deletions packages/community-cli-plugin/src/commands/start/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,5 +93,3 @@ export default {
},
],
};

export {startServerInNewWindow} from './startServerInNewWindow';
60 changes: 47 additions & 13 deletions packages/community-cli-plugin/src/commands/start/runServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,23 @@ import typeof TerminalReporter from 'metro/src/lib/TerminalReporter';
import type Server from 'metro/src/Server';
import type {Middleware} from 'metro-config';

import chalk from 'chalk';
import Metro from 'metro';
import {Terminal} from 'metro-core';
import path from 'path';
import {
createDevServerMiddleware,
indexPageMiddleware,
} from '@react-native-community/cli-server-api';
import {
isPackagerRunning,
logger,
version,
logAlreadyRunningBundler,
handlePortUnavailable,
} from '@react-native-community/cli-tools';

import loadMetroConfig from '../../utils/loadMetroConfig';
import {version} from '@react-native-community/cli-tools';
import enableWatchMode from './watchMode';

export type Args = {
Expand All @@ -48,7 +55,43 @@ export type Args = {
};

async function runServer(_argv: Array<string>, ctx: Config, args: Args) {
let reportEvent: (event: any) => void;
let port = args.port ?? 8081;
let packager = true;
const packagerStatus = await isPackagerRunning(port);

if (
typeof packagerStatus === 'object' &&
packagerStatus.status === 'running'
) {
if (packagerStatus.root === ctx.root) {
packager = false;
logAlreadyRunningBundler(port);
} else {
const result = await handlePortUnavailable(port, ctx.root, packager);
[port, packager] = [result.port, result.packager];
}
} else if (packagerStatus === 'unrecognized') {
const result = await handlePortUnavailable(port, ctx.root, packager);
[port, packager] = [result.port, result.packager];
}

if (packager === false) {
process.exit();
}

logger.info(`Starting dev server on port ${chalk.bold(String(port))}`);

const metroConfig = await loadMetroConfig(ctx, {
config: args.config,
maxWorkers: args.maxWorkers,
port: port,
resetCache: args.resetCache,
watchFolders: args.watchFolders,
projectRoot: args.projectRoot,
sourceExts: args.sourceExts,
});

let reportEvent: (event: TerminalReportableEvent) => void;
const terminal = new Terminal(process.stdout);
const ReporterImpl = getReporterImpl(args.customLogReporterPath);
const terminalReporter = new ReporterImpl(terminal);
Expand All @@ -60,17 +103,8 @@ async function runServer(_argv: Array<string>, ctx: Config, args: Args) {
}
},
};

const metroConfig = await loadMetroConfig(ctx, {
config: args.config,
maxWorkers: args.maxWorkers,
port: args.port,
resetCache: args.resetCache,
watchFolders: args.watchFolders,
projectRoot: args.projectRoot,
sourceExts: args.sourceExts,
reporter,
});
// $FlowIgnore[cannot-write] Assigning to readonly property
metroConfig.reporter = reporter;

if (args.assetPlugins) {
// $FlowIgnore[cannot-write] Assigning to readonly property
Expand Down

This file was deleted.

73 changes: 41 additions & 32 deletions packages/community-cli-plugin/src/commands/start/watchMode.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,17 @@
import type {Config} from '@react-native-community/cli-types';

import readline from 'readline';
import {logger, hookStdout} from '@react-native-community/cli-tools';
import {
addInteractionListener,
logger,
hookStdout,
} from '@react-native-community/cli-tools';
import execa from 'execa';
import chalk from 'chalk';
import {KeyPressHandler} from '../../utils/KeyPressHandler';

const CTRL_C = '\u0003';
const CTRL_Z = '\u0026';

function printWatchModeInstructions() {
logger.log(
Expand Down Expand Up @@ -59,43 +67,44 @@ function enableWatchMode(
}
});

process.stdin.on(
'keypress',
(_key: string, data: {ctrl: boolean, name: string}) => {
const {ctrl, name} = data;
if (ctrl === true) {
switch (name) {
case 'c':
process.exit();
break;
case 'z':
process.emit('SIGTSTP', 'SIGTSTP');
break;
}
} else if (name === 'r') {
const onPressAsync = async (key: string) => {
switch (key) {
case 'r':
messageSocket.broadcast('reload', null);
logger.info('Reloading app...');
} else if (name === 'd') {
break;
case 'd':
messageSocket.broadcast('devMenu', null);
logger.info('Opening developer menu...');
} else if (name === 'i' || name === 'a') {
logger.info(
`Opening the app on ${name === 'i' ? 'iOS' : 'Android'}...`,
);
const params =
name === 'i'
? ctx.project.ios?.watchModeCommandParams
: ctx.project.android?.watchModeCommandParams;
logger.info('Opening Dev Menu...');
break;
case 'i':
logger.info('Opening app on iOS...');
execa('npx', [
'react-native',
name === 'i' ? 'run-ios' : 'run-android',
...(params ?? []),
'run-ios',
...(ctx.project.ios?.watchModeCommandParams ?? []),
]).stdout?.pipe(process.stdout);
} else {
console.log(_key);
}
},
);
break;
case 'a':
logger.info('Opening app on Android...');
execa('npx', [
'react-native',
'run-android',
...(ctx.project.android?.watchModeCommandParams ?? []),
]).stdout?.pipe(process.stdout);
break;
case CTRL_Z:
process.emit('SIGTSTP', 'SIGTSTP');
break;
case CTRL_C:
process.exit();
}
};

const keyPressHandler = new KeyPressHandler(onPressAsync);
const listener = keyPressHandler.createInteractionListener();
addInteractionListener(listener);
keyPressHandler.startInterceptingKeyStrokes();
}

export default enableWatchMode;
Loading

0 comments on commit e312065

Please sign in to comment.