Skip to content

Commit

Permalink
Merge branch 'stramel-ms/prompt-for-alternative-port'
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott committed Jun 10, 2020
2 parents f79ec28 + 141c49e commit 7ed25ce
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 21 deletions.
34 changes: 13 additions & 21 deletions src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import cacache from 'cacache';
import chalk from 'chalk';
import chokidar from 'chokidar';
import isCompressible from 'compressible';
import detectPort from 'detect-port';
import etag from 'etag';
import {EventEmitter} from 'events';
import execa from 'execa';
Expand Down Expand Up @@ -70,7 +69,7 @@ import {
generateEnvModule,
} from './build-util';
import {command as installCommand} from './install';
import {paint} from './paint';
import {paint, getPort} from './paint';
import srcFileExtensionMapping from './src-file-extension-mapping';

const HMR_DEV_CODE = readFileSync(path.join(__dirname, '../assets/hmr.js'));
Expand Down Expand Up @@ -177,9 +176,14 @@ function getMountedDirectory(cwd: string, workerConfig: BuildScript): [string, s
let currentlyRunningCommand: any = null;

export async function command(commandOptions: CommandOptions) {
let serverStart = Date.now();
const {cwd, config} = commandOptions;
const {port, open, hmr: isHmr} = config.devOptions;
const {port: defaultPort, open, hmr: isHmr} = config.devOptions;
let serverStart = Date.now();
const port = await getPort(defaultPort);
// Reset the clock if we had to wait for the user to select a new port.
if (port !== defaultPort) {
serverStart = Date.now();
}

const inMemoryBuildCache = new Map<string, Buffer>();
const inMemoryResourceCache = new Map<string, string>();
Expand All @@ -188,23 +192,6 @@ export async function command(commandOptions: CommandOptions) {
const messageBus = new EventEmitter();
const mountedDirectories: [string, string][] = [];

// Check whether the port is available
const availablePort = await detectPort(port);
const isPortAvailable = port === availablePort;

if (!isPortAvailable) {
console.error();
console.error(
chalk.red(
` ✘ port ${chalk.bold(port)} is not available. use ${chalk.bold(
'--port',
)} to specify a different port.`,
),
);
console.error();
process.exit(1);
}

// Set the proper install options, in case an install is needed.
commandOptions.config.installOptions.dest = DEV_DEPENDENCIES_DIR;
commandOptions.config.installOptions.env.NODE_ENV = process.env.NODE_ENV || 'development';
Expand Down Expand Up @@ -787,6 +774,11 @@ export async function command(commandOptions: CommandOptions) {

sendFile(req, res, wrappedResponse, responseFileExt);
})
.on('error', (err: Error) => {
console.error(chalk.red(` ✘ Failed to start server at port ${chalk.bold(port)}.`), err);
server.close();
process.exit(1);
})
.on('upgrade', (req: http.IncomingMessage, socket, head) => {
config.proxy.forEach(([pathPrefix, proxyOptions]) => {
const isWebSocket = proxyOptions.ws || proxyOptions.target?.toString().startsWith('ws');
Expand Down
41 changes: 41 additions & 0 deletions src/commands/paint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,49 @@ import readline from 'readline';
import util from 'util';
import {BuildScript} from '../config';
import {isYarn} from '../util';
import detectPort from 'detect-port';
const cwd = process.cwd();

/**
* Get the actual port, based on the `defaultPort`.
* If the default port was not available, then we'll prompt the user if its okay
* to use the next available port.
*/
export async function getPort(defaultPort: number): Promise<number> {
const bestAvailablePort = await detectPort(defaultPort);
if (defaultPort !== bestAvailablePort) {
let useNextPort: boolean = false;
if (process.stdout.isTTY) {
const rl = readline.createInterface({input: process.stdin, output: process.stdout});
useNextPort = await new Promise((resolve) => {
rl.question(
chalk.yellow(
`! Port ${chalk.bold(defaultPort)} not available. Run on port ${chalk.bold(
bestAvailablePort,
)} instead? (Y/n) `,
),
(answer) => {
resolve(!/^no?$/i.test(answer));
},
);
});
rl.close();
}
if (!useNextPort) {
console.error(
chalk.red(
`✘ Port ${chalk.bold(defaultPort)} not available. Use ${chalk.bold(
'--port',
)} to specify a different port.`,
),
);
console.error();
process.exit(1);
}
}
return bestAvailablePort;
}

function getStateString(workerState: any, isWatch: boolean): [chalk.ChalkFunction, string] {
if (workerState.state) {
if (Array.isArray(workerState.state)) {
Expand Down

0 comments on commit 7ed25ce

Please sign in to comment.