Skip to content

Commit

Permalink
feat: add --config & --generated-files-dir option to CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
longlho committed Feb 27, 2021
1 parent 12afb9e commit 15b50dc
Show file tree
Hide file tree
Showing 13 changed files with 198 additions and 107 deletions.
35 changes: 25 additions & 10 deletions packages/docusaurus-types/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,21 +131,36 @@ export type HostPortCLIOptions = {
port?: string;
};

export type StartCLIOptions = HostPortCLIOptions & {
hotOnly: boolean;
open: boolean;
poll: boolean | number;
locale?: string;
export type ConfigOptions = {
config: string;
};

export type ServeCLIOptions = HostPortCLIOptions & {
build: boolean;
dir: string;
};
export type StartCLIOptions = HostPortCLIOptions &
ConfigOptions & {
hotOnly: boolean;
open: boolean;
poll: boolean | number;
locale?: string;
};

export type BuildOptions = {
export type ServeCLIOptions = HostPortCLIOptions &
ConfigOptions & {
dir: string;
} & (
| {
build: true;
// We only need generatedFilesDir when `build` is true
generatedFilesDir: string;
}
| {
build: false;
}
);

export type BuildOptions = ConfigOptions & {
bundleAnalyzer: boolean;
outDir: string;
generatedFilesDir: string;
minify: boolean;
skipBuild: boolean;
};
Expand Down
94 changes: 73 additions & 21 deletions packages/docusaurus/bin/docusaurus.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ cli
'--out-dir <dir>',
'The full path for the new output directory, relative to the current workspace (default: build).',
)
.option(
'--config <config>',
'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`',
)
.option(
'--generated-files-dir <dir>',
'Path to temporary `.docusaurus` folder, default to `[siteDir]/.docusaurus`.',
)
.option(
'-l, --locale <locale>',
'Build the site in a specified locale. Build all known locales otherwise.',
Expand All @@ -117,14 +125,21 @@ cli
'--no-minify',
'Build website without minimizing JS bundles (default: false)',
)
.action((siteDir = '.', {bundleAnalyzer, outDir, locale, minify}) => {
wrapCommand(build)(path.resolve(siteDir), {
bundleAnalyzer,
outDir,
locale,
minify,
});
});
.action(
(
siteDir = '.',
{bundleAnalyzer, config, generatedFilesDir, outDir, locale, minify},
) => {
wrapCommand(build)(path.resolve(siteDir), {
bundleAnalyzer,
outDir,
config,
generatedFilesDir,
locale,
minify,
});
},
);

cli
.command('swizzle [themeName] [componentName] [siteDir]')
Expand Down Expand Up @@ -155,12 +170,25 @@ cli
'--out-dir <dir>',
'The full path for the new output directory, relative to the current workspace (default: build).',
)
.option(
'--config <config>',
'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`',
)
.option(
'--generated-files-dir <dir>',
'Path to temporary `.docusaurus` folder, default to `[siteDir]/.docusaurus`. This is only relevant when `--build` passed in.',
)
.option(
'--skip-build',
'Skip building website before deploy it (default: false)',
)
.action((siteDir = '.', {outDir, skipBuild}) => {
wrapCommand(deploy)(path.resolve(siteDir), {outDir, skipBuild});
.action((siteDir = '.', {outDir, skipBuild, config, generatedFilesDir}) => {
wrapCommand(deploy)(path.resolve(siteDir), {
outDir,
config,
generatedFilesDir,
skipBuild,
});
});

cli
Expand All @@ -173,21 +201,28 @@ cli
'--hot-only',
'Do not fallback to page refresh if hot reload fails (default: false)',
)
.option(
'--config <config>',
'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`',
)
.option('--no-open', 'Do not open page in the browser (default: false)')
.option(
'--poll [interval]',
'Use polling rather than watching for reload (default: false). Can specify a poll interval in milliseconds.',
)
.action((siteDir = '.', {port, host, locale, hotOnly, open, poll}) => {
wrapCommand(start)(path.resolve(siteDir), {
port,
host,
locale,
hotOnly,
open,
poll,
});
});
.action(
(siteDir = '.', {port, host, locale, config, hotOnly, open, poll}) => {
wrapCommand(start)(path.resolve(siteDir), {
port,
host,
locale,
config,
hotOnly,
open,
poll,
});
},
);

cli
.command('serve [siteDir]')
Expand All @@ -196,6 +231,14 @@ cli
'--dir <dir>',
'The full path for the new output directory, relative to the current workspace (default: build).',
)
.option(
'--config <config>',
'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`',
)
.option(
'--generated-files-dir <dir>',
'Path to temporary `.docusaurus` folder, default to `[siteDir]/.docusaurus`. This is only relevant when `--build` passed in.',
)
.option('-p, --port <port>', 'use specified port (default: 3000)')
.option('--build', 'Build website before serving (default: false)')
.option('-h, --host <host>', 'use specified host (default: localhost')
Expand All @@ -207,12 +250,16 @@ cli
port = 3000,
host = 'localhost',
build: buildSite = false,
config,
generatedFilesDir,
},
) => {
wrapCommand(serve)(path.resolve(siteDir), {
dir,
port,
build: buildSite,
config,
generatedFilesDir,
host,
});
},
Expand All @@ -236,18 +283,23 @@ cli
'--override',
'By default, we only append missing translation messages to existing translation files. This option allows to override existing translation messages. Make sure to commit or backup your existing translations, as they may be overridden.',
)
.option(
'--config <config>',
'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`',
)
.option(
'--messagePrefix <messagePrefix>',
'Allows to init new written messages with a given prefix. This might help you to highlight untranslated message to make them stand out in the UI.',
)
.action(
(
siteDir = '.',
{locale = undefined, override = false, messagePrefix = ''},
{locale = undefined, override = false, messagePrefix = '', config},
) => {
wrapCommand(writeTranslations)(path.resolve(siteDir), {
locale,
override,
config,
messagePrefix,
});
},
Expand Down
15 changes: 11 additions & 4 deletions packages/docusaurus/src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {Configuration, Plugin} from 'webpack';
import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer';
import merge from 'webpack-merge';
import {STATIC_DIR_NAME} from '../constants';
import {load} from '../server';
import {load, loadContext} from '../server';
import {handleBrokenLinks} from '../server/brokenLinks';

import {BuildCLIOptions, Props} from '@docusaurus/types';
Expand All @@ -28,7 +28,6 @@ import {
import CleanWebpackPlugin from '../webpack/plugins/CleanWebpackPlugin';
import {loadI18n} from '../server/i18n';
import {mapAsyncSequencial} from '@docusaurus/utils';
import loadConfig from '../server/config';

export default async function build(
siteDir: string,
Expand Down Expand Up @@ -59,8 +58,14 @@ export default async function build(
throw e;
}
}

const i18n = await loadI18n(loadConfig(siteDir), {
const context = await loadContext(siteDir, {
customOutDir: cliOptions.outDir,
customGeneratedFilesDir: cliOptions.generatedFilesDir,
customConfigFilePath: cliOptions.config,
locale: cliOptions.locale,
localizePath: cliOptions.locale ? false : undefined,
});
const i18n = await loadI18n(context.siteConfig, {
locale: cliOptions.locale,
});
if (cliOptions.locale) {
Expand Down Expand Up @@ -112,6 +117,8 @@ async function buildLocale({

const props: Props = await load(siteDir, {
customOutDir: cliOptions.outDir,
customConfigFilePath: cliOptions.config,
customGeneratedFilesDir: cliOptions.generatedFilesDir,
locale,
localizePath: cliOptions.locale ? false : undefined,
});
Expand Down
45 changes: 14 additions & 31 deletions packages/docusaurus/src/commands/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
*/

import fs from 'fs-extra';
import path from 'path';
import shell from 'shelljs';
import chalk from 'chalk';
import {CONFIG_FILE_NAME, GENERATED_FILES_DIR_NAME} from '../constants';
import {CONFIG_FILE_NAME} from '../constants';
import {loadContext} from '../server';
import loadConfig from '../server/config';
import build from './build';
import {BuildCLIOptions} from '@docusaurus/types';
import {mkdtempSync} from 'fs';
import path from 'path';
import os from 'os';

// GIT_PASS env variable should not appear in logs
function obfuscateGitPass(str) {
Expand Down Expand Up @@ -42,10 +43,10 @@ export default async function deploy(
siteDir: string,
cliOptions: Partial<BuildCLIOptions> = {},
): Promise<void> {
const {outDir} = await loadContext(siteDir, {
const {outDir, siteConfig} = await loadContext(siteDir, {
customConfigFilePath: cliOptions.config,
customOutDir: cliOptions.outDir,
});
const tempDir = path.join(siteDir, GENERATED_FILES_DIR_NAME);

console.log('Deploy command invoked ...');
if (!shell.which('git')) {
Expand All @@ -62,7 +63,6 @@ export default async function deploy(
process.env.CURRENT_BRANCH ||
shell.exec('git rev-parse --abbrev-ref HEAD').stdout.trim();

const siteConfig = loadConfig(siteDir);
const organizationName =
process.env.ORGANIZATION_NAME ||
process.env.CIRCLE_PROJECT_USERNAME ||
Expand Down Expand Up @@ -142,21 +142,15 @@ export default async function deploy(
const currentCommit = shellExecLog('git rev-parse HEAD').stdout.trim();

const runDeploy = (outputDirectory) => {
if (shell.cd(tempDir).code !== 0) {
throw new Error(
`Temp dir ${GENERATED_FILES_DIR_NAME} does not exists. Run build website first.`,
);
}

if (
shellExecLog(
`git clone ${remoteBranch} ${projectName}-${deploymentBranch}`,
).code !== 0
) {
throw new Error('Error: git clone failed');
const fromPath = outputDirectory;
const toPath = mkdtempSync(
path.join(os.tmpdir(), `${projectName}-${deploymentBranch}`),
);
if (shellExecLog(`git clone ${remoteBranch} ${toPath}`).code !== 0) {
throw new Error(`Error: git clone failed in ${toPath}`);
}

shell.cd(`${projectName}-${deploymentBranch}`);
shell.cd(toPath);

// If the default branch is the one we're deploying to, then we'll fail
// to create it. This is the case of a cross-repo publish, where we clone
Expand Down Expand Up @@ -184,18 +178,10 @@ export default async function deploy(

shellExecLog('git rm -rf .');

shell.cd('../..');

const fromPath = outputDirectory;
const toPath = path.join(
GENERATED_FILES_DIR_NAME,
`${projectName}-${deploymentBranch}`,
);

fs.copy(fromPath, toPath, (error) => {
if (error) {
throw new Error(
`Error: Copying build assets failed with error '${error}'`,
`Error: Copying build assets from "${fromPath}" to "${toPath}" failed with error '${error}'`,
);
}

Expand Down Expand Up @@ -228,9 +214,6 @@ export default async function deploy(
};

if (!cliOptions.skipBuild) {
// Clear Docusaurus 2 cache dir for deploy consistency.
fs.removeSync(tempDir);

// Build static html files, then push to deploymentBranch branch of specified repo.
build(siteDir, cliOptions, false)
.then(runDeploy)
Expand Down
6 changes: 5 additions & 1 deletion packages/docusaurus/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@ export default async function serve(
siteDir: string,
cliOptions: ServeCLIOptions,
): Promise<void> {
let dir = path.join(siteDir, cliOptions.dir);
let dir = path.isAbsolute(cliOptions.dir)
? cliOptions.dir
: path.join(siteDir, cliOptions.dir);
if (cliOptions.build) {
dir = await build(
siteDir,
{
generatedFilesDir: cliOptions.generatedFilesDir,
config: cliOptions.config,
outDir: dir,
},
false,
Expand Down
1 change: 1 addition & 0 deletions packages/docusaurus/src/commands/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export default async function start(

function loadSite() {
return load(siteDir, {
customConfigFilePath: cliOptions.config,
locale: cliOptions.locale,
localizePath: undefined, // should this be configurable?
});
Expand Down
Loading

0 comments on commit 15b50dc

Please sign in to comment.