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

CLI: Add upgrade telemetry details #20064

Merged
merged 3 commits into from
Dec 3, 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
26 changes: 24 additions & 2 deletions code/lib/cli/src/automigrate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,44 @@ import { fixes } from './fixes';

const logger = console;

type FixId = string;

interface FixOptions {
fixId?: string;
fixId?: FixId;
yes?: boolean;
dryRun?: boolean;
useNpm?: boolean;
force?: PackageManagerName;
}

enum FixStatus {
CHECK_FAILED = 'check_failed',
UNNECESSARY = 'unnecessary',
SKIPPED = 'skipped',
SUCCEEDED = 'succeeded',
FAILED = 'failed',
}

export const automigrate = async ({ fixId, dryRun, yes, useNpm, force }: FixOptions = {}) => {
const packageManager = JsPackageManagerFactory.getPackageManager({ useNpm, force });
const filtered = fixId ? fixes.filter((f) => f.id === fixId) : fixes;

logger.info('🔎 checking possible migrations..');
const fixResults = {} as Record<FixId, FixStatus>;

for (let i = 0; i < filtered.length; i += 1) {
const f = fixes[i] as Fix;
let result;
let fixStatus;
try {
result = await f.check({ packageManager });
} catch (e) {
fixStatus = FixStatus.CHECK_FAILED;
logger.info(`failed to check fix: ${f.id}`);
}
if (result) {
if (!result) {
fixStatus = FixStatus.UNNECESSARY;
} else {
logger.info(`🔎 found a '${chalk.cyan(f.id)}' migration:`);
logger.info();
const message = f.prompt(result);
Expand All @@ -58,22 +73,29 @@ export const automigrate = async ({ fixId, dryRun, yes, useNpm, force }: FixOpti
try {
await f.run({ result, packageManager, dryRun });
logger.info(`✅ ran ${chalk.cyan(f.id)} migration`);
fixStatus = FixStatus.SUCCEEDED;
} catch (error) {
fixStatus = FixStatus.FAILED;
logger.info(`❌ error when running ${chalk.cyan(f.id)} migration:`);
logger.info(error);
logger.info();
}
} else {
fixStatus = FixStatus.SKIPPED;
logger.info(`Skipping the ${chalk.cyan(f.id)} migration.`);
logger.info();
logger.info(
`If you change your mind, run '${chalk.cyan('npx storybook@next automigrate')}'`
);
}
}

fixResults[f.id] = fixStatus;
}

logger.info();
logger.info('✅ migration check successfully ran');
logger.info();

return fixResults;
};
8 changes: 4 additions & 4 deletions code/lib/cli/src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,12 @@ program
.option('-n --dry-run', 'Only check for fixes, do not actually run them')
.option('--package-manager <npm|pnpm|yarn1|yarn2>', 'Force package manager')
.option('-N --use-npm', 'Use npm as package manager (deprecated)')
.action((fixId, options) =>
automigrate({ fixId, ...options }).catch((e) => {
.action(async (fixId, options) => {
await automigrate({ fixId, ...options }).catch((e) => {
logger.error(e);
process.exit(1);
})
);
});
});

program
.command('dev')
Expand Down
15 changes: 10 additions & 5 deletions code/lib/cli/src/upgrade.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { sync as spawnSync } from 'cross-spawn';
import { telemetry } from '@storybook/telemetry';
import { telemetry, getStorybookCoreVersion } from '@storybook/telemetry';
import semver from 'semver';
import { logger } from '@storybook/node-logger';
import { withTelemetry } from '@storybook/core-server';
Expand Down Expand Up @@ -159,10 +159,9 @@ export const doUpgrade = async ({
}
const packageManager = JsPackageManagerFactory.getPackageManager({ useNpm, force: pkgMgr });

const beforeVersion = await getStorybookCoreVersion();

commandLog(`Checking for latest versions of '@storybook/*' packages`);
if (!options.disableTelemetry) {
telemetry('upgrade', { prerelease });
}

let flags = [];
if (!dryRun) flags.push('--upgrade');
Expand All @@ -180,9 +179,15 @@ export const doUpgrade = async ({
packageManager.installDependencies();
}

let automigrationResults;
if (!skipCheck) {
checkVersionConsistency();
await automigrate({ dryRun, yes, useNpm, force: pkgMgr });
automigrationResults = await automigrate({ dryRun, yes, useNpm, force: pkgMgr });
}

if (!options.disableTelemetry) {
const afterVersion = await getStorybookCoreVersion();
telemetry('upgrade', { prerelease, automigrationResults, beforeVersion, afterVersion });
}
};

Expand Down
2 changes: 2 additions & 0 deletions code/lib/telemetry/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export * from './storybook-metadata';

export * from './types';

export { getStorybookCoreVersion } from './package-json';

export const telemetry = async (
eventType: EventType,
payload: Payload = {},
Expand Down
15 changes: 13 additions & 2 deletions code/lib/telemetry/src/package-json.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { readJson } from 'fs-extra';
import path from 'path';

import type { Dependency } from './types';
Expand All @@ -20,7 +21,17 @@ export const getActualPackageVersion = async (packageName: string) => {
};

export const getActualPackageJson = async (packageName: string) => {
// eslint-disable-next-line import/no-dynamic-require,global-require
const packageJson = require(path.join(packageName, 'package.json'));
const resolvedPackageJson = require.resolve(path.join(packageName, 'package.json'), {
paths: [process.cwd()],
});
const packageJson = await readJson(resolvedPackageJson);
return packageJson;
};

// Note that this probably doesn't work in PNPM mode
export const getStorybookCoreVersion = async () => {
const coreVersions = await Promise.all(
['@storybook/core-common', '@storybook/core-server'].map(getActualPackageVersion)
);
return coreVersions.find((v) => v.version)?.version;
};
Comment on lines +31 to +37
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we reuse the code we use to check all SB versions are in sync for this (i.e. check all direct dependencies that are from the monorepo) rather than just trying a couple of packages that won't work in pnpm?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That code needs a lot of work. I'll leave this for now, but we should definitely invest in making this area more robust.