Skip to content

Commit

Permalink
Fix a bunch of ESLint unicorn errors
Browse files Browse the repository at this point in the history
  • Loading branch information
codykaup committed Sep 12, 2024
1 parent 220a3c2 commit d8f3708
Show file tree
Hide file tree
Showing 71 changed files with 294 additions and 280 deletions.
4 changes: 2 additions & 2 deletions bin-src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ export const addChromaticScriptToPackageJson = async ({ packageJson, packagePath
},
};
await writeFile(packagePath, json, { spaces: 2 });
} catch (e) {
console.warn(e);
} catch (err) {
console.warn(err);
}
};

Expand Down
8 changes: 4 additions & 4 deletions bin-src/trim-stats-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { outputFile } from 'fs-extra';

import { readStatsFile } from '../node-src/tasks/read-stats-file';

const dedupe = <T>(arr: T[]) => Array.from(new Set(arr));
const dedupe = <T>(arr: T[]) => [...new Set(arr)];
const isUserCode = ({ name, moduleName = name }: { name?: string; moduleName?: string }) =>
moduleName &&
!moduleName.startsWith('(webpack)') &&
!moduleName.match(/(node_modules|webpack\/runtime)\//);
!/(node_modules|webpack\/runtime)\//.test(moduleName);

/**
* Utility to trim down a `preview-stats.json` file to the bare minimum, so that it can be used to
Expand Down Expand Up @@ -41,8 +41,8 @@ export async function main([statsFile = './storybook-static/preview-stats.json']
await outputFile(
targetFile,
JSON.stringify({ modules: trimmedModules }, null, 2)
.replace(/{\n {10}/g, '{ ')
.replace(/\n {8}}/g, ' }')
.replaceAll(/{\n {10}/g, '{ ')
.replaceAll(/\n {8}}/g, ' }')
);

console.log(`Wrote ${targetFile}`);
Expand Down
4 changes: 2 additions & 2 deletions isChromatic.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module.exports = function isChromatic(windowArg) {
const windowToCheck = windowArg || (typeof window !== 'undefined' && window);
return !!(
windowToCheck &&
(windowToCheck.navigator.userAgent.match(/Chromatic/) ||
windowToCheck.location.href.match(/chromatic=true/))
(/Chromatic/.test(windowToCheck.navigator.userAgent) ||
/chromatic=true/.test(windowToCheck.location.href))
);
};
4 changes: 2 additions & 2 deletions isChromatic.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export default function isChromatic(windowArg) {
const windowToCheck = windowArg || (typeof window !== 'undefined' && window);
return !!(
windowToCheck &&
(windowToCheck.navigator.userAgent.match(/Chromatic/) ||
windowToCheck.location.href.match(/chromatic=true/))
(/Chromatic/.test(windowToCheck.navigator.userAgent) ||
/chromatic=true/.test(windowToCheck.location.href))
);
}
2 changes: 2 additions & 0 deletions node-src/__mocks__/storybookBaseDir/subdir/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* eslint-disable unicorn/no-empty-file */
// This file is intentionally left blank
2 changes: 2 additions & 0 deletions node-src/__mocks__/storybookBaseDir/subdir/test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* eslint-disable unicorn/no-empty-file */
// This file is intentionally left blank
2 changes: 2 additions & 0 deletions node-src/__mocks__/storybookBaseDir/subdir/test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* eslint-disable unicorn/no-empty-file */
// This file is intentionally left blank
2 changes: 2 additions & 0 deletions node-src/__mocks__/storybookBaseDir/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* eslint-disable unicorn/no-empty-file */
// This file is intentionally left blank
23 changes: 11 additions & 12 deletions node-src/git/generateGitRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ async function generateCommit(
[name, parentNames]: Line,
commitMap: CommitMap
) {
const parentCommits = []
.concat(parentNames)
.filter((parentName) => commitMap[parentName])
.map((parentName) => commitMap[parentName].hash);
const parentCommits = [parentNames]
.flat()
.filter((parentName) => parentName && commitMap[parentName])
.map((parentName) => parentName && commitMap[parentName].hash);

const randomBranchName = `temp-${Math.random().toString().substring(2)}`;
const randomBranchName = `temp-${Math.random().toString().slice(2)}`;
const commitEnv = `GIT_COMMITTER_DATE='${nextDate()}'`;
// No parent, check out nothing
if (parentCommits.length === 0) {
Expand All @@ -34,15 +34,14 @@ async function generateCommit(
await runGit(`git checkout ${parentCommits[0]}`);

// If more parents, create merge commit
if (parentCommits.length > 1) {
await runGit(`${commitEnv} git merge -m ${name} ${parentCommits.slice(1).join(' ')}`);
} else {
await runGit(`${commitEnv} git commit -m ${name} --allow-empty`);
}
await (parentCommits.length > 1
? runGit(`${commitEnv} git merge -m ${name} ${parentCommits.slice(1).join(' ')}`)
: runGit(`${commitEnv} git commit -m ${name} --allow-empty`));
}
const [hash, committedAt] = (await runGit(`git show --format=%H,%ct`)).stdout.trim().split(',');
const gitShowStr = await runGit(`git show --format=%H,%ct`);
const [hash, committedAt] = gitShowStr.stdout.trim().split(',');

return { hash, committedAt: parseInt(committedAt, 10) };
return { hash, committedAt: Number.parseInt(committedAt, 10) };
}

// Take a repository description in the following format:
Expand Down
2 changes: 1 addition & 1 deletion node-src/git/getChangedFilesWithReplacement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getChangedFilesWithReplacement } from './getChangedFilesWithReplacement

vi.mock('./git', () => ({
getChangedFiles: (hash) => {
if (hash.match(/exists/)) return ['changed', 'files'];
if (/exists/.test(hash)) return ['changed', 'files'];
throw new Error(`fatal: bad object ${hash}`);
},
commitExists: (hash) => hash.match(/exists/),
Expand Down
2 changes: 1 addition & 1 deletion node-src/git/getChangedFilesWithReplacement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export async function getChangedFilesWithReplacement(
`Got error fetching commit for #${build.number}(${build.commit}): ${err.message}`
);

if (err.message.match(/(bad object|uncommitted changes)/)) {
if (/(bad object|uncommitted changes)/.test(err.message)) {
const replacementBuild = await findAncestorBuildWithCommit(context, build.number);

if (replacementBuild) {
Expand Down
6 changes: 3 additions & 3 deletions node-src/git/getCommitAndBranch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ beforeEach(() => {
getBranch.mockResolvedValue('main');
getCommit.mockResolvedValue({
commit: '48e0c83fadbf504c191bc868040b7a969a4f1feb',
committedAt: 1640094096000,
committedAt: 1_640_094_096_000,
committerName: 'GitHub',
committerEmail: '[email protected]',
});
Expand All @@ -40,7 +40,7 @@ afterEach(() => {
});

const commitInfo = {
committedAt: 1640131292,
committedAt: 1_640_131_292,
committerName: 'Gert Hengeveld',
committerEmail: '[email protected]',
};
Expand All @@ -51,7 +51,7 @@ describe('getCommitAndBranch', () => {
expect(info).toMatchObject({
branch: 'main',
commit: '48e0c83fadbf504c191bc868040b7a969a4f1feb',
committedAt: 1640094096000,
committedAt: 1_640_094_096_000,
committerName: 'GitHub',
committerEmail: '[email protected]',
slug: undefined,
Expand Down
4 changes: 2 additions & 2 deletions node-src/git/getParentCommits.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function expectCommitsToEqualNames(hashes, names, { commitMap }) {

async function checkoutCommit(name, branch, { dirname, runGit, commitMap }) {
process.chdir(dirname);
await runGit(`git checkout ${branch !== 'HEAD' ? `-B ${branch}` : ''} ${commitMap[name].hash}`);
await runGit(`git checkout ${branch === 'HEAD' ? '' : `-B ${branch}`} ${commitMap[name].hash}`);

return commitMap[name].hash;
}
Expand All @@ -77,7 +77,7 @@ const repositories: Record<string, Repository> = {};
beforeAll(async () => {
await Promise.all(
Object.keys(descriptions).map(async (key) => {
const dirname = (await tmp.dir({ unsafeCleanup: true, prefix: `chromatictest-` })).path;
const { path: dirname } = await tmp.dir({ unsafeCleanup: true, prefix: `chromatictest-` });
const runGit = makeRunGit(dirname);
const commitMap = await generateGitRepository(runGit, descriptions[key]);
repositories[key] = { dirname, runGit, commitMap };
Expand Down
6 changes: 4 additions & 2 deletions node-src/git/getParentCommits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ async function nextCommits(
${firstCommittedAtSeconds ? `--since ${firstCommittedAtSeconds}` : ''} \
-n ${limit + commitsWithoutBuilds.length} --not ${commitsForCLI(commitsWithBuilds)}`;
log.debug(`running ${command}`);
const commits = (await execGitCommand(command)).split('\n').filter(Boolean);
const commitsString = await execGitCommand(command);
const commits = commitsString.split('\n').filter(Boolean);
log.debug(`command output: ${commits}`);

// Later on we want to know which commits we visited on the way to finding the ancestor commits
Expand Down Expand Up @@ -190,7 +191,8 @@ async function maximallyDescendentCommits({ log }: Pick<Context, 'log'>, commits
// This just filters any commits that are ancestors of other commits
const command = `git rev-list ${commitsForCLI(commits)} --not ${commitsForCLI(parentCommits)}`;
log.debug(`running ${command}`);
const maxCommits = (await execGitCommand(command)).split('\n').filter(Boolean);
const maxCommitsString = await execGitCommand(command);
const maxCommits = maxCommitsString.split('\n').filter(Boolean);
log.debug(`command output: ${maxCommits}`);

return maxCommits;
Expand Down
4 changes: 2 additions & 2 deletions node-src/git/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('getCommit', () => {
);
expect(await getCommit()).toEqual({
commit: '19b6c9c5b3d34d9fc55627fcaf8a85bd5d5e5b2a',
committedAt: 1696588814 * 1000,
committedAt: 1_696_588_814 * 1000,
committerEmail: '[email protected]',
committerName: 'Gert Hengeveld',
});
Expand All @@ -48,7 +48,7 @@ gpg: Can't check signature: No public key
);
expect(await getCommit()).toEqual({
commit: '19b6c9c5b3d34d9fc55627fcaf8a85bd5d5e5b2a',
committedAt: 1696588814 * 1000,
committedAt: 1_696_588_814 * 1000,
committerEmail: '[email protected]',
committerName: 'Gert Hengeveld',
});
Expand Down
39 changes: 19 additions & 20 deletions node-src/git/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export async function execGitCommand(command: string) {
try {
const { all } = await execaCommand(command, {
env: { LANG: 'C', LC_ALL: 'C' }, // make sure we're speaking English
timeout: 20000, // 20 seconds
timeout: 20_000, // 20 seconds
all: true, // interleave stdout and stderr
shell: true, // we'll deal with escaping ourselves (for now)
});
Expand Down Expand Up @@ -84,13 +84,13 @@ export async function getBranch() {
// Yields an empty string when in detached HEAD state
const branch = await execGitCommand('git branch --show-current');
return branch || 'HEAD';
} catch (_err) {
} catch {
try {
// Git v1.8 and above
// Throws when in detached HEAD state
const ref = await execGitCommand('git symbolic-ref HEAD');
return ref.replace(/^refs\/heads\//, ''); // strip the "refs/heads/" prefix
} catch (_ex) {
} catch {
// Git v1.7 and above
// Yields 'HEAD' when in detached HEAD state
const ref = await execGitCommand('git rev-parse --abbrev-ref HEAD');
Expand All @@ -108,14 +108,13 @@ export async function getUncommittedHash() {
const listUntrackedFiles = 'git ls-files --others --exclude-standard';
const listUncommittedFiles = [listStagedFiles, listUnstagedFiles, listUntrackedFiles].join(';');

const uncommittedHash = (
await execGitCommand(
// Pass the combined list of filenames to hash-object to retrieve a list of hashes. Then pass
// the list of hashes to hash-object again to retrieve a single hash of all hashes. We use
// stdin to avoid the limit on command line arguments.
`(${listUncommittedFiles}) | git hash-object --stdin-paths | git hash-object --stdin`
)
).trim();
let uncommittedHash = await execGitCommand(
// Pass the combined list of filenames to hash-object to retrieve a list of hashes. Then pass
// the list of hashes to hash-object again to retrieve a single hash of all hashes. We use
// stdin to avoid the limit on command line arguments.
`(${listUncommittedFiles}) | git hash-object --stdin-paths | git hash-object --stdin`
);
uncommittedHash = uncommittedHash.trim();

// In case there are no uncommited changes (empty list), we always get this same hash.
const noChangesHash = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391';
Expand All @@ -135,7 +134,7 @@ export async function commitExists(commit: string) {
try {
await execGitCommand(`git cat-file -e "${commit}^{commit}"`);
return true;
} catch (_err) {
} catch {
return false;
}
}
Expand All @@ -153,26 +152,26 @@ export async function getChangedFiles(baseCommit: string, headCommit = '') {
export async function isUpToDate({ log }: Pick<Context, 'log'>) {
try {
await execGitCommand(`git remote update`);
} catch (e) {
log.warn(e);
} catch (err) {
log.warn(err);
return true;
}

let localCommit;
try {
localCommit = await execGitCommand('git rev-parse HEAD');
if (!localCommit) throw new Error('Failed to retrieve last local commit hash');
} catch (e) {
log.warn(e);
} catch (err) {
log.warn(err);
return true;
}

let remoteCommit;
try {
remoteCommit = await execGitCommand('git rev-parse "@{upstream}"');
if (!remoteCommit) throw new Error('Failed to retrieve last remote commit hash');
} catch (e) {
log.warn(e);
} catch (err) {
log.warn(err);
return true;
}

Expand Down Expand Up @@ -245,7 +244,7 @@ export async function findMergeBase(headRef: string, baseRef: string) {
return name.replace(/~[0-9]+$/, ''); // Drop the potential suffix
})
);
const baseRefIndex = branchNames.findIndex((branch) => branch === baseRef);
const baseRefIndex = branchNames.indexOf(baseRef);
return mergeBases[baseRefIndex] || mergeBases[0];
}

Expand All @@ -260,7 +259,7 @@ export async function checkoutFile({ log }: Pick<Context, 'log'>, ref: string, f
if (!fileCache[pathspec]) {
fileCache[pathspec] = limitConcurrency(async () => {
const { path: targetFileName } = await tmpFile({
postfix: `-${fileName.replace(/\//g, '--')}`,
postfix: `-${fileName.replaceAll('/', '--')}`,
});
log.debug(`Checking out file ${pathspec} at ${targetFileName}`);
await execGitCommand(`git show ${pathspec} > ${targetFileName}`);
Expand Down
8 changes: 4 additions & 4 deletions node-src/git/mocks/long-line.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
// |
// Z

const ACode = 'A'.charCodeAt(0);
const ACode = 'A'.codePointAt(0);

// [commit, parent(s)]
export default [
['A', false],
['z', false],
...[...Array(25)].map((_, index) => [
String.fromCharCode(index + 1 + ACode), // e.g. 'B'
String.fromCharCode(index + ACode), // e.g. 'A'
...Array.from({ length: 25 }).map((_, index) => [
String.fromCodePoint(index + 1 + ACode), // e.g. 'B'
String.fromCodePoint(index + ACode), // e.g. 'A'
]),
];
9 changes: 3 additions & 6 deletions node-src/git/mocks/mock-index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@ interface MergeInfo {
}

function lastBuildOnBranch(builds: Build[], findingBranch: string) {
return builds
.slice()
.reverse()
.find((b) => b.branch === findingBranch);
return [...builds].reverse().find((b) => b.branch === findingBranch);
}

const mocks = {
Expand All @@ -50,7 +47,7 @@ const mocks = {
},
HasBuildsWithCommitsQuery: (builds: Build[], _prs: PR[], { commits }: { commits: string[] }) => ({
app: {
hasBuildsWithCommits: commits.filter((commit) => !!builds.find((b) => b.commit === commit)),
hasBuildsWithCommits: commits.filter((commit) => !!builds.some((b) => b.commit === commit)),
},
}),
MergeCommitsQuery: (
Expand Down Expand Up @@ -83,7 +80,7 @@ export default function createMockIndex({ commitMap }, buildDescriptions, prDesc
if (commitMap[name]) {
const commitInfo = commitMap[name];
hash = commitInfo.hash;
committedAt = parseInt(commitInfo.committedAt, 10) * 1000;
committedAt = Number.parseInt(commitInfo.committedAt, 10) * 1000;
} else {
// Allow for test cases with a commit that is no longer in the history
hash = name;
Expand Down
6 changes: 3 additions & 3 deletions node-src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ vi.mock('node-fetch', () => ({
const data = JSON.parse(body);
query = data.query;
variables = data.variables;
} catch (_err) {
} catch {
// Do nothing
}

Expand Down Expand Up @@ -174,7 +174,7 @@ vi.mock('node-fetch', () => ({
if (query?.match('SnapshotBuildQuery')) {
return {
data: {
app: { build: { status: 'PENDING', changeCount: 1, completedAt: 12345 } },
app: { build: { status: 'PENDING', changeCount: 1, completedAt: 12_345 } },
},
};
}
Expand All @@ -198,7 +198,7 @@ vi.mock('node-fetch', () => ({
status: 'PASSED',
commit: 'baseline',
committedAt: 1234,
completedAt: 12345,
completedAt: 12_345,
changeCount: 1,
},
],
Expand Down
Loading

0 comments on commit d8f3708

Please sign in to comment.