Skip to content

Commit

Permalink
Update postinstall to look for addon script
Browse files Browse the repository at this point in the history
  • Loading branch information
Shaun Lloyd committed Aug 10, 2023
1 parent 354d1ba commit d89dee3
Showing 1 changed file with 18 additions and 43 deletions.
61 changes: 18 additions & 43 deletions code/lib/cli/src/add.ts
Original file line number Diff line number Diff line change
@@ -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,23 @@ 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
logger.log(`No postinstall script for ${addonName}`);
logger.log(e);
}
};

Expand Down Expand Up @@ -109,7 +84,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 d89dee3

Please sign in to comment.