Skip to content

Commit

Permalink
Use invariant for error handling instead
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperpeulen committed Aug 16, 2023
1 parent 48eb7d3 commit e84f7dc
Show file tree
Hide file tree
Showing 8 changed files with 31 additions and 24 deletions.
1 change: 1 addition & 0 deletions scripts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@
"slash": "^3.0.0",
"sort-package-json": "^2.0.0",
"tempy": "^1.0.0",
"tiny-invariant": "^1.3.1",
"trash": "^7.0.0",
"ts-dedent": "^2.0.0",
"ts-node": "^10.9.1",
Expand Down
8 changes: 5 additions & 3 deletions scripts/release/pick-patches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import ora from 'ora';
import { setOutput } from '@actions/core';
import { git } from './utils/git-client';
import { getUnpickedPRs } from './utils/github-client';
import { getErrorMessage } from '../type-utils/errorHandling';
import invariant from 'tiny-invariant';

program.name('pick-patches').description('Cherry pick patch PRs back to main');

Expand Down Expand Up @@ -58,15 +58,17 @@ export const run = async (_: unknown) => {
await git.raw(['cherry-pick', '-m', '1', '--keep-redundant-commits', '-x', pr.mergeCommit]);
prSpinner.succeed(`Picked: ${formatPR(pr)}`);
} catch (pickError) {
invariant(pickError instanceof Error);
prSpinner.fail(`Failed to automatically pick: ${formatPR(pr)}`);
logger.error(getErrorMessage(pickError));
logger.error(pickError.message);
const abort = ora(`Aborting cherry pick for merge commit: ${pr.mergeCommit}`).start();
try {
await git.raw(['cherry-pick', '--abort']);
abort.stop();
} catch (abortError) {
invariant(abortError instanceof Error);
abort.warn(`Failed to abort cherry pick (${pr.mergeCommit})`);
logger.error(getErrorMessage(pickError));
logger.error(abortError.message);
}
failedCherryPicks.push(pr.mergeCommit);
prSpinner.info(
Expand Down
21 changes: 10 additions & 11 deletions scripts/sandbox/utils/git.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import fetch from 'node-fetch';
import invariant from 'tiny-invariant';

import { execaCommand } from '../../utils/exec';
// eslint-disable-next-line import/no-cycle
import { logger } from '../publish';
import { getErrorMessage } from '../../type-utils/errorHandling';

const { version: storybookVersion } = require('../../../code/package.json');

Expand All @@ -28,14 +29,12 @@ const getTheLastCommitHashThatUpdatedTheSandboxRepo = async (branch: string) =>
`Could not find the last commit hash in the following commit message: "${latestCommitMessage}".\nDid someone manually push to the sandboxes repo?`
);
}

return lastCommitHash;
} catch (error) {
if (!getErrorMessage(error).includes('Did someone manually push to the sandboxes repo')) {
invariant(error instanceof Error);
if (!error.message.includes('Did someone manually push to the sandboxes repo')) {
logger.error(
`⚠️ Error getting latest commit message of ${owner}/${repo} on branch ${branch}: ${getErrorMessage(
error
)}`
`⚠️ Error getting latest commit message of ${owner}/${repo} on branch ${branch}: ${error.message}`
);
}

Expand Down Expand Up @@ -87,10 +86,9 @@ export async function commitAllToGit({ cwd, branch }: { cwd: string; branch: str
].join('\n');
gitCommitCommand = `git commit -m "${commitTitle}" -m "${commitBody}"`;
} catch (err) {
invariant(err instanceof Error);
logger.log(
`⚠️ Falling back to a simpler commit message because of an error while trying to get the previous commit hash: ${getErrorMessage(
err
)}`
`⚠️ Falling back to a simpler commit message because of an error while trying to get the previous commit hash: ${err.message}`
);
gitCommitCommand = `git commit -m "${storybookVersion} - ${new Date().toDateString()} - ${currentCommitHash}"`;
}
Expand All @@ -100,12 +98,13 @@ export async function commitAllToGit({ cwd, branch }: { cwd: string; branch: str
cwd,
});
} catch (e) {
if (!getErrorMessage(e).includes('nothing to commit')) {
invariant(e instanceof Error);
if (!e.message.includes('nothing to commit')) {
logger.log(
`🤷 Git found no changes between previous versions so there is nothing to commit. Skipping publish!`
);
} else {
logger.error(`🤯 Something went wrong while committing to git: ${getErrorMessage(e)}`);
logger.error(`🤯 Something went wrong while committing to git: ${e.message}`);
}
}
}
5 changes: 3 additions & 2 deletions scripts/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { join, resolve } from 'path';
import { prompt } from 'prompts';
import { dedent } from 'ts-dedent';

import { getErrorMessage } from './type-utils/errorHandling';
import { CODE_DIRECTORY, JUNIT_DIRECTORY, SANDBOX_DIRECTORY } from './utils/constants';
import type { OptionValues } from './utils/options';
import { createOptions, getCommand, getOptionsOrPrompt } from './utils/options';
Expand Down Expand Up @@ -36,6 +35,7 @@ import {
} from '../code/lib/cli/src/sandbox-templates';

import { version } from '../code/package.json';
import invariant from 'tiny-invariant';

const sandboxDir = process.env.SANDBOX_ROOT || SANDBOX_DIRECTORY;

Expand Down Expand Up @@ -473,10 +473,11 @@ async function run() {
});
if (controller) controllers.push(controller);
} catch (err) {
invariant(err instanceof Error);
logger.error(`Error running task ${getTaskKey(task)}:`);
// If it is the last task, we don't need to log the full trace
if (task === finalTask) {
logger.error(getErrorMessage(err));
logger.error(err.message);
} else {
logger.error(err);
}
Expand Down
5 changes: 3 additions & 2 deletions scripts/ts-to-ts49.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as recast from 'recast';
import type Babel from '@babel/core';
import type { File } from '@babel/types';
import * as t from '@babel/types';
import { getErrorMessage } from './type-utils/errorHandling';
import invariant from 'tiny-invariant';

const files = glob.sync('**/*.ts.mdx', {
absolute: true,
Expand Down Expand Up @@ -75,7 +75,8 @@ for (const [, file] of files.entries()) {
console.log('changed', file);
}
} catch (e) {
console.error(getErrorMessage(e));
invariant(e instanceof Error);
console.error(e.message);
}
}

Expand Down
5 changes: 0 additions & 5 deletions scripts/type-utils/errorHandling.ts

This file was deleted.

2 changes: 1 addition & 1 deletion scripts/utils/exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const exec = async (
}
}
} catch (err) {
if (!(err as any)?.killed) {
if (!(typeof err === 'object' && 'killed' in err && err.killed)) {
logger.error(chalk.red(`An error occurred while executing: \`${command}\``));
logger.log(`${errorMessage}\n`);
}
Expand Down
8 changes: 8 additions & 0 deletions scripts/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3033,6 +3033,7 @@ __metadata:
slash: ^3.0.0
sort-package-json: ^2.0.0
tempy: ^1.0.0
tiny-invariant: ^1.3.1
trash: ^7.0.0
ts-dedent: ^2.0.0
ts-loader: ^9.4.2
Expand Down Expand Up @@ -15617,6 +15618,13 @@ __metadata:
languageName: node
linkType: hard

"tiny-invariant@npm:^1.3.1":
version: 1.3.1
resolution: "tiny-invariant@npm:1.3.1"
checksum: 5b87c1d52847d9452b60d0dcb77011b459044e0361ca8253bfe7b43d6288106e12af926adb709a6fc28900e3864349b91dad9a4ac93c39aa15f360b26c2ff4db
languageName: node
linkType: hard

"tmp@npm:~0.2.1":
version: 0.2.1
resolution: "tmp@npm:0.2.1"
Expand Down

0 comments on commit e84f7dc

Please sign in to comment.