Skip to content

Commit

Permalink
Merge pull request #23791 from storybookjs/shaun/new-add-cmd
Browse files Browse the repository at this point in the history
CLI: Update postinstall to look for addon script
  • Loading branch information
shilman committed Aug 11, 2023
2 parents af906e2 + b157376 commit 19d26cc
Showing 1 changed file with 16 additions and 43 deletions.
59 changes: 16 additions & 43 deletions code/lib/cli/src/add.ts
@@ -1,11 +1,6 @@
import path from 'path';
import fs from 'fs';
import { sync as spawnSync } from 'cross-spawn';

import { getStorybookInfo } from '@storybook/core-common';
import { readConfig, writeConfig } from '@storybook/csf-tools';

import { commandLog } from './helpers';
import {
JsPackageManagerFactory,
useNpmWarning,
Expand All @@ -15,43 +10,21 @@ import { getStorybookVersion } from './utils';

const logger = console;

const LEGACY_CONFIGS = ['addons', 'config', 'presets'];

const postinstallAddon = async (addonName: string, isOfficialAddon: boolean) => {
let skipMsg = null;
if (!isOfficialAddon) {
skipMsg = 'unofficial addon';
} else if (!fs.existsSync('.storybook')) {
skipMsg = 'no .storybook config';
} else {
skipMsg = 'no codmods found';
LEGACY_CONFIGS.forEach((config) => {
try {
const codemod = require.resolve(
// @ts-expect-error (it is broken)
`${getPackageName(addonName, isOfficialAddon)}/postinstall/${config}.js`
);
commandLog(`Running postinstall script for ${addonName}`)();
let configFile = path.join('.storybook', `${config}.ts`);
if (!fs.existsSync(configFile)) {
configFile = path.join('.storybook', `${config}.js`);
if (!fs.existsSync(configFile)) {
fs.writeFileSync(configFile, '', 'utf8');
}
}
spawnSync('npx', ['jscodeshift', '-t', codemod, configFile], {
stdio: 'inherit',
shell: true,
});
skipMsg = null;
} catch (err) {
// resolve failed, skip
}
});
}
const postinstallAddon = async (addonName: string) => {
try {
const modulePath = require.resolve(`${addonName}/postinstall`, { paths: [process.cwd()] });
// eslint-disable-next-line import/no-dynamic-require, global-require
const postinstall = require(modulePath);

if (skipMsg) {
commandLog(`Skipping postinstall for ${addonName}, ${skipMsg}`)();
try {
logger.log(`Running postinstall script for ${addonName}`);
await postinstall();
} catch (e) {
logger.error(`Error running postinstall script for ${addonName}`);
logger.error(e);
}
} catch (e) {
// no postinstall script
}
};

Expand Down Expand Up @@ -109,7 +82,7 @@ export async function add(
main.appendValueToArray(['addons'], addonName);
await writeConfig(main);

if (!options.skipPostinstall) {
await postinstallAddon(addon, isStorybookAddon);
if (!options.skipPostinstall && isStorybookAddon) {
await postinstallAddon(addonName);
}
}

0 comments on commit 19d26cc

Please sign in to comment.