Skip to content

Commit

Permalink
feat(v2): Collect plugin versions to allow them to be inspected in de…
Browse files Browse the repository at this point in the history
…bug plugin (#3050)
  • Loading branch information
SamChou19815 authored Jul 13, 2020
1 parent a384986 commit 3ebe245
Show file tree
Hide file tree
Showing 11 changed files with 193 additions and 13 deletions.
23 changes: 23 additions & 0 deletions packages/docusaurus-module-type-aliases/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,29 @@ declare module '@generated/routesChunkNames' {
export default routesChunkNames;
}

declare module '@generated/site-metadata' {
/**
* - `type: 'package'`, plugin is in a different package.
* - `type: 'project'`, plugin is in the same docusaurus project.
* - `type: 'local'`, none of plugin's ancestor directory contains any package.json.
* - `type: 'synthetic'`, docusaurus generated internal plugin.
*/
export type PluginVersionInformation =
| {readonly type: 'package'; readonly version?: string}
| {readonly type: 'project'}
| {readonly type: 'local'}
| {readonly type: 'synthetic'};

export type DocusaurusSiteMetadata = {
readonly docusaurusVersion: string;
readonly siteVersion?: string;
readonly pluginVersions: Record<string, PluginVersionInformation>;
};

const siteMetadata: DocusaurusSiteMetadata;
export default siteMetadata;
}

declare module '@theme/*';

declare module '@theme-original/*';
Expand Down
26 changes: 24 additions & 2 deletions packages/docusaurus-plugin-debug/src/theme/Debug/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,36 @@ import Layout from '@theme/Layout';

import registry from '@generated/registry';
import routes from '@generated/routes';
import siteMetadata from '@generated/site-metadata';

import styles from './styles.module.css';

function Debug() {
return (
<Layout permalink="__docusaurus/debug" title="Debug">
<main className={styles.Container}>
<section>
<section className={styles.Section}>
<h2>Site Metadata</h2>
<div>Docusaurus Version: {siteMetadata.docusaurusVersion}</div>
<div>
Site Version: {siteMetadata.siteVersion || 'No version specified'}
</div>
<h3>Plugins and themes:</h3>
<ul>
{Object.entries(siteMetadata.pluginVersions).map(
([name, versionInformation]) => (
<li key={name}>
<div>Name: {name}</div>
<div>Type: {versionInformation.type}</div>
{versionInformation.version && (
<div>Version: {versionInformation.version}</div>
)}
</li>
),
)}
</ul>
</section>
<section className={styles.Section}>
<h2>Registry</h2>
<ul>
{Object.values(registry).map(([, aliasedPath, resolved]) => (
Expand All @@ -28,7 +50,7 @@ function Debug() {
))}
</ul>
</section>
<section>
<section className={styles.Section}>
<h2>Routes</h2>
<ul>
{routes.map(({path, exact}) => (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,11 @@

.Container {
display: flex;
flex-wrap: wrap;
justify-content: center;
margin: 1em;
}

.Section {
width: 500px;
}
25 changes: 24 additions & 1 deletion packages/docusaurus/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
*/

import {generate} from '@docusaurus/utils';
import path from 'path';
import {DocusaurusSiteMetadata} from '@generated/site-metadata';
import path, {join} from 'path';
import {
BUILD_DIR_NAME,
CONFIG_FILE_NAME,
Expand All @@ -26,6 +27,7 @@ import {
Props,
} from '@docusaurus/types';
import {loadHtmlTags} from './html-tags';
import {getPackageJsonVersion} from './versions';

export function loadContext(
siteDir: string,
Expand Down Expand Up @@ -96,6 +98,7 @@ export async function load(
const {stylesheets = [], scripts = []} = siteConfig;
plugins.push({
name: 'docusaurus-bootstrap-plugin',
version: {type: 'synthetic'},
configureWebpack: () => ({
resolve: {
alias,
Expand Down Expand Up @@ -178,12 +181,32 @@ ${Object.keys(registry)

const genRoutes = generate(generatedFilesDir, 'routes.js', routesConfig);

// Version metadata.
const siteMetadata: DocusaurusSiteMetadata = {
docusaurusVersion: getPackageJsonVersion(
join(__dirname, '../../package.json'),
)!,
siteVersion: getPackageJsonVersion(join(siteDir, 'package.json')),
pluginVersions: {},
};
plugins
.filter(({version: {type}}) => type !== 'synthetic')
.forEach(({name, version}) => {
siteMetadata.pluginVersions[name] = version;
});
const genSiteMetadata = generate(
generatedFilesDir,
'site-metadata.json',
JSON.stringify(siteMetadata, null, 2),
);

await Promise.all([
genClientModules,
genSiteConfig,
genRegistry,
genRoutesChunkNames,
genRoutes,
genSiteMetadata,
]);

const props: Props = {
Expand Down
10 changes: 6 additions & 4 deletions packages/docusaurus/src/server/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ import fs from 'fs-extra';
import path from 'path';
import {
LoadContext,
Plugin,
PluginConfig,
PluginContentLoadedActions,
RouteConfig,
} from '@docusaurus/types';
import initPlugins from './init';
import initPlugins, {PluginWithVersionInformation} from './init';

export function sortConfig(routeConfigs: RouteConfig[]): void {
// Sort the route config. This ensures that route with nested
Expand Down Expand Up @@ -53,11 +52,14 @@ export async function loadPlugins({
pluginConfigs: PluginConfig[];
context: LoadContext;
}): Promise<{
plugins: Plugin<unknown>[];
plugins: PluginWithVersionInformation[];
pluginsRouteConfigs: RouteConfig[];
}> {
// 1. Plugin Lifecycle - Initialization/Constructor.
const plugins: Plugin<unknown>[] = initPlugins({pluginConfigs, context});
const plugins: PluginWithVersionInformation[] = initPlugins({
pluginConfigs,
context,
});

// 2. Plugin Lifecycle - loadContent.
// Currently plugins run lifecycle methods in parallel and are not order-dependent.
Expand Down
18 changes: 12 additions & 6 deletions packages/docusaurus/src/server/plugins/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ import {
PluginConfig,
ValidationSchema,
} from '@docusaurus/types';
import {PluginVersionInformation} from '@generated/site-metadata';
import {CONFIG_FILE_NAME} from '../../constants';
import {getPluginVersion} from '../versions';

function validate<T>(schema: ValidationSchema<T>, options: Partial<T>) {
const {error, value} = schema.validate(options, {
Expand All @@ -37,21 +39,25 @@ function validateAndStrip<T>(schema: ValidationSchema<T>, options: Partial<T>) {
return value;
}

export type PluginWithVersionInformation = Plugin<unknown> & {
readonly version: PluginVersionInformation;
};

export default function initPlugins({
pluginConfigs,
context,
}: {
pluginConfigs: PluginConfig[];
context: LoadContext;
}): Plugin<unknown>[] {
}): PluginWithVersionInformation[] {
// We need to resolve plugins from the perspective of the siteDir, since the siteDir's package.json
// declares the dependency on these plugins.
// We need to fallback to createRequireFromPath since createRequire is only available in node v12.
// See: https://nodejs.org/api/modules.html#modules_module_createrequire_filename
const createRequire = Module.createRequire || Module.createRequireFromPath;
const pluginRequire = createRequire(join(context.siteDir, CONFIG_FILE_NAME));

const plugins: Plugin<unknown>[] = pluginConfigs
const plugins: PluginWithVersionInformation[] = pluginConfigs
.map((pluginItem) => {
let pluginModuleImport: string | undefined;
let pluginOptions = {};
Expand All @@ -72,9 +78,9 @@ export default function initPlugins({

// The pluginModuleImport value is any valid
// module identifier - npm package or locally-resolved path.
const pluginModule: any = importFresh(
pluginRequire.resolve(pluginModuleImport),
);
const pluginPath = pluginRequire.resolve(pluginModuleImport);
const pluginModule: any = importFresh(pluginPath);
const pluginVersion = getPluginVersion(pluginPath, context.siteDir);

const plugin = pluginModule.default || pluginModule;

Expand Down Expand Up @@ -106,7 +112,7 @@ export default function initPlugins({
...normalizedThemeConfig,
};
}
return plugin(context, pluginOptions);
return {...plugin(context, pluginOptions), version: pluginVersion};
})
.filter(Boolean);
return plugins;
Expand Down
11 changes: 11 additions & 0 deletions packages/docusaurus/src/server/types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* 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.
*/

// triple slash is important to keep,
// see https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html
// eslint-disable-next-line
/// <reference types="@docusaurus/module-type-aliases" />
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"version": "random-version"
}
35 changes: 35 additions & 0 deletions packages/docusaurus/src/server/versions/__tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* 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.
*/

import {getPluginVersion} from '..';
import {join} from 'path';

describe('getPluginVersion', () => {
it('Can detect external packages plugins versions of correctly.', () => {
expect(
getPluginVersion(
join(__dirname, '..', '__fixtures__', 'dummy-plugin.js'),
// Make the plugin appear external.
join(__dirname, '..', '..', '..', '..', '..', '..', 'website'),
),
).toEqual({type: 'package', version: 'random-version'});
});

it('Can detect project plugins versions correctly.', () => {
expect(
getPluginVersion(
join(__dirname, '..', '__fixtures__', 'dummy-plugin.js'),
// Make the plugin appear project local.
join(__dirname, '..', '__fixtures__'),
),
).toEqual({type: 'project'});
});

it('Can detect local packages versions correctly.', () => {
expect(getPluginVersion('/', '/')).toEqual({type: 'local'});
});
});
49 changes: 49 additions & 0 deletions packages/docusaurus/src/server/versions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* 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.
*/

import {PluginVersionInformation} from '@generated/site-metadata';
import {existsSync, lstatSync} from 'fs-extra';
import {dirname, join} from 'path';

export function getPackageJsonVersion(
packageJsonPath: string,
): string | undefined {
if (existsSync(packageJsonPath)) {
// eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-dynamic-require, global-require
const {version} = require(packageJsonPath);
return typeof version === 'string' ? version : undefined;
}
return undefined;
}

export function getPluginVersion(
pluginPath: string,
siteDir: string,
): PluginVersionInformation {
let potentialPluginPackageJsonDirectory = dirname(pluginPath);
while (potentialPluginPackageJsonDirectory !== '/') {
const packageJsonPath = join(
potentialPluginPackageJsonDirectory,
'package.json',
);
if (existsSync(packageJsonPath) && lstatSync(packageJsonPath).isFile()) {
if (potentialPluginPackageJsonDirectory === siteDir) {
// If the plugin belongs to the same docusaurus project, we classify it as local plugin.
return {type: 'project'};
}
return {
type: 'package',
version: getPackageJsonVersion(packageJsonPath),
};
}
potentialPluginPackageJsonDirectory = dirname(
potentialPluginPackageJsonDirectory,
);
}
// In rare cases where a plugin is a path where no parent directory contains package.json, we can only classify it as local.
return {type: 'local'};
}

0 comments on commit 3ebe245

Please sign in to comment.