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(v2): prompt user when default port is in use #3006

Merged
merged 5 commits into from
Jun 30, 2020
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
4 changes: 3 additions & 1 deletion packages/docusaurus/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"core-js": "^2.6.5",
"css-loader": "^3.4.2",
"del": "^5.1.0",
"detect-port": "^1.3.0",
"eta": "^1.1.1",
"express": "^4.17.1",
"fs-extra": "^8.1.0",
Expand All @@ -62,6 +63,8 @@
"html-tags": "^3.1.0",
"html-webpack-plugin": "^4.0.4",
"import-fresh": "^3.2.1",
"inquirer": "^7.2.0",
"is-root": "^2.1.0",
"lodash.has": "^4.5.2",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
Expand All @@ -70,7 +73,6 @@
"null-loader": "^3.0.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"pnp-webpack-plugin": "^1.6.4",
"portfinder": "^1.0.25",
"postcss-loader": "^3.0.0",
"postcss-preset-env": "^6.7.0",
"react-dev-utils": "^10.2.1",
Expand Down
136 changes: 136 additions & 0 deletions packages/docusaurus/src/choosePort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* This feature was heavily inspired by create-react-app and
* uses many of the same utility functions to implement it.
*/

import {execSync} from 'child_process';
import detect from 'detect-port';
import isRoot from 'is-root';
import chalk from 'chalk';
import inquirer from 'inquirer';

const isInteractive = process.stdout.isTTY;

const execOptions: object = {
encoding: 'utf8',
stdio: [
'pipe', // stdin (default)
'pipe', // stdout (default)
'ignore', // stderr
],
};

// Clears console
function clearConsole(): void {
process.stdout.write(
process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H',
);
}

// Gets process id of what is on port
function getProcessIdOnPort(port: number): string {
return execSync(`lsof -i:${port} -P -t -sTCP:LISTEN`, execOptions)
.toString()
.split('\n')[0]
.trim();
}

// Gets process command
function getProcessCommand(processId: string): Promise<string | null> | string {
let command: Buffer | string = execSync(
`ps -o command -p ${processId} | sed -n 2p`,
execOptions,
);

command = command.toString().replace(/\n$/, '');

return command;
}

// Gets directory of a process from its process id
function getDirectoryOfProcessById(processId: string): string {
return execSync(
`lsof -p ${processId} | awk '$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}'`,
execOptions,
)
.toString()
.trim();
}

// Gets process on port
function getProcessForPort(port: number): string | null {
try {
const processId = getProcessIdOnPort(port);
const directory = getDirectoryOfProcessById(processId);
const command = getProcessCommand(processId);
return (
chalk.cyan(command) +
chalk.grey(` (pid ${processId})\n`) +
chalk.blue(' in ') +
chalk.cyan(directory)
);
} catch (e) {
return null;
}
}

/**
* Detects if program is running on port and prompts user
* to choose another if port is already being used
*/
export default async function choosePort(
host: string,
defaultPort: number,
): Promise<number | null> {
return detect(defaultPort, host).then(
(port) =>
new Promise((resolve) => {
if (port === defaultPort) {
return resolve(port);
}
const message =
process.platform !== 'win32' && defaultPort < 1024 && !isRoot()
? `Admin permissions are required to run a server on a port below 1024.`
: `Something is already running on port ${defaultPort}.`;
if (isInteractive) {
clearConsole();
const existingProcess = getProcessForPort(defaultPort);
const question: any = {
type: 'confirm',
name: 'shouldChangePort',
message: `${chalk.yellow(
`${message}${
existingProcess ? ` Probably:\n ${existingProcess}` : ''
}`,
)}\n\nWould you like to run the app on another port instead?`,
default: true,
};
inquirer.prompt(question).then((answer: any) => {
if (answer.shouldChangePort) {
resolve(port);
} else {
resolve(null);
}
});
} else {
console.log(chalk.red(message));
resolve(null);
}
return null;
}),
(err) => {
throw new Error(
`${chalk.red(`Could not find an open port at ${chalk.bold(host)}.`)}\n${
`Network error message: ${err.message}` || err
}\n`,
);
},
);
}
17 changes: 13 additions & 4 deletions packages/docusaurus/src/commands/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import chokidar from 'chokidar';
import express from 'express';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import path from 'path';
import portfinder from 'portfinder';
taylorallen0913 marked this conversation as resolved.
Show resolved Hide resolved
import openBrowser from 'react-dev-utils/openBrowser';
import {prepareUrls} from 'react-dev-utils/WebpackDevServerUtils';
import errorOverlayMiddleware from 'react-dev-utils/errorOverlayMiddleware';
Expand All @@ -25,14 +24,18 @@ import {StartCLIOptions} from '@docusaurus/types';
import {CONFIG_FILE_NAME, STATIC_DIR_NAME, DEFAULT_PORT} from '../constants';
import createClientConfig from '../webpack/client';
import {applyConfigureWebpack} from '../webpack/utils';
import choosePort from '../choosePort';

function getHost(reqHost: string | undefined): string {
return reqHost || 'localhost';
}

async function getPort(reqPort: string | undefined): Promise<number> {
async function getPort(
reqPort: string | undefined,
host: string,
): Promise<number | null> {
const basePort = reqPort ? parseInt(reqPort, 10) : DEFAULT_PORT;
const port = await portfinder.getPortPromise({port: basePort});
const port = await choosePort(host, basePort);
return port;
}

Expand Down Expand Up @@ -78,8 +81,14 @@ export default async function start(
);

const protocol: string = process.env.HTTPS === 'true' ? 'https' : 'http';
const port: number = await getPort(cliOptions.port);

const host: string = getHost(cliOptions.host);
const port: number | null = await getPort(cliOptions.port, host);

if (port === null) {
process.exit();
}

const {baseUrl, headTags, preBodyTags, postBodyTags} = props;
const urls = prepareUrls(protocol, host, port);
const openUrl = normalizeUrl([urls.localUrlForBrowser, baseUrl]);
Expand Down
31 changes: 29 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2839,7 +2839,7 @@
version "17.1.2"
resolved "https://registry.yarnpkg.com/@types/hapi__joi/-/hapi__joi-17.1.2.tgz#f547d45b5d33677d1807ec217aeee832dc7e6334"
integrity sha512-2S6+hBISRQ5Ca6/9zfQi7zPueWMGyZxox6xicqJuW1/aC/6ambLyh+gDqY5fi8JBuHmGKMHldSfEpIXJtTmGKQ==

"@types/history@*":
version "4.7.6"
resolved "https://registry.yarnpkg.com/@types/history/-/history-4.7.6.tgz#ed8fc802c45b8e8f54419c2d054e55c9ea344356"
Expand Down Expand Up @@ -6615,6 +6615,14 @@ [email protected]:
address "^1.0.1"
debug "^2.6.0"

detect-port@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/detect-port/-/detect-port-1.3.0.tgz#d9c40e9accadd4df5cac6a782aefd014d573d1f1"
integrity sha512-E+B1gzkl2gqxt1IhUzwjrxBKRqx1UzC3WLONHinn8S3T6lwV/agVCyitiFOsGJ/eYuEUBvD71MZHy3Pv1G9doQ==
dependencies:
address "^1.0.1"
debug "^2.6.0"

dezalgo@^1.0.0:
version "1.0.3"
resolved "https://registry.yarnpkg.com/dezalgo/-/dezalgo-1.0.3.tgz#7f742de066fc748bc8db820569dddce49bf0d456"
Expand Down Expand Up @@ -9743,6 +9751,25 @@ inquirer@^7.1.0:
strip-ansi "^6.0.0"
through "^2.3.6"

inquirer@^7.2.0:
version "7.2.0"
resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-7.2.0.tgz#63ce99d823090de7eb420e4bb05e6f3449aa389a"
integrity sha512-E0c4rPwr9ByePfNlTIB8z51kK1s2n6jrHuJeEHENl/sbq2G/S1auvibgEwNR4uSyiU+PiYHqSwsgGiXjG8p5ZQ==
dependencies:
ansi-escapes "^4.2.1"
chalk "^3.0.0"
cli-cursor "^3.1.0"
cli-width "^2.0.0"
external-editor "^3.0.3"
figures "^3.0.0"
lodash "^4.17.15"
mute-stream "0.0.8"
run-async "^2.4.0"
rxjs "^6.5.3"
string-width "^4.1.0"
strip-ansi "^6.0.0"
through "^2.3.6"

internal-ip@^4.3.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/internal-ip/-/internal-ip-4.3.0.tgz#845452baad9d2ca3b69c635a137acb9a0dad0907"
Expand Down Expand Up @@ -10206,7 +10233,7 @@ is-retry-allowed@^1.0.0, is-retry-allowed@^1.1.0:
resolved "https://registry.yarnpkg.com/is-retry-allowed/-/is-retry-allowed-1.2.0.tgz#d778488bd0a4666a3be8a1482b9f2baafedea8b4"
integrity sha512-RUbUeKwvm3XG2VYamhJL1xFktgjvPzL0Hq8C+6yrWIswDy3BIXGqCxhxkc30N9jqK311gVU137K8Ei55/zVJRg==

[email protected]:
[email protected], is-root@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/is-root/-/is-root-2.1.0.tgz#809e18129cf1129644302a4f8544035d51984a9c"
integrity sha512-AGOriNp96vNBd3HtU+RzFEc75FfR5ymiYv8E553I71SCeXBiMsVDUtdio1OEFvrPyLIQ9tVR5RxXIFe5PUFjMg==
Expand Down