Skip to content

Commit

Permalink
Merge pull request #1057 from chromaui/cody/cap-2222-enable-unicornno…
Browse files Browse the repository at this point in the history
…-null

Enable `unicorn/no-null` ESLint rule
  • Loading branch information
codykaup authored Sep 27, 2024
2 parents cce85f1 + 3d61a79 commit 38a7b49
Show file tree
Hide file tree
Showing 29 changed files with 46 additions and 51 deletions.
4 changes: 2 additions & 2 deletions bin-src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const addChromaticScriptToPackageJson = async ({ packageJson, packagePath
}
};

export const createChromaticConfigFile = async ({ configFile, buildScriptName = null }) => {
export const createChromaticConfigFile = async ({ configFile, buildScriptName = undefined }) => {
await writeFile(configFile, {
...(buildScriptName && {
buildScriptName,
Expand Down Expand Up @@ -148,7 +148,7 @@ export async function main(argv: string[]) {
const { path: packagePath, packageJson } = pkgInfo;
const { testFramework } = await prompts([
{
type: flags.framework ? null : 'select',
type: flags.framework ? undefined : 'select',
name: 'testFramework',
message: 'What testing framework are you using?',
choices: [
Expand Down
2 changes: 1 addition & 1 deletion bin-src/trim-stats-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export async function main([statsFile = './storybook-static/preview-stats.json']
const targetFile = statsFile.replace('.json', '.trimmed.json');
await outputFile(
targetFile,
JSON.stringify({ modules: trimmedModules }, null, 2)
JSON.stringify({ modules: trimmedModules }, undefined, 2)
.replaceAll(/{\n {10}/g, '{ ')
.replaceAll(/\n {8}}/g, ' }')
);
Expand Down
2 changes: 1 addition & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ export default [
'unicorn/no-process-exit': 'off',
'unicorn/prefer-node-protocol': 'off', // This will error our Webpack build
// TODO: remove the following lines when we are ready to enforce these rules
'unicorn/no-null': 'off',
'unicorn/prefer-module': 'off',
},
},
Expand Down Expand Up @@ -259,6 +258,7 @@ export default [
'no-secrets/no-secrets': 'warn',
'max-lines': 'warn',
'jsdoc/require-jsdoc': 'off',
'unicorn/no-null': 'off', // GraphQL returns `null` when there is no value
},
},
];
6 changes: 3 additions & 3 deletions node-src/git/findAncestorBuildWithCommit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ describe('findAncestorBuildWithCommit', () => {
makeResult([makeBuild({ commit: 'exists', uncommittedHash: 'abc123', isLocalBuild: true })])
);

expect(await findAncestorBuildWithCommit({ client }, 1, { page: 1, limit: 1 })).toBeNull();
expect(await findAncestorBuildWithCommit({ client }, 1, { page: 1, limit: 1 })).toBeUndefined();
});

it('DOES return a CI build with uncommitted changes', async () => {
Expand Down Expand Up @@ -74,7 +74,7 @@ describe('findAncestorBuildWithCommit', () => {
.mockReturnValueOnce(makeResult([makeBuild(), makeBuild()]))
.mockReturnValueOnce(makeResult([makeBuild(), makeBuild()]));

expect(await findAncestorBuildWithCommit({ client }, 1, { page: 2, limit: 3 })).toBeNull();
expect(await findAncestorBuildWithCommit({ client }, 1, { page: 2, limit: 3 })).toBeUndefined();
expect(client.runQuery).toHaveBeenCalledTimes(2);
expect(client.runQuery.mock.calls[0][1]).toMatchObject({ buildNumber: 1, skip: 0, limit: 2 });
expect(client.runQuery.mock.calls[1][1]).toMatchObject({ buildNumber: 1, skip: 2, limit: 1 });
Expand All @@ -83,7 +83,7 @@ describe('findAncestorBuildWithCommit', () => {
it('stops querying when the results run out', async () => {
client.runQuery.mockReturnValueOnce(makeResult([makeBuild()]));

expect(await findAncestorBuildWithCommit({ client }, 1, { page: 2, limit: 3 })).toBeNull();
expect(await findAncestorBuildWithCommit({ client }, 1, { page: 2, limit: 3 })).toBeUndefined();
expect(client.runQuery).toHaveBeenCalledTimes(1);
});
});
4 changes: 2 additions & 2 deletions node-src/git/findAncestorBuildWithCommit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ export async function findAncestorBuildWithCommit(

if (result) return result[0];

if (results.length < page) return null;
if (results.length < page) return;

skip += page;
}
return null;
return;
}
2 changes: 1 addition & 1 deletion node-src/git/getCommitAndBranch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ beforeEach(() => {
committerEmail: '[email protected]',
});
hasPreviousCommit.mockResolvedValue(true);
mergeQueueBranchMatch.mockResolvedValue(null);
mergeQueueBranchMatch.mockResolvedValue(undefined);
});

afterEach(() => {
Expand Down
2 changes: 1 addition & 1 deletion node-src/git/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ describe('mergeQueueBranchMatch', () => {

it('returns null if it is not a merge queue branch', async () => {
const branch = 'develop';
expect(await mergeQueueBranchMatch(branch)).toEqual(null);
expect(await mergeQueueBranchMatch(branch)).toBeUndefined();
});
});

Expand Down
2 changes: 1 addition & 1 deletion node-src/git/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,5 +302,5 @@ export async function mergeQueueBranchMatch(branch) {
const mergeQueuePattern = new RegExp(/gh-readonly-queue\/.*\/pr-(\d+)-[\da-f]{30}/);
const match = branch.match(mergeQueuePattern);

return match ? Number(match[1]) : null;
return match ? Number(match[1]) : undefined;
}
2 changes: 1 addition & 1 deletion node-src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ vi.mock('./git/git', () => ({
getRepositoryRoot: () => Promise.resolve(process.cwd()),
getUncommittedHash: () => Promise.resolve('abc123'),
getUserEmail: () => Promise.resolve('[email protected]'),
mergeQueueBranchMatch: () => Promise.resolve(null),
mergeQueueBranchMatch: () => Promise.resolve(undefined),
}));

vi.mock('./git/getParentCommits', () => ({
Expand Down
2 changes: 1 addition & 1 deletion node-src/lib/compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Context, FileDesc } from '../types';
export default async function makeZipFile(ctx: Context, files: FileDesc[]) {
const archive = archiver('zip', { zlib: { level: 9 } });
const tmp = await tempFile({ postfix: '.zip' });
const sink = createWriteStream(null, { fd: tmp.fd });
const sink = createWriteStream(undefined, { fd: tmp.fd });

return new Promise<{ path: string; size: number }>((resolve, reject) => {
sink.on('close', () => {
Expand Down
8 changes: 4 additions & 4 deletions node-src/lib/getDependentStoryFiles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ describe('getDependentStoryFiles', () => {
];
const ctx = getContext({ configDir: 'path/to/storybook-config' });
const res = await getDependentStoryFiles(ctx, { modules }, statsPath, changedFiles);
expect(res).toEqual(null);
expect(res).toBeUndefined();
expect(ctx.turboSnap.bailReason).toEqual({
changedStorybookFiles: ['path/to/storybook-config/file.js'],
});
Expand All @@ -530,7 +530,7 @@ describe('getDependentStoryFiles', () => {
];
const ctx = getContext({ configDir: 'path/to/storybook-config' });
const res = await getDependentStoryFiles(ctx, { modules }, statsPath, changedFiles);
expect(res).toEqual(null);
expect(res).toBeUndefined();
expect(ctx.turboSnap.bailReason).toEqual({
changedStorybookFiles: ['path/to/storybook-config/file.js'],
});
Expand Down Expand Up @@ -558,7 +558,7 @@ describe('getDependentStoryFiles', () => {
];
const ctx = getContext({ configDir: 'path/to/storybook-config' });
const res = await getDependentStoryFiles(ctx, { modules }, statsPath, changedFiles);
expect(res).toEqual(null);
expect(res).toBeUndefined();
expect(ctx.turboSnap.bailReason).toEqual({
changedStorybookFiles: ['path/to/storybook-config/file.js', 'src/styles.js'],
});
Expand All @@ -585,7 +585,7 @@ describe('getDependentStoryFiles', () => {
];
const ctx = getContext({ staticDir: ['path/to/statics'] });
const res = await getDependentStoryFiles(ctx, { modules }, statsPath, changedFiles);
expect(res).toEqual(null);
expect(res).toBeUndefined();
expect(ctx.turboSnap.bailReason).toEqual({
changedStaticFiles: ['path/to/statics/image.png'],
});
Expand Down
2 changes: 1 addition & 1 deletion node-src/lib/getDependentStoryFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ export async function getDependentStoryFiles(

if (ctx.turboSnap.bailReason) {
ctx.log.warn(bailFile({ turboSnap: ctx.turboSnap }));
return null;
return;
}

return affectedModules;
Expand Down
4 changes: 2 additions & 2 deletions node-src/lib/getFileHashes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const hashFile = (buffer: Buffer, path: string, xxhash: XXHashAPI): Promise<stri
};

const readIncremental = (fd: number, hash: XXHash<bigint>) => {
read(fd, buffer, null, BUFFER_SIZE, -1, (readErr, bytesRead) => {
read(fd, buffer, undefined, BUFFER_SIZE, -1, (readErr, bytesRead) => {
if (readErr) {
return close(fd, () => reject(readErr));
}
Expand All @@ -36,7 +36,7 @@ const hashFile = (buffer: Buffer, path: string, xxhash: XXHashAPI): Promise<stri
if (openErr) {
return reject(openErr);
}
read(fd, buffer, null, BUFFER_SIZE, -1, (readErr, bytesRead) => {
read(fd, buffer, undefined, BUFFER_SIZE, -1, (readErr, bytesRead) => {
if (readErr) {
return close(fd, () => reject(readErr));
}
Expand Down
4 changes: 2 additions & 2 deletions node-src/lib/getPrebuiltStorybookMetadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ export const getStorybookMetadataFromProjectJson = async (
const builder = getBuilder(sbProjectJson);

return {
viewLayer: sbProjectJson.framework.name ?? null,
version: sbProjectJson.storybookPackages[viewLayerPackage].version ?? null,
viewLayer: sbProjectJson.framework.name,
version: sbProjectJson.storybookPackages[viewLayerPackage].version,
builder,
addons: Object.entries(sbProjectJson.addons)
.filter(([packageName]) => supportedAddons[packageName])
Expand Down
4 changes: 2 additions & 2 deletions node-src/lib/getStorybookConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ export default function getStorybookConfiguration(
shortName: string,
longName?: string
) {
if (!storybookScript) return null;
if (!storybookScript) return;
const parts = storybookScript.split(/[\s"'=]+/);
let index = parts.indexOf(longName);
if (index === -1) {
index = parts.indexOf(shortName);
}
if (index === -1) {
return null;
return;
}
return parts[index + 1];
}
7 changes: 1 addition & 6 deletions node-src/lib/getStorybookInfo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,12 +203,7 @@ describe('getStorybookInfo', () => {
options: { storybookBuildDir: 'bin-src/__mocks__/malformedProjectJson' },
packageJson: { dependencies: REACT },
});
expect(await getStorybookInfo(ctx)).toEqual({
addons: [],
version: null,
viewLayer: null,
builder: null,
});
expect(await getStorybookInfo(ctx)).toEqual({});
});

it('does not return unsupported addons in metadata', async () => {
Expand Down
2 changes: 1 addition & 1 deletion node-src/lib/getStorybookInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ export default async function getStorybookInfo(
return await getStorybookMetadata(ctx);
} catch (err) {
ctx.log.debug(err);
return { viewLayer: null, version: null, addons: [], builder: null };
return {};
}
}
1 change: 0 additions & 1 deletion node-src/lib/getStorybookMetadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,6 @@ export const getStorybookMetadata = async (ctx: Context) => {
v7 = true;
} catch (err) {
ctx.log.debug({ storybookV7error: err });
mainConfig = null;
}
}

Expand Down
4 changes: 2 additions & 2 deletions node-src/lib/uploadMetadataFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ export async function uploadMetadataFiles(ctx: Context) {
ctx.options.logFile,
ctx.options.diagnosticsFile,
ctx.options.storybookLogFile,
await findStorybookConfigFile(ctx, /^main\.[jt]sx?$/).catch(() => null),
await findStorybookConfigFile(ctx, /^preview\.[jt]sx?$/).catch(() => null),
await findStorybookConfigFile(ctx, /^main\.[jt]sx?$/).catch(() => undefined),
await findStorybookConfigFile(ctx, /^preview\.[jt]sx?$/).catch(() => undefined),
ctx.fileInfo?.statsPath && (await trimStatsFile([ctx.fileInfo.statsPath])),
].filter(Boolean);

Expand Down
6 changes: 3 additions & 3 deletions node-src/tasks/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ function e2eBuildErrorMessage(
}

export const buildStorybook = async (ctx: Context) => {
let logFile = null;
let logFile;
if (ctx.options.storybookLogFile) {
ctx.buildLogFile = path.resolve(ctx.options.storybookLogFile);
logFile = createWriteStream(ctx.buildLogFile);
Expand All @@ -112,10 +112,10 @@ export const buildStorybook = async (ctx: Context) => {
const { experimental_abortSignal: signal } = ctx.options;
try {
ctx.log.debug('Running build command:', ctx.buildCommand);
ctx.log.debug('Runtime metadata:', JSON.stringify(ctx.runtimeMetadata, null, 2));
ctx.log.debug('Runtime metadata:', JSON.stringify(ctx.runtimeMetadata, undefined, 2));

const subprocess = execaCommand(ctx.buildCommand, {
stdio: [null, logFile, null],
stdio: [undefined, logFile, undefined],
// When `true`, this will run in the node version set by the
// action (node20), not the version set in the workflow
preferLocal: false,
Expand Down
2 changes: 1 addition & 1 deletion node-src/tasks/gitInfo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ describe('setGitInfo', () => {
});
const ctx = { log, options: { onlyChanged: true, externals: ['**/*.scss'] }, client } as any;
await setGitInfo(ctx, {} as any);
expect(ctx.git.changedFiles).toBeNull();
expect(ctx.git.changedFiles).toBeUndefined();
});

it('forces rebuild automatically if app is onboarding', async () => {
Expand Down
12 changes: 6 additions & 6 deletions node-src/tasks/gitInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@ export const setGitInfo = async (ctx: Context, task: Task) => {
version: await getVersion(),
gitUserEmail: await getUserEmail().catch((err) => {
ctx.log.debug('Failed to retrieve Git user email', err);
return null;
return undefined;
}),
uncommittedHash: await getUncommittedHash().catch((err) => {
ctx.log.warn('Failed to retrieve uncommitted files hash', err);
return null;
return undefined;
}),
...commitAndBranchInfo,
};
Expand Down Expand Up @@ -225,8 +225,8 @@ export const setGitInfo = async (ctx: Context, task: Task) => {
}
} catch (err) {
ctx.turboSnap.bailReason = { invalidChangedFiles: true };
ctx.git.changedFiles = null;
ctx.git.replacementBuildIds = null;
delete ctx.git.changedFiles;
delete ctx.git.replacementBuildIds;
ctx.log.warn(invalidChangedFiles());
ctx.log.debug(err);
}
Expand All @@ -237,8 +237,8 @@ export const setGitInfo = async (ctx: Context, task: Task) => {
if (matches.length > 0) {
ctx.turboSnap.bailReason = { changedExternalFiles: matches };
ctx.log.warn(externalsChanged(matches));
ctx.git.changedFiles = null;
ctx.git.replacementBuildIds = null;
delete ctx.git.changedFiles;
delete ctx.git.replacementBuildIds;
break;
}
}
Expand Down
2 changes: 1 addition & 1 deletion node-src/tasks/initialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const setEnvironment = async (ctx: Context) => {
}
}

ctx.log.debug(`Got environment:\n${JSON.stringify(ctx.environment, null, 2)}`);
ctx.log.debug(`Got environment:\n${JSON.stringify(ctx.environment, undefined, 2)}`);
};

export const setRuntimeMetadata = async (ctx: Context) => {
Expand Down
2 changes: 1 addition & 1 deletion node-src/ui/messages/errors/buildFailed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default (
`),
message,
chalk`${info} Build command:\n{dim ${buildCommand}}`,
chalk`${info} Runtime metadata:\n{dim ${JSON.stringify(runtimeMetadata, null, 2)}}`,
chalk`${info} Runtime metadata:\n{dim ${JSON.stringify(runtimeMetadata, undefined, 2)}}`,
chalk`${info} Storybook build output:\n{dim ${buildLogFile}}`,
lines.join(`\n`),
].join('\n\n');
Expand Down
2 changes: 1 addition & 1 deletion node-src/ui/messages/errors/fatalError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export default function fatalError(
Please provide us with the above CLI output and the following info:
`),
chalk`{bold ${JSON.stringify(debugInfo, null, 2)}}`,
chalk`{bold ${JSON.stringify(debugInfo, undefined, 2)}}`,
stacktraces.length > 0 ? chalk`\n{dim ${stacktraces.join('\n\n')}}` : '',
].join('\n');
}
2 changes: 1 addition & 1 deletion node-src/ui/messages/errors/uploadFailed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ export function uploadFailed({ target }: { target: FileDesc & TargetInfo }, debu
${diagnosis}
${debug ? '' : chalk`Enable the {bold debug} option to get more information.`}
`);
return debug ? message + JSON.stringify(target, null, 2) : message;
return debug ? message + JSON.stringify(target, undefined, 2) : message;
}
2 changes: 1 addition & 1 deletion node-src/ui/messages/info/tracedAffectedFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default (
const changed = pluralize('changed files', changedFiles.length, true);
const affected = pluralize('affected story files', Object.keys(affectedModules).length, true);

let directoryDebug = null;
let directoryDebug;

if (expanded) {
const bailReason = ctx.turboSnap?.bailReason ? `${ctx.turboSnap.bailReason}\n\n` : '';
Expand Down
1 change: 1 addition & 0 deletions node-src/ui/tasks/verify.stories.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable unicorn/no-null -- GraphQL returns `null` if a value doesn't exist */
import task from '../components/task';
import {
awaitingUpgrades,
Expand Down
2 changes: 1 addition & 1 deletion test-stories/Tests.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default {
};

export const WithViewports = () => {
let bg = null;
let bg;
if (window.matchMedia('(max-width: 400px)').matches) {
bg = 'cyan';
} else if (window.matchMedia('(max-width: 800px)').matches) {
Expand Down

0 comments on commit 38a7b49

Please sign in to comment.