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

refactor(cli): make the CLI an even thinner wrapper around command functions #7583

Merged
merged 2 commits into from Jun 15, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 11 additions & 26 deletions packages/docusaurus/bin/docusaurus.mjs
Expand Up @@ -8,7 +8,6 @@

// @ts-check

import fs from 'fs-extra';
import logger from '@docusaurus/logger';
import cli from 'commander';
import {DOCUSAURUS_VERSION} from '@docusaurus/utils';
Expand All @@ -27,8 +26,6 @@ import beforeCli from './beforeCli.mjs';

await beforeCli();

const resolveDir = (dir = '.') => fs.realpath(dir);

cli.version(DOCUSAURUS_VERSION).usage('<command> [options]');

cli
Expand All @@ -54,9 +51,9 @@ cli
'--no-minify',
'build website without minimizing JS bundles (default: false)',
)
.action(async (siteDir, options) => {
await build(await resolveDir(siteDir), options);
});
// @ts-expect-error: Promise<string> is not assignable to Promise<void>... but
// good enough here.
.action(build);

cli
.command('swizzle [themeName] [componentName] [siteDir]')
Expand All @@ -80,9 +77,7 @@ cli
'copy TypeScript theme files when possible (default: false)',
)
.option('--danger', 'enable swizzle for unsafe component of themes')
.action(async (themeName, componentName, siteDir, options) =>
swizzle(await resolveDir(siteDir), themeName, componentName, options),
);
.action(swizzle);

cli
.command('deploy [siteDir]')
Expand All @@ -103,9 +98,7 @@ cli
'--skip-build',
'skip building website before deploy it (default: false)',
)
.action(async (siteDir, options) =>
deploy(await resolveDir(siteDir), options),
);
.action(deploy);

cli
.command('start [siteDir]')
Expand All @@ -130,9 +123,7 @@ cli
'--no-minify',
'build website without minimizing JS bundles (default: false)',
)
.action(async (siteDir, options) =>
start(await resolveDir(siteDir), options),
);
.action(start);

cli
.command('serve [siteDir]')
Expand All @@ -152,14 +143,12 @@ cli
'--no-open',
'do not open page in the browser (default: false, or true in CI)',
)
.action(async (siteDir, options) =>
serve(await resolveDir(siteDir), options),
);
.action(serve);

cli
.command('clear [siteDir]')
.description('Remove build artifacts.')
.action(async (siteDir) => clear(await resolveDir(siteDir)));
.action(clear);

cli
.command('write-translations [siteDir]')
Expand All @@ -180,9 +169,7 @@ cli
'--messagePrefix <messagePrefix>',
'Allows to init new written messages with a given prefix. This might help you to highlight untranslated message by making them stand out in the UI (default: "")',
)
.action(async (siteDir, options) =>
writeTranslations(await resolveDir(siteDir), options),
);
.action(writeTranslations);

cli
.command('write-heading-ids [siteDir] [files...]')
Expand All @@ -192,9 +179,7 @@ cli
"keep the headings' casing, otherwise make all lowercase (default: false)",
)
.option('--overwrite', 'overwrite existing heading IDs (default: false)')
.action(async (siteDir, files, options) =>
writeHeadingIds(await resolveDir(siteDir), files, options),
);
.action(writeHeadingIds);

cli.arguments('<command>').action((cmd) => {
cli.outputHelp();
Expand All @@ -221,7 +206,7 @@ function isInternalCommand(command) {
}

if (!isInternalCommand(process.argv.slice(2)[0])) {
await externalCommand(cli, await resolveDir('.'));
await externalCommand(cli);
}

if (!process.argv.slice(2).length) {
Expand Down
6 changes: 4 additions & 2 deletions packages/docusaurus/src/commands/build.ts
Expand Up @@ -38,14 +38,16 @@ export type BuildCLIOptions = Pick<
};

export async function build(
siteDir: string,
cliOptions: Partial<BuildCLIOptions>,
siteDirParam: string = '.',
cliOptions: Partial<BuildCLIOptions> = {},
// When running build, we force terminate the process to prevent async
// operations from never returning. However, if run as part of docusaurus
// deploy, we have to let deploy finish.
// See https://github.com/facebook/docusaurus/pull/2496
forceTerminate: boolean = true,
): Promise<string> {
const siteDir = await fs.realpath(siteDirParam);

['SIGINT', 'SIGTERM'].forEach((sig) => {
process.on(sig, () => process.exit());
});
Expand Down
4 changes: 3 additions & 1 deletion packages/docusaurus/src/commands/clear.ts
Expand Up @@ -26,7 +26,9 @@ async function removePath(entry: {path: string; description: string}) {
}
}

export async function clear(siteDir: string): Promise<void> {
export async function clear(siteDirParam: string = '.'): Promise<void> {
const siteDir = await fs.realpath(siteDirParam);

const generatedFolder = {
path: path.join(siteDir, GENERATED_FILES_DIR_NAME),
description: 'generated folder',
Expand Down
6 changes: 4 additions & 2 deletions packages/docusaurus/src/commands/deploy.ts
Expand Up @@ -41,9 +41,11 @@ function shellExecLog(cmd: string) {
}

export async function deploy(
siteDir: string,
cliOptions: Partial<DeployCLIOptions>,
siteDirParam: string = '.',
cliOptions: Partial<DeployCLIOptions> = {},
): Promise<void> {
const siteDir = await fs.realpath(siteDirParam);

const {outDir, siteConfig, siteConfigPath} = await loadContext({
siteDir,
config: cliOptions.config,
Expand Down
7 changes: 3 additions & 4 deletions packages/docusaurus/src/commands/external.ts
Expand Up @@ -5,14 +5,13 @@
* LICENSE file in the root directory of this source tree.
*/

import fs from 'fs-extra';
import {loadContext} from '../server';
import {initPlugins} from '../server/plugins/init';
import type {CommanderStatic} from 'commander';

export async function externalCommand(
cli: CommanderStatic,
siteDir: string,
): Promise<void> {
export async function externalCommand(cli: CommanderStatic): Promise<void> {
const siteDir = await fs.realpath('.');
Copy link
Collaborator

Choose a reason for hiding this comment

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

🤔 that looks different from the other cli commands 🤪

But same as before so maybe a different issue

const context = await loadContext({siteDir});
const plugins = await initPlugins(context);

Expand Down
7 changes: 5 additions & 2 deletions packages/docusaurus/src/commands/serve.ts
Expand Up @@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import fs from 'fs-extra';
import http from 'http';
import path from 'path';
import logger from '@docusaurus/logger';
Expand All @@ -24,9 +25,11 @@ export type ServeCLIOptions = HostPortOptions &
};

export async function serve(
siteDir: string,
cliOptions: Partial<ServeCLIOptions>,
siteDirParam: string = '.',
cliOptions: Partial<ServeCLIOptions> = {},
): Promise<void> {
const siteDir = await fs.realpath(siteDirParam);

const buildDir = cliOptions.dir ?? DEFAULT_BUILD_DIR_NAME;
let dir = path.resolve(siteDir, buildDir);

Expand Down
7 changes: 5 additions & 2 deletions packages/docusaurus/src/commands/start.ts
Expand Up @@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import fs from 'fs-extra';
import path from 'path';
import _ from 'lodash';
import logger from '@docusaurus/logger';
Expand Down Expand Up @@ -35,9 +36,11 @@ export type StartCLIOptions = HostPortOptions &
};

export async function start(
siteDir: string,
cliOptions: Partial<StartCLIOptions>,
siteDirParam: string = '.',
cliOptions: Partial<StartCLIOptions> = {},
): Promise<void> {
const siteDir = await fs.realpath(siteDirParam);

process.env.NODE_ENV = 'development';
process.env.BABEL_ENV = 'development';
logger.info('Starting the development server...');
Expand Down
Expand Up @@ -111,7 +111,7 @@ async function createTestSite() {
component: string;
typescript?: boolean;
}) {
return swizzleWithExit(siteDir, FixtureThemeName, component, {
return swizzleWithExit(FixtureThemeName, component, siteDir, {
wrap: true,
danger: true,
typescript,
Expand All @@ -125,7 +125,7 @@ async function createTestSite() {
component: string;
typescript?: boolean;
}) {
return swizzleWithExit(siteDir, FixtureThemeName, component, {
return swizzleWithExit(FixtureThemeName, component, siteDir, {
eject: true,
danger: true,
typescript,
Expand Down
11 changes: 7 additions & 4 deletions packages/docusaurus/src/commands/swizzle/index.ts
Expand Up @@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import fs from 'fs-extra';
import logger from '@docusaurus/logger';
import {getThemeName, getThemePath, getThemeNames} from './themes';
import {getThemeComponents, getComponentName} from './components';
Expand Down Expand Up @@ -87,11 +88,13 @@ If you want to swizzle it, use the code=${'--danger'} flag, or confirm that you
}

export async function swizzle(
siteDir: string,
themeNameParam: string | undefined,
componentNameParam: string | undefined,
optionsParam: Partial<SwizzleCLIOptions>,
themeNameParam: string | undefined = undefined,
componentNameParam: string | undefined = undefined,
siteDirParam: string = '.',
optionsParam: Partial<SwizzleCLIOptions> = {},
): Promise<void> {
const siteDir = await fs.realpath(siteDirParam);

const options = normalizeOptions(optionsParam);
const {list, danger, typescript} = options;

Expand Down
8 changes: 5 additions & 3 deletions packages/docusaurus/src/commands/writeHeadingIds.ts
Expand Up @@ -41,10 +41,12 @@ async function getPathsToWatch(siteDir: string): Promise<string[]> {
}

export async function writeHeadingIds(
siteDir: string,
files: string[] | undefined,
options: WriteHeadingIDOptions,
siteDirParam: string = '.',
files: string[] = [],
options: WriteHeadingIDOptions = {},
): Promise<void> {
const siteDir = await fs.realpath(siteDirParam);

const markdownFiles = await safeGlobby(
files ?? (await getPathsToWatch(siteDir)),
{
Expand Down
7 changes: 5 additions & 2 deletions packages/docusaurus/src/commands/writeTranslations.ts
Expand Up @@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import fs from 'fs-extra';
import path from 'path';
import {loadContext, type LoadContextOptions} from '../server';
import {initPlugins} from '../server/plugins/init';
Expand Down Expand Up @@ -75,9 +76,11 @@ async function writePluginTranslationFiles({
}

export async function writeTranslations(
siteDir: string,
options: Partial<WriteTranslationsCLIOptions>,
siteDirParam: string = '.',
options: Partial<WriteTranslationsCLIOptions> = {},
): Promise<void> {
const siteDir = await fs.realpath(siteDirParam);

const context = await loadContext({
siteDir,
config: options.config,
Expand Down