Skip to content

Commit

Permalink
Merge pull request #1064 from chromaui/cody/cap-2260-enable-unicornpr…
Browse files Browse the repository at this point in the history
…event-abbreviations

Enable `unicorn/prevent-abbreviations` ESLint rule
  • Loading branch information
codykaup authored Sep 30, 2024
2 parents 91a8f73 + 7e28628 commit aa83825
Show file tree
Hide file tree
Showing 70 changed files with 507 additions and 442 deletions.
6 changes: 3 additions & 3 deletions bin-src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ export const installArchiveDependencies = async (
packageJson: PackageJson,
testFramework: TestFrameworkType
) => {
const defaultInstallArgs = ['-D', 'chromatic', `@chromatic-com/${testFramework}`];
const defaultInstallArguments = ['-D', 'chromatic', `@chromatic-com/${testFramework}`];
const sbPackages = getStorybookPackages(packageJson);
const installArgs = [...defaultInstallArgs, ...sbPackages];
const installCommand = await getPackageManagerInstallCommand(installArgs);
const installArguments = [...defaultInstallArguments, ...sbPackages];
const installCommand = await getPackageManagerInstallCommand(installArguments);
await execaCommand(installCommand);
};

Expand Down
14 changes: 7 additions & 7 deletions bin-src/trace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { execSync } from 'child_process';
import { describe, expect, it } from 'vitest';

import {
baseDirNote,
rootDirNote,
storybookDirNote,
baseDirectoryNote,
rootDirectoryNote,
storybookDirectoryNote,
traceSuggestions,
} from '../node-src/ui/messages/info/tracedAffectedFiles';

Expand All @@ -17,7 +17,7 @@ describe('Test trace script from package.json', () => {
const output = execSync(`yarn ${scriptName}`).toString().trim();

// Verify that the output does not contain the expanded output
expect(output).not.toContain(rootDirNote);
expect(output).not.toContain(rootDirectoryNote);
});
it('outputs directory info when -m expanded is passed', () => {
const scriptName =
Expand All @@ -30,9 +30,9 @@ describe('Test trace script from package.json', () => {
const expandedFileModule = `node-src/ui/messages/errors/invalidReportPath.ts`;

// Add your assertions based on the expected output or behavior of the script
expect(output).toContain(rootDirNote);
expect(output).toContain(baseDirNote);
expect(output).toContain(storybookDirNote);
expect(output).toContain(rootDirectoryNote);
expect(output).toContain(baseDirectoryNote);
expect(output).toContain(storybookDirectoryNote);
expect(output).toContain(traceSuggestions);
expect(output).toContain(expandedStoryModule);
expect(output).toContain(expandedFileModule);
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 @@ -2,7 +2,7 @@ import { outputFile } from 'fs-extra';

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

const dedupe = <T>(arr: T[]) => [...new Set(arr)];
const dedupe = <T>(array: T[]) => [...new Set(array)];
const isUserCode = ({ name, moduleName = name }: { name?: string; moduleName?: string }) =>
moduleName &&
!moduleName.startsWith('(webpack)') &&
Expand Down
5 changes: 4 additions & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export default [
// Chromatic uses err as our catch convention.
// This is baked into pino transforms as well.
'unicorn/prevent-abbreviations': [
'off', // TODO: Switch this to 'error' when we are ready to enforce this rule
'error',
{
allowList: {
err: true,
Expand All @@ -122,7 +122,10 @@ export default [
str: true,
args: true,
docsUrl: true,
fn: true,
pkg: true,
},
ignore: [/.*e2e.*/, /\w+[Dd]ocs\w*/],
},
],
'unicorn/catch-error-name': [
Expand Down
4 changes: 2 additions & 2 deletions isChromatic.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-env browser */

module.exports = function isChromatic(windowArg) {
const windowToCheck = windowArg || (typeof window !== 'undefined' && window);
module.exports = function isChromatic(windowArgument) {
const windowToCheck = windowArgument || (typeof window !== 'undefined' && window);
return !!(
windowToCheck &&
(/Chromatic/.test(windowToCheck.navigator.userAgent) ||
Expand Down
4 changes: 2 additions & 2 deletions isChromatic.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-env browser */

export default function isChromatic(windowArg) {
const windowToCheck = windowArg || (typeof window !== 'undefined' && window);
export default function isChromatic(windowArgument) {
const windowToCheck = windowArgument || (typeof window !== 'undefined' && window);
return !!(
windowToCheck &&
(/Chromatic/.test(windowToCheck.navigator.userAgent) ||
Expand Down
12 changes: 6 additions & 6 deletions node-src/git/generateGitRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,22 @@ async function generateCommit(
.map((parentName) => parentName && commitMap[parentName].hash);

const randomBranchName = `temp-${Math.random().toString().slice(2)}`;
const commitEnv = `GIT_COMMITTER_DATE='${nextDate()}'`;
const commitEnvironment = `GIT_COMMITTER_DATE='${nextDate()}'`;
// No parent, check out nothing
if (parentCommits.length === 0) {
await runGit(`git checkout --orphan ${randomBranchName}`);
await runGit(`${commitEnv} git commit -m ${name} --allow-empty`);
await runGit(`${commitEnvironment} git commit -m ${name} --allow-empty`);
} else {
// Check out the first parent
await runGit(`git checkout ${parentCommits[0]}`);

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

return { hash, committedAt: Number.parseInt(committedAt, 10) };
}
Expand Down
4 changes: 2 additions & 2 deletions node-src/git/getCommitAndBranch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ const mergeQueueBranchMatch = vi.mocked(git.mergeQueueBranchMatch);

const log = { info: vi.fn(), warn: vi.fn(), debug: vi.fn() };

const processEnv = process.env;
const processEnvironment = process.env;
beforeEach(() => {
process.env = { ...processEnv };
process.env = { ...processEnvironment };
envCi.mockReturnValue({});
getBranch.mockResolvedValue('main');
getCommit.mockResolvedValue({
Expand Down
6 changes: 3 additions & 3 deletions node-src/git/getCommitAndBranch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export default async function getCommitAndBranch(
} = process.env;
const { isCi, service, prBranch, branch: ciBranch, commit: ciCommit, slug: ciSlug } = envCi();

const isFromEnvVariable = CHROMATIC_SHA && CHROMATIC_BRANCH; // Our GitHub Action also sets these
const isFromEnvironmentVariable = CHROMATIC_SHA && CHROMATIC_BRANCH; // Our GitHub Action also sets these
const isTravisPrBuild = TRAVIS_EVENT_TYPE === 'pull_request';
const isGitHubAction = GITHUB_ACTIONS === 'true';
const isGitHubPrBuild = GITHUB_EVENT_NAME === 'pull_request';
Expand All @@ -70,7 +70,7 @@ export default async function getCommitAndBranch(
}
}

if (isFromEnvVariable) {
if (isFromEnvironmentVariable) {
commit = await getCommit(CHROMATIC_SHA).catch((err) => {
log.warn(noCommitDetails({ sha: CHROMATIC_SHA, env: 'CHROMATIC_SHA' }));
log.debug(err);
Expand Down Expand Up @@ -156,7 +156,7 @@ export default async function getCommitAndBranch(
!!process.env.GITHUB_REPOSITORY;

// Strip off any `origin/` prefix that's added sometimes.
if (!branchName && !isFromEnvVariable && ORIGIN_PREFIX_REGEXP.test(branch)) {
if (!branchName && !isFromEnvironmentVariable && ORIGIN_PREFIX_REGEXP.test(branch)) {
log.warn(`Ignoring 'origin/' prefix in branch name.`);
branch = branch.replace(ORIGIN_PREFIX_REGEXP, '');
}
Expand Down
32 changes: 18 additions & 14 deletions node-src/git/git.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { execaCommand } from 'execa';
import { EOL } from 'os';
import pLimit from 'p-limit';
import { file as tmpFile } from 'tmp-promise';
import { file as temporaryFile } from 'tmp-promise';

import { Context } from '../types';
import gitNoCommits from '../ui/messages/errors/gitNoCommits';
Expand Down Expand Up @@ -88,13 +88,13 @@ export async function getBranch() {
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
const reference = await execGitCommand('git symbolic-ref HEAD');
return reference.replace(/^refs\/heads\//, ''); // strip the "refs/heads/" prefix
} catch {
// Git v1.7 and above
// Yields 'HEAD' when in detached HEAD state
const ref = await execGitCommand('git rev-parse --abbrev-ref HEAD');
return ref.replace(/^heads\//, ''); // strip the "heads/" prefix that's sometimes present
const reference = await execGitCommand('git rev-parse --abbrev-ref HEAD');
return reference.replace(/^heads\//, ''); // strip the "heads/" prefix that's sometimes present
}
}
}
Expand Down Expand Up @@ -230,8 +230,8 @@ export async function getUpdateMessage() {
* @param {string} headRef Name of the head branch
* @param {string} baseRef Name of the base branch
*/
export async function findMergeBase(headRef: string, baseRef: string) {
const result = await execGitCommand(`git merge-base --all ${headRef} ${baseRef}`);
export async function findMergeBase(headReference: string, baseReference: string) {
const result = await execGitCommand(`git merge-base --all ${headReference} ${baseReference}`);
const mergeBases = result.split(newline).filter((line) => line && !line.startsWith('warning: '));
if (mergeBases.length === 0) return undefined;
if (mergeBases.length === 1) return mergeBases[0];
Expand All @@ -244,21 +244,25 @@ export async function findMergeBase(headRef: string, baseRef: string) {
return name.replace(/~\d+$/, ''); // Drop the potential suffix
})
);
const baseRefIndex = branchNames.indexOf(baseRef);
return mergeBases[baseRefIndex] || mergeBases[0];
const baseReferenceIndex = branchNames.indexOf(baseReference);
return mergeBases[baseReferenceIndex] || mergeBases[0];
}

export async function checkout(ref: string) {
return execGitCommand(`git checkout ${ref}`);
export async function checkout(reference: string) {
return execGitCommand(`git checkout ${reference}`);
}

const fileCache = {};
const limitConcurrency = pLimit(10);
export async function checkoutFile({ log }: Pick<Context, 'log'>, ref: string, fileName: string) {
const pathspec = `${ref}:${fileName}`;
export async function checkoutFile(
{ log }: Pick<Context, 'log'>,
reference: string,
fileName: string
) {
const pathspec = `${reference}:${fileName}`;
if (!fileCache[pathspec]) {
fileCache[pathspec] = limitConcurrency(async () => {
const { path: targetFileName } = await tmpFile({
const { path: targetFileName } = await temporaryFile({
postfix: `-${fileName.replaceAll('/', '--')}`,
});
log.debug(`Checking out file ${pathspec} at ${targetFileName}`);
Expand Down
14 changes: 7 additions & 7 deletions node-src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { getGitInfo, runAll } from '.';
import * as git from './git/git';
import { DNSResolveAgent } from './io/getDNSResolveAgent';
import * as checkPackageJson from './lib/checkPackageJson';
import getEnv from './lib/getEnv';
import parseArgs from './lib/parseArgs';
import getEnvironment from './lib/getEnvironment';
import parseArguments from './lib/parseArguments';
import TestLogger from './lib/testLogger';
import { uploadFiles } from './lib/uploadFiles';
import { writeChromaticDiagnostics } from './lib/writeChromaticDiagnostics';
Expand Down Expand Up @@ -342,9 +342,9 @@ vi.mock('./lib/uploadFiles');

vi.mock('./lib/spawn', () => ({ default: () => Promise.resolve('https://npm.example.com') }));

let processEnv;
let processEnvironment;
beforeEach(() => {
processEnv = process.env;
processEnvironment = process.env;
process.env = {
DISABLE_LOGGING: 'true',
CHROMATIC_APP_CODE: undefined,
Expand All @@ -361,14 +361,14 @@ beforeEach(() => {
getSlug.mockResolvedValue('user/repo');
});
afterEach(() => {
process.env = processEnv;
process.env = processEnvironment;
});

const getContext = (argv: string[]): Context & { testLogger: TestLogger } => {
const testLogger = new TestLogger();
return {
title: '',
env: getEnv(),
env: getEnvironment(),
log: testLogger,
testLogger,
sessionId: ':sessionId',
Expand All @@ -384,7 +384,7 @@ const getContext = (argv: string[]): Context & { testLogger: TestLogger } => {
packagePath: '',
statsPath: 'preview-stats.json',
options: {},
...parseArgs(argv),
...parseArguments(argv),
} as any;
};

Expand Down
34 changes: 20 additions & 14 deletions node-src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ import checkPackageJson from './lib/checkPackageJson';
import { isE2EBuild } from './lib/e2e';
import { emailHash } from './lib/emailHash';
import { getConfiguration } from './lib/getConfiguration';
import getEnv from './lib/getEnv';
import getEnvironment from './lib/getEnvironment';
import getOptions from './lib/getOptions';
import { createLogger } from './lib/log';
import LoggingRenderer from './lib/LoggingRenderer';
import NonTTYRenderer from './lib/NonTTYRenderer';
import parseArgs from './lib/parseArgs';
import parseArguments from './lib/parseArguments';
import { exitCodes, setExitCode } from './lib/setExitCode';
import { uploadMetadataFiles } from './lib/uploadMetadataFiles';
import { rewriteErrorMessage } from './lib/utils';
Expand Down Expand Up @@ -96,22 +96,26 @@ export async function run({
flags?: Flags;
options?: Partial<Options>;
}): Promise<Output> {
const { sessionId = uuid(), env = getEnv(), log = createLogger() } = extraOptions || {};
const {
sessionId = uuid(),
env: environment = getEnvironment(),
log = createLogger(),
} = extraOptions || {};

const pkgInfo = await readPkgUp({ cwd: process.cwd() });
if (!pkgInfo) {
const packageInfo = await readPkgUp({ cwd: process.cwd() });
if (!packageInfo) {
log.error(noPackageJson());
process.exit(253);
}

const { path: packagePath, packageJson } = pkgInfo;
const { path: packagePath, packageJson } = packageInfo;
const ctx: InitialContext = {
...parseArgs(argv),
...parseArguments(argv),
...(flags && { flags }),
...(extraOptions && { extraOptions }),
packagePath,
packageJson,
env,
env: environment,
log,
sessionId,
};
Expand Down Expand Up @@ -142,12 +146,12 @@ export async function runAll(ctx: InitialContext) {
ctx.log.info(intro(ctx));
ctx.log.info('');

const onError = (e: Error | Error[]) => {
const onError = (err: Error | Error[]) => {
ctx.log.info('');
ctx.log.error(fatalError(ctx, [e].flat()));
ctx.log.error(fatalError(ctx, [err].flat()));
ctx.extraOptions?.experimental_onTaskError?.(ctx, {
formattedError: fatalError(ctx, [e].flat()),
originalError: e,
formattedError: fatalError(ctx, [err].flat()),
originalError: err,
});
setExitCode(ctx, exitCodes.INVALID_OPTIONS, true);
};
Expand Down Expand Up @@ -278,6 +282,8 @@ export interface GitInfo {
repositoryRootDir: string;
}

// Although this function may not be used directly in this project, it can be used externally (such
// as https://github.com/chromaui/addon-visual-tests).
export async function getGitInfo(): Promise<GitInfo> {
let slug: string;
try {
Expand All @@ -289,7 +295,7 @@ export async function getGitInfo(): Promise<GitInfo> {
const commitInfo = await getCommit();
const userEmail = await getUserEmail();
const userEmailHash = emailHash(userEmail);
const repositoryRootDir = await getRepositoryRoot();
const repositoryRootDirectory = await getRepositoryRoot();

const [ownerName, repoName, ...rest] = slug ? slug.split('/') : [];
const isValidSlug = !!ownerName && !!repoName && rest.length === 0;
Expand All @@ -302,7 +308,7 @@ export async function getGitInfo(): Promise<GitInfo> {
uncommittedHash,
userEmail,
userEmailHash,
repositoryRootDir,
repositoryRootDir: repositoryRootDirectory,
};
}

Expand Down
2 changes: 1 addition & 1 deletion node-src/io/GraphQLClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default class GraphQLClient {
},
{ retries }
)
.then((res) => res.json() as any)
.then((result) => result.json() as any)
.catch(bail);

if (!errors) return data;
Expand Down
Loading

0 comments on commit aa83825

Please sign in to comment.