Skip to content

Commit

Permalink
Merge pull request #24229 from storybookjs/norbert/sb-add-no-duplicat…
Browse files Browse the repository at this point in the history
…e-entries

CLI: Fix `sb add` adding duplicative entries
(cherry picked from commit 4a29bbb)
  • Loading branch information
yannbf authored and storybook-bot committed Sep 20, 2023
1 parent 10bb99c commit da4c170
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
28 changes: 26 additions & 2 deletions code/lib/cli/src/add.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { getStorybookInfo } from '@storybook/core-common';
import { getStorybookInfo, serverRequire } from '@storybook/core-common';
import { readConfig, writeConfig } from '@storybook/csf-tools';
import { isAbsolute, join } from 'path';
import SemVer from 'semver';
import dedent from 'ts-dedent';

import {
JsPackageManagerFactory,
Expand Down Expand Up @@ -38,6 +40,21 @@ const getVersionSpecifier = (addon: string) => {
return groups ? [groups[1], groups[2]] : [addon, undefined];
};

const requireMain = (configDir: string) => {
const absoluteConfigDir = isAbsolute(configDir) ? configDir : join(process.cwd(), configDir);
const mainFile = join(absoluteConfigDir, 'main');

return serverRequire(mainFile) ?? {};
};

const checkInstalled = (addonName: string, main: any) => {
const existingAddon = main.addons?.find((entry: string | { name: string }) => {
const name = typeof entry === 'string' ? entry : entry.name;
return name?.endsWith(addonName);
});
return !!existingAddon;
};

/**
* Install the given addon package and add it to main.js
*
Expand All @@ -60,9 +77,16 @@ export async function add(
}
const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr });
const packageJson = await packageManager.retrievePackageJson();
const { mainConfig, configDir } = getStorybookInfo(packageJson);

if (checkInstalled(addon, requireMain(configDir))) {
throw new Error(dedent`
Addon ${addon} is already installed; we skipped adding it to your ${mainConfig}.
`);
}

const [addonName, versionSpecifier] = getVersionSpecifier(addon);

const { mainConfig } = getStorybookInfo(packageJson);
if (!mainConfig) {
logger.error('Unable to find storybook main.js config');
return;
Expand Down
2 changes: 1 addition & 1 deletion code/lib/core-common/src/utils/get-storybook-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ const getConfigInfo = (packageJson: PackageJson, configDir?: string) => {
}

return {
configDir,
configDir: storybookConfigDir,
mainConfig: findConfigFile('main', storybookConfigDir),
previewConfig: findConfigFile('preview', storybookConfigDir),
managerConfig: findConfigFile('manager', storybookConfigDir),
Expand Down

0 comments on commit da4c170

Please sign in to comment.