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(core): reorganize functions #7037

Merged
merged 1 commit into from
Mar 28, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {loadContext} from '@docusaurus/core/src/server/index';
import {applyConfigureWebpack} from '@docusaurus/core/src/webpack/utils';
import type {RouteConfig} from '@docusaurus/types';
import {posixPath, DEFAULT_PLUGIN_ID} from '@docusaurus/utils';
import {sortConfig} from '@docusaurus/core/src/server/plugins';
import {sortConfig} from '@docusaurus/core/src/server/plugins/routeConfig';

import * as cliDocs from '../cli';
import {validateOptions} from '../options';
Expand Down
84 changes: 84 additions & 0 deletions packages/docusaurus-utils/src/__tests__/i18nUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
* LICENSE file in the root directory of this source tree.
*/

import path from 'path';
import {
mergeTranslations,
updateTranslationFileMessages,
getPluginI18nPath,
localizePath,
} from '../i18nUtils';

describe('mergeTranslations', () => {
Expand Down Expand Up @@ -93,3 +95,85 @@ describe('getPluginI18nPath', () => {
).toMatchInlineSnapshot(`"/i18n/zh-Hans/plugin-content-docs"`);
});
});

describe('localizePath', () => {
it('localizes url path with current locale', () => {
expect(
localizePath({
pathType: 'url',
path: '/baseUrl',
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
currentLocale: 'fr',
localeConfigs: {},
},
options: {localizePath: true},
}),
).toBe('/baseUrl/fr/');
});

it('localizes fs path with current locale', () => {
expect(
localizePath({
pathType: 'fs',
path: '/baseFsPath',
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
currentLocale: 'fr',
localeConfigs: {},
},
options: {localizePath: true},
}),
).toBe(`${path.sep}baseFsPath${path.sep}fr`);
});

it('localizes path for default locale, if requested', () => {
expect(
localizePath({
pathType: 'url',
path: '/baseUrl/',
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
currentLocale: 'en',
localeConfigs: {},
},
options: {localizePath: true},
}),
).toBe('/baseUrl/en/');
});

it('does not localize path for default locale by default', () => {
expect(
localizePath({
pathType: 'url',
path: '/baseUrl/',
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
currentLocale: 'en',
localeConfigs: {},
},
// options: {localizePath: true},
}),
).toBe('/baseUrl/');
});

it('localizes path for non-default locale by default', () => {
expect(
localizePath({
pathType: 'url',
path: '/baseUrl/',
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
currentLocale: 'en',
localeConfigs: {},
},
// options: {localizePath: true},
}),
).toBe('/baseUrl/');
});
});
50 changes: 49 additions & 1 deletion packages/docusaurus-utils/src/i18nUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@

import path from 'path';
import _ from 'lodash';
import type {TranslationFileContent, TranslationFile} from '@docusaurus/types';
import type {
TranslationFileContent,
TranslationFile,
I18n,
} from '@docusaurus/types';
import {DEFAULT_PLUGIN_ID, I18N_DIR_NAME} from './constants';
import {normalizeUrl} from './urlUtils';

/**
* Takes a list of translation file contents, and shallow-merges them into one.
Expand Down Expand Up @@ -65,3 +70,46 @@ export function getPluginI18nPath({
...subPaths,
);
}

/**
* Takes a path and returns a localized a version (which is basically `path +
* i18n.currentLocale`).
*/
export function localizePath({
pathType,
path: originalPath,
i18n,
options = {},
}: {
/**
* FS paths will treat Windows specially; URL paths will always have a
* trailing slash to make it a valid base URL.
*/
pathType: 'fs' | 'url';
/** The path, URL or file path, to be localized. */
path: string;
/** The current i18n context. */
i18n: I18n;
options?: {
/**
* By default, we don't localize the path of defaultLocale. This option
* would override that behavior. Setting `false` is useful for `yarn build
* -l zh-Hans` to always emit into the root build directory.
*/
localizePath?: boolean;
};
}): string {
const shouldLocalizePath: boolean =
//
options.localizePath ?? i18n.currentLocale !== i18n.defaultLocale;

if (!shouldLocalizePath) {
return originalPath;
}
// FS paths need special care, for Windows support
if (pathType === 'fs') {
return path.join(originalPath, i18n.currentLocale);
}
// Url paths; add a trailing slash so it's a valid base URL
return normalizeUrl([originalPath, i18n.currentLocale, '/']);
}
1 change: 1 addition & 0 deletions packages/docusaurus-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export {
mergeTranslations,
updateTranslationFileMessages,
getPluginI18nPath,
localizePath,
} from './i18nUtils';
export {
removeSuffix,
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus/src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import CleanWebpackPlugin from '../webpack/plugins/CleanWebpackPlugin';
import {loadI18n} from '../server/i18n';
import {mapAsyncSequential} from '@docusaurus/utils';

export default async function build(
export async function build(
siteDir: string,
cliOptions: Partial<BuildCLIOptions> = {},
// When running build, we force terminate the process to prevent async
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus/src/commands/clear.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async function removePath(entry: {path: string; description: string}) {
}
}

export default async function clear(siteDir: string): Promise<unknown> {
export async function clear(siteDir: string): Promise<unknown> {
const generatedFolder = {
path: path.join(siteDir, GENERATED_FILES_DIR_NAME),
description: 'generated folder',
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus/src/commands/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import shell from 'shelljs';
import logger from '@docusaurus/logger';
import {hasSSHProtocol, buildSshUrl, buildHttpsUrl} from '@docusaurus/utils';
import {loadContext} from '../server';
import build from './build';
import {build} from './build';
import type {BuildCLIOptions} from '@docusaurus/types';
import path from 'path';
import os from 'os';
Expand All @@ -34,7 +34,7 @@ function shellExecLog(cmd: string) {
}
}

export default async function deploy(
export async function deploy(
siteDir: string,
cliOptions: Partial<BuildCLIOptions> = {},
): Promise<void> {
Expand Down
9 changes: 4 additions & 5 deletions packages/docusaurus/src/commands/external.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@
*/

import type {CommanderStatic} from 'commander';
import {loadContext, loadPluginConfigs} from '../server';
import initPlugins from '../server/plugins/init';
import {loadContext} from '../server';
import {initPlugins} from '../server/plugins/init';

export default async function externalCommand(
export async function externalCommand(
cli: CommanderStatic,
siteDir: string,
): Promise<void> {
const context = await loadContext(siteDir);
const pluginConfigs = await loadPluginConfigs(context);
const plugins = await initPlugins({pluginConfigs, context});
const plugins = await initPlugins(context);

// Plugin Lifecycle - extendCli.
plugins.forEach((plugin) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ import serveHandler from 'serve-handler';
import logger from '@docusaurus/logger';
import path from 'path';
import {loadSiteConfig} from '../server';
import build from './build';
import {build} from './build';
import {getCLIOptionHost, getCLIOptionPort} from './commandUtils';
import type {ServeCLIOptions} from '@docusaurus/types';

export default async function serve(
export async function serve(
siteDir: string,
cliOptions: ServeCLIOptions,
): Promise<void> {
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus/src/commands/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
import {getCLIOptionHost, getCLIOptionPort} from './commandUtils';
import {getTranslationsLocaleDirPath} from '../server/translations/translations';

export default async function start(
export async function start(
siteDir: string,
cliOptions: Partial<StartCLIOptions>,
): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import path from 'path';
import fs from 'fs-extra';
import {ThemePath, createTempSiteDir, Components} from './testUtils';
import tree from 'tree-node-cli';
import swizzle from '../index';
import {swizzle} from '../index';
import {escapePath, Globby, posixPath} from '@docusaurus/utils';

const FixtureThemeName = 'fixture-theme-name';
Expand Down
12 changes: 4 additions & 8 deletions packages/docusaurus/src/commands/swizzle/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,17 @@
* LICENSE file in the root directory of this source tree.
*/

import {loadContext, loadPluginConfigs} from '../../server';
import initPlugins, {normalizePluginConfigs} from '../../server/plugins/init';
import type {InitializedPlugin} from '@docusaurus/types';
import {loadContext} from '../../server';
import {initPlugins, normalizePluginConfigs} from '../../server/plugins/init';
import {loadPluginConfigs} from '../../server/plugins/configs';
import type {SwizzleContext} from './common';

export async function initSwizzleContext(
siteDir: string,
): Promise<SwizzleContext> {
const context = await loadContext(siteDir);

const plugins = await initPlugins(context);
const pluginConfigs = await loadPluginConfigs(context);
const plugins: InitializedPlugin[] = await initPlugins({
pluginConfigs,
context,
});

const pluginsNormalized = await normalizePluginConfigs(
pluginConfigs,
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus/src/commands/swizzle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ If you want to swizzle it, use the code=${'--danger'} flag, or confirm that you
return undefined;
}

export default async function swizzle(
export async function swizzle(
siteDir: string,
themeNameParam: string | undefined,
componentNameParam: string | undefined,
Expand Down
12 changes: 4 additions & 8 deletions packages/docusaurus/src/commands/writeHeadingIds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import {
writeMarkdownHeadingId,
type WriteHeadingIDOptions,
} from '@docusaurus/utils';
import {loadContext, loadPluginConfigs} from '../server';
import initPlugins from '../server/plugins/init';
import {loadContext} from '../server';
import {initPlugins} from '../server/plugins/init';
import {safeGlobby} from '../server/utils';

async function transformMarkdownFile(
Expand All @@ -36,15 +36,11 @@ async function transformMarkdownFile(
*/
async function getPathsToWatch(siteDir: string): Promise<string[]> {
const context = await loadContext(siteDir);
const pluginConfigs = await loadPluginConfigs(context);
const plugins = await initPlugins({
pluginConfigs,
context,
});
const plugins = await initPlugins(context);
return plugins.flatMap((plugin) => plugin?.getPathsToWatch?.() ?? []);
}

export default async function writeHeadingIds(
export async function writeHeadingIds(
siteDir: string,
files?: string[],
options?: WriteHeadingIDOptions,
Expand Down
12 changes: 4 additions & 8 deletions packages/docusaurus/src/commands/writeTranslations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

import type {ConfigOptions, InitializedPlugin} from '@docusaurus/types';
import path from 'path';
import {loadContext, loadPluginConfigs} from '../server';
import initPlugins from '../server/plugins/init';
import {loadContext} from '../server';
import {initPlugins} from '../server/plugins/init';

import {
writePluginTranslations,
Expand Down Expand Up @@ -72,19 +72,15 @@ async function writePluginTranslationFiles({
}
}

export default async function writeTranslations(
export async function writeTranslations(
siteDir: string,
options: WriteTranslationsOptions & ConfigOptions & {locale?: string},
): Promise<void> {
const context = await loadContext(siteDir, {
customConfigFilePath: options.config,
locale: options.locale,
});
const pluginConfigs = await loadPluginConfigs(context);
const plugins = await initPlugins({
pluginConfigs,
context,
});
const plugins = await initPlugins(context);

const locale = options.locale ?? context.i18n.defaultLocale;

Expand Down
30 changes: 9 additions & 21 deletions packages/docusaurus/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,12 @@
* LICENSE file in the root directory of this source tree.
*/

import build from './commands/build';
import clear from './commands/clear';
import deploy from './commands/deploy';
import externalCommand from './commands/external';
import serve from './commands/serve';
import start from './commands/start';
import swizzle from './commands/swizzle';
import writeHeadingIds from './commands/writeHeadingIds';
import writeTranslations from './commands/writeTranslations';

export {
build,
clear,
deploy,
externalCommand,
serve,
start,
swizzle,
writeHeadingIds,
writeTranslations,
};
export {build} from './commands/build';
export {clear} from './commands/clear';
export {deploy} from './commands/deploy';
export {externalCommand} from './commands/external';
export {serve} from './commands/serve';
export {start} from './commands/start';
export {swizzle} from './commands/swizzle';
export {writeHeadingIds} from './commands/writeHeadingIds';
export {writeTranslations} from './commands/writeTranslations';
Loading