diff --git a/packages/cli/bin/codeshift-cli.js b/packages/cli/bin/codeshift-cli.js index 5896045a5..96b3e16d9 100755 --- a/packages/cli/bin/codeshift-cli.js +++ b/packages/cli/bin/codeshift-cli.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +const tryCatch = require('try-catch'); +const isNumber = a => typeof a === 'number'; /* eslint-disable */ const fs = require('fs'); @@ -11,10 +13,10 @@ if (dev && !require.extensions['.ts']) { require('ts-node').register({ project }); } -try { - require(path.join('..', dev ? 'src/index' : 'dist/codeshift-cli.cjs.js')); -} catch (error) { - if (typeof error === 'number') { +const [error] = tryCatch(require, path.join('..', dev ? 'src/index' : 'dist/codeshift-cli.cjs.js')); + +if (error) { + if (isNumber(error)) { process.exit(error); } console.error(error); diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 9de9e5cb2..7ef742d74 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,3 +1,4 @@ +import tryToCatch from 'try-to-catch'; import chalk from 'chalk'; import { Command, Option, CommanderError } from 'commander'; @@ -128,34 +129,32 @@ Examples: program.exitOverride(); -(async function() { - try { - await program.parseAsync(process.argv); - } catch (error) { - if (error instanceof CommanderError) { - if ( - error.code === 'commander.helpDisplayed' || - error.code === 'commander.version' - ) { - return; - } - - console.error(chalk.red(error.message)); - process.exit(error.exitCode); - } +const [error] = await tryToCatch(program.parseAsync, process.argv); - if (error instanceof InvalidUserInputError) { - console.warn(program.help()); - console.warn(chalk.red(error.message)); - process.exit(9); +if (error) { + if (error instanceof CommanderError) { + if ( + error.code === 'commander.helpDisplayed' || + error.code === 'commander.version' + ) { + return; } - if (error instanceof InvalidConfigError) { - console.warn(chalk.red(error.message)); - process.exit(7); - } + console.error(chalk.red(error.message)); + process.exit(error.exitCode); + } - console.error(chalk.red(error)); - process.exit(1); + if (error instanceof InvalidUserInputError) { + console.warn(program.help()); + console.warn(chalk.red(error.message)); + process.exit(9); } -})(); + + if (error instanceof InvalidConfigError) { + console.warn(chalk.red(error.message)); + process.exit(7); + } + + console.error(chalk.red(error)); + process.exit(1); +} diff --git a/packages/cli/src/init.ts b/packages/cli/src/init.ts index 5e2efef1f..8791b6277 100644 --- a/packages/cli/src/init.ts +++ b/packages/cli/src/init.ts @@ -1,7 +1,7 @@ import path from 'path'; import { initDirectory, initTransform } from '@codeshift/initializer'; -export default async function init( +export default function init( packageName: string, transform?: string, preset?: string, diff --git a/packages/cli/src/list.spec.ts b/packages/cli/src/list.spec.ts index b1cc63b0c..09a312171 100644 --- a/packages/cli/src/list.spec.ts +++ b/packages/cli/src/list.spec.ts @@ -78,7 +78,7 @@ ${chalk.bold('@foo/bar')} it('should return error message a package is not found', async () => { (PluginManager as jest.Mock).mockImplementation(() => ({ install: jest.fn().mockImplementation(() => { - throw new Error('404 not found'); + throw Error('404 not found'); }), })); @@ -93,7 +93,7 @@ ${chalk.bold('@foo/bar')} it('should return error message for multiple packages that are not found', async () => { (PluginManager as jest.Mock).mockImplementation(() => ({ install: jest.fn().mockImplementation(() => { - throw new Error('404 not found'); + throw Error('404 not found'); }), })); @@ -113,12 +113,12 @@ ${chalk.bold('@foo/bar')} install: jest .fn() .mockImplementationOnce(() => { - throw new Error('404 not found'); + throw Error('404 not found'); }) .mockResolvedValueOnce(undefined) .mockResolvedValueOnce(undefined) .mockImplementationOnce(() => { - throw new Error('404 not found'); + throw Error('404 not found'); }) .mockResolvedValueOnce(undefined) .mockResolvedValueOnce(undefined), diff --git a/packages/cli/src/list.ts b/packages/cli/src/list.ts index 8f0bb14db..5567abb70 100644 --- a/packages/cli/src/list.ts +++ b/packages/cli/src/list.ts @@ -12,7 +12,7 @@ export default async function list(packages: string[]) { try { await packageManager.install(codemodName); - } catch (error) { + } catch { console.warn( chalk.red( `Unable to find codeshift package: ${chalk.bold(packageName)}.`, @@ -24,30 +24,32 @@ export default async function list(packages: string[]) { await packageManager.install(codemodName); const pkg = packageManager.require(codemodName); - const config: CodeshiftConfig = pkg.default ? pkg.default : pkg; + const config: CodeshiftConfig = pkg.default || pkg; console.log(chalk.bold(packageName)); if (config.transforms) { - console.log(`├─ transforms`), - Object.keys(config.transforms).forEach((transform, index, array) => { - if (index + 1 === array.length) { - console.log(`| └─ ${transform}`); - return; - } - console.log(`| ├─ ${transform}`); - }); + console.log(`├─ transforms`); + + Object.keys(config.transforms).forEach((transform, index, array) => { + if (index + 1 === array.length) { + console.log(`| └─ ${transform}`); + return; + } + console.log(`| ├─ ${transform}`); + }); } if (config.presets) { - console.log(`└─ presets`), - Object.keys(config.presets).forEach((transform, index, array) => { - if (index + 1 === array.length) { - console.log(` └─ ${transform}`); - return; - } - console.log(`| ├─ ${transform}`); - }); + console.log(`└─ presets`); + + Object.keys(config.presets).forEach((transform, index, array) => { + if (index + 1 === array.length) { + console.log(` └─ ${transform}`); + return; + } + console.log(`| ├─ ${transform}`); + }); } } } diff --git a/packages/cli/src/main.spec.ts b/packages/cli/src/main.spec.ts index bc3c994c1..52ec626e3 100644 --- a/packages/cli/src/main.spec.ts +++ b/packages/cli/src/main.spec.ts @@ -10,6 +10,8 @@ import * as jscodeshift from 'jscodeshift/src/Runner'; import { PluginManager } from 'live-plugin-manager'; import globby from 'globby'; +import tryToCatch from 'try-to-catch'; + import main from './main'; const mockPath = 'src/pages/home-page/'; @@ -23,9 +25,11 @@ describe('main', () => { it('should exit early if file path is not supplied', async () => { expect.assertions(1); - try { - await main([], { transform: 'path/to/transform.ts' }); - } catch (error) { + const [error] = await tryToCatch(main, [], { + transform: 'path/to/transform.ts', + }); + + if (error) { // @ts-ignore expect(error.message).toMatch( 'No path provided, please specify which files your codemod should modify', @@ -36,9 +40,9 @@ describe('main', () => { it('should exit early if nether a package or transform is supplied', async () => { expect.assertions(1); - try { - await main([mockPath], {}); - } catch (error) { + const [error] = await tryToCatch(main, [mockPath], {}); + + if (error) { // @ts-ignore expect(error.message).toMatch( 'No transform provided, please specify a transform with either the --transform or --packages flags', @@ -125,7 +129,7 @@ describe('main', () => { install: jest.fn().mockResolvedValue(undefined), require: jest.fn().mockImplementation((codemodName: string) => { if (!codemodName.startsWith('@codeshift')) { - throw new Error('Attempted to fetch codemod from npm'); + throw Error('Attempted to fetch codemod from npm'); } return { @@ -279,13 +283,13 @@ describe('main', () => { it('should throw when package format is invalid', async () => { expect.assertions(1); - try { - await main([mockPath], { - packages: 'mylib@NOT_SEMVER', - parser: 'babel', - extensions: 'js', - }); - } catch (error) { + const [error] = await tryToCatch(main, [mockPath], { + packages: 'mylib@NOT_SEMVER', + parser: 'babel', + extensions: 'js', + }); + + if (error) { // @ts-ignore expect(error.message).toMatch( 'Invalid version provided to the --packages flag. Unable to resolve version "NOT_SEMVER" for package "mylib". Please try: "[scope]/[package]@[version]" for example @mylib/mypackage@10.0.0', @@ -296,13 +300,13 @@ describe('main', () => { it('should throw when transform is not found', async () => { expect.assertions(1); - try { - await main([mockPath], { - packages: 'mylib@120.0.0', - parser: 'babel', - extensions: 'js', - }); - } catch (error) { + const [error] = await tryToCatch(main, [mockPath], { + packages: 'mylib@120.0.0', + parser: 'babel', + extensions: 'js', + }); + + if (error) { // @ts-ignore expect(error.message).toMatch( 'Invalid version provided to the --packages flag. Unable to resolve version "120.0.0" for package "mylib"', @@ -386,7 +390,7 @@ describe('main', () => { install: jest.fn().mockResolvedValue(undefined), require: jest.fn().mockImplementation((codemodName: string) => { if (!codemodName.startsWith('@codeshift')) { - throw new Error('Attempted to fetch codemod from npm'); + throw Error('Attempted to fetch codemod from npm'); } return { @@ -473,13 +477,13 @@ describe('main', () => { it('should throw when preset is not found', async () => { expect.assertions(1); - try { - await main([mockPath], { - packages: 'mylib#does-not-exist', - parser: 'babel', - extensions: 'js', - }); - } catch (error) { + const [error] = await tryToCatch(main, [mockPath], { + packages: 'mylib#does-not-exist', + parser: 'babel', + extensions: 'js', + }); + + if (error) { // @ts-ignore expect(error.message).toMatch( 'Invalid preset provided to the --packages flag. Unable to resolve preset "does-not-exist" for package "mylib"', diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index 37d3be6ad..97c710419 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -39,7 +39,7 @@ export default async function main(paths: string[], flags: Flags) { if (flags.transform) { if (flags.transform.includes(',')) { - flags.transform.split(',').forEach(t => transforms.push(t.trim())); + for (const t of flags.transform.split(',')) transforms.push(t.trim()); } else { transforms.push(flags.transform); } @@ -70,7 +70,7 @@ export default async function main(paths: string[], flags: Flags) { `Found CodeshiftCommunity package: `, )} ${getCodeshiftPackageName(pkgName)}`, ); - } catch (error) { + } catch { spinner.warn( `${chalk.yellow( `Unable to locate CodeshiftCommunity package: `, @@ -83,23 +83,21 @@ export default async function main(paths: string[], flags: Flags) { spinner.succeed( `${chalk.green(`Found codeshift package: `)} ${pkgName}`, ); - } catch (error) { + } catch { spinner.warn( `${chalk.yellow(`Unable to locate codeshift package: `)} ${pkgName}`, ); } if (!codeshiftConfig && !remoteConfig) { - throw new Error( - `Unable to locate package from codeshift-community or NPM. -Make sure the package name "${pkgName}" is correct and try again.`, - ); + throw Error(`Unable to locate package from codeshift-community or NPM. +Make sure the package name "${pkgName}" is correct and try again.`); } const config: CodeshiftConfig = merge({}, remoteConfig, codeshiftConfig); if (!isValidConfig(config)) { - throw new Error( + throw Error( `Unable to locate a valid codeshift.config in package ${pkgName}`, ); } @@ -121,7 +119,7 @@ Make sure the package name "${pkgName}" is correct and try again.`, .map(id => id.substring(1)); // Validate transforms/presets - transformIds.forEach(id => { + for (const id of transformIds) { if (!semver.valid(semver.coerce(id.substring(1)))) { throw new InvalidUserInputError( `Invalid version provided to the --packages flag. Unable to resolve version "${id}" for package "${pkgName}". Please try: "[scope]/[package]@[version]" for example @mylib/mypackage@10.0.0`, @@ -133,15 +131,15 @@ Make sure the package name "${pkgName}" is correct and try again.`, `Invalid version provided to the --packages flag. Unable to resolve version "${id}" for package "${pkgName}"`, ); } - }); + } - presetIds.forEach(id => { + for (const id of presetIds) { if (!config.presets || !config.presets[id]) { throw new InvalidUserInputError( `Invalid preset provided to the --packages flag. Unable to resolve preset "${id}" for package "${pkgName}"`, ); } - }); + } // Get transform file paths if (config.transforms) { @@ -150,25 +148,25 @@ Make sure the package name "${pkgName}" is correct and try again.`, .filter(([key]) => semver.satisfies(key, `>=${transformIds[0]}`)) .forEach(([, path]) => transforms.push(path)); } else { - Object.entries(config.transforms as Record).forEach( - ([id, path]) => { - if (transformIds.includes(id)) { - transforms.push(path); - } - }, - ); + for (const [id, path] of Object.entries( + config.transforms as Record, + )) { + if (transformIds.includes(id)) { + transforms.push(path); + } + } } } // Get preset file paths if (config.presets) { - Object.entries(config.presets as Record).forEach( - ([id, path]) => { - if (presetIds.includes(id)) { - transforms.push(path); - } - }, - ); + for (const [id, path] of Object.entries( + config.presets as Record, + )) { + if (presetIds.includes(id)) { + transforms.push(path); + } + } } } } diff --git a/packages/fetcher/src/index.spec.ts b/packages/fetcher/src/index.spec.ts index e38f6bcd2..8ef925b08 100644 --- a/packages/fetcher/src/index.spec.ts +++ b/packages/fetcher/src/index.spec.ts @@ -166,7 +166,7 @@ describe('fetcher', () => { (mockPackageManager as unknown) as PluginManager, ), ).rejects.toEqual( - new Error(`Unable to locate package files for package: 'fake-package'`), + Error(`Unable to locate package files for package: 'fake-package'`), ); }); }); diff --git a/packages/fetcher/src/index.ts b/packages/fetcher/src/index.ts index a56416057..e54364279 100644 --- a/packages/fetcher/src/index.ts +++ b/packages/fetcher/src/index.ts @@ -5,7 +5,7 @@ import { PluginManager } from 'live-plugin-manager'; import { CodeshiftConfig } from '@codeshift/types'; function resolveConfigExport(pkg: any): CodeshiftConfig { - return pkg.default ? pkg.default : pkg; + return pkg.default || pkg; } export async function fetchConfig( @@ -22,7 +22,7 @@ export async function fetchConfig( // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require(matchedPath); return resolveConfigExport(pkg); - } catch (e) {} + } catch {} } return undefined; @@ -45,9 +45,7 @@ export async function fetchRemotePackage( const info = packageManager.getInfo(packageName); if (!info) { - throw new Error( - `Unable to locate package files for package: '${packageName}'`, - ); + throw Error(`Unable to locate package files for package: '${packageName}'`); } return await fetchConfig(info.location); diff --git a/packages/initializer/src/index.ts b/packages/initializer/src/index.ts index 776c1afcc..49e04e20f 100644 --- a/packages/initializer/src/index.ts +++ b/packages/initializer/src/index.ts @@ -77,15 +77,15 @@ function updateConfig( // @ts-ignore if (path.node.key.name !== key) return false; // @ts-ignore - const properties = path.node.value.properties; + const { properties } = path.node.value; // @ts-ignore - properties.forEach(property => { + for (const property of properties) { if (property.key.value === transformName) { - throw new Error( + throw Error( `Transform for ${packageName} ${transformName} already exists`, ); } - }); + } properties.push( b.property( @@ -150,7 +150,7 @@ export function initTransform( isReduced: boolean = false, ) { if (type === 'version' && !semver.valid(id)) { - throw new Error(`Provided version ${id} is not a valid semver version`); + throw Error(`Provided version ${id} is not a valid semver version`); } const basePath = path.join(targetPath, packageName.replace('/', '__')); @@ -162,7 +162,7 @@ export function initTransform( ); if (fs.existsSync(transformPath)) { - throw new Error(`Codemod for ${type} "${id}" already exists`); + throw Error(`Codemod for ${type} "${id}" already exists`); } fs.copySync( diff --git a/packages/initializer/template/src/codemod/transform.ts b/packages/initializer/template/src/codemod/transform.ts index 4f359544a..b9e571f7b 100644 --- a/packages/initializer/template/src/codemod/transform.ts +++ b/packages/initializer/template/src/codemod/transform.ts @@ -1,12 +1,6 @@ -import { API, FileInfo, Options } from 'jscodeshift'; - -export default function transformer( - file: FileInfo, - { jscodeshift: j }: API, - options: Options, -) { - const source = j(file.source); +import { FileInfo } from 'jscodeshift'; +export default function transformer(file: FileInfo) { /** * Early exit condition * ----- @@ -15,26 +9,5 @@ export default function transformer( * See this page for more information: * https://codeshiftcommunity.github.io/CodeshiftCommunity/docs/your-first-codemod#output */ - if (/* Some condition here */ true) { - return file.source; - } - - /** - * Codemod logic goes here 👇 - * ----- - * This is where the core logic for your codemod will go, - * consider grouping specific actions into 'motions' and running them in sequence - * - * See this page for more information: - * https://codeshiftcommunity.github.io/CodeshiftCommunity/docs/authoring#motions - */ - source.findVariableDeclarators('foo').renameTo('bar'); - - /** - * Return your modified AST here 👇 - * ----- - * This is where your modified AST will be transformed back into a string - * and written back to the file. - */ - return source.toSource(options.printOptions); + return file.source; } diff --git a/packages/publisher/src/changed.ts b/packages/publisher/src/changed.ts index 384de0e67..faa50f578 100644 --- a/packages/publisher/src/changed.ts +++ b/packages/publisher/src/changed.ts @@ -8,14 +8,14 @@ export function getAllPackages(path: string) { .map(dir => dir.name); } -export async function getChangedPackages(sinceRef: string) { +export async function getChangedPackages() { const git = simpleGit(); const eventMeta = JSON.parse(fs.readFileSync(sinceRef!, 'utf8')); try { await git.revparse(['--verify', eventMeta.before]); - } catch (e) { - throw new Error(`Invalid git ref detected in ref: "${eventMeta.before}"`); + } catch { + throw Error(`Invalid git ref detected in ref: "${eventMeta.before}"`); } const diff = await git.diff([ @@ -26,7 +26,7 @@ export async function getChangedPackages(sinceRef: string) { return diff .split('\n') - .filter(path => !!path && path.startsWith('community/')) + .filter(path => path?.startsWith('community/')) .map(path => path.split('/')[1]) .filter((path, i, self) => self.indexOf(path) === i); } diff --git a/packages/publisher/src/generate.ts b/packages/publisher/src/generate.ts index e23d9f36a..e8e298b5b 100644 --- a/packages/publisher/src/generate.ts +++ b/packages/publisher/src/generate.ts @@ -1,32 +1,6 @@ -import semver from 'semver'; import fs from 'fs-extra'; -// @ts-ignore -import RegClient from 'npm-registry-client'; import { getPackageJson } from '@codeshift/initializer'; -const client = new RegClient(); -const npmUri = 'https://registry.npmjs.org/'; - -function getPackageVersion(packageName: string) { - return new Promise((resolve, reject) => - client.get( - npmUri + packageName, - { timeout: 2000 }, - ( - error: any, - data: { 'dist-tags': { latest: string } }, - _raw: any, - res: { statusCode: number }, - ) => { - if (res.statusCode === 404) return resolve('0.0.0'); - if (error) reject(`Unexpected error when contacting NPM: ${error}`); - - resolve(data['dist-tags'].latest); - }, - ), - ); -} - export default async function generatePackages( sourcePath: string, targetPath: string, @@ -43,9 +17,6 @@ export default async function generatePackages( const packageName = `@codeshift/mod-${dir .replace('@', '') .replace('/', '__')}`; - const packageVersion = await getPackageVersion(packageName); - // We need to manually patch bump the codemod - const nextPackageVersion = semver.inc(packageVersion, 'patch'); const basePath = `${targetPath}/${dir}`; await fs.copy(`${sourcePath}/${dir}`, `${basePath}/src`); diff --git a/packages/publisher/src/publish.ts b/packages/publisher/src/publish.ts index a6f316f03..5eb37dad1 100644 --- a/packages/publisher/src/publish.ts +++ b/packages/publisher/src/publish.ts @@ -42,19 +42,20 @@ async function publish( 'npm', ['publish', pkg.dir, '--json', ...publishOpts], { - env: Object.assign({}, process.env, envOverride), + env: { + ...process.env, + ...envOverride, + }, }, ); const json = jsonParse(stdout.toString().replace(/[^{]*/, '')); if (json.error) { - throw new Error( - `An error occurred while publishing ${name}: ${json.error.code} + throw Error(`An error occurred while publishing ${name}: ${json.error.code} ${json.error.summary} ${json.error.detail ? '\n' + json.error.detail : ''} - `, - ); + `); } } @@ -81,6 +82,6 @@ export default function publishPackages( ); }), ).catch(error => { - throw new Error(error); + throw Error(error); }); } diff --git a/packages/test-utils/README.md b/packages/test-utils/README.md index 39dd6851d..cc02554a4 100755 --- a/packages/test-utils/README.md +++ b/packages/test-utils/README.md @@ -31,4 +31,5 @@ it('should wrap avatar in a tooltip', () => { }" `); }); + ``` diff --git a/packages/test-utils/src/apply-transform.ts b/packages/test-utils/src/apply-transform.ts index 515bc5fb0..f9588ee7a 100644 --- a/packages/test-utils/src/apply-transform.ts +++ b/packages/test-utils/src/apply-transform.ts @@ -14,7 +14,7 @@ export default function applyTransform( }, ) { // Handle ES6 modules using default export for the transform - const transformer = transform.default ? transform.default : transform; + const transformer = transform.default || transform; const output = transformer( { source: input }, { diff --git a/packages/utils/src/imports.ts b/packages/utils/src/imports.ts index 93344610a..9010fd03e 100644 --- a/packages/utils/src/imports.ts +++ b/packages/utils/src/imports.ts @@ -38,10 +38,8 @@ export function renameImportDeclaration( sourcePath: string, newSourcePath: string, ) { - getImportDeclaration(j, source, sourcePath).forEach( - importDeclaration => - (importDeclaration.node.source = j.stringLiteral(newSourcePath)), - ); + for (const importDeclaration of getImportDeclaration(j, source, sourcePath)) + importDeclaration.node.source = j.stringLiteral(newSourcePath); } export function getDefaultImportSpecifier( diff --git a/packages/utils/src/motions.ts b/packages/utils/src/motions.ts index 2c09daaff..4611565dc 100644 --- a/packages/utils/src/motions.ts +++ b/packages/utils/src/motions.ts @@ -5,5 +5,5 @@ export function applyMotions( source: ReturnType, motions: Function[], ) { - motions.forEach(motionTransformer => motionTransformer(j, source)); + for (const motionTransformer of motions) motionTransformer(j, source); } diff --git a/packages/validator/src/index.spec.ts b/packages/validator/src/index.spec.ts index a7142dd04..244f88b38 100644 --- a/packages/validator/src/index.spec.ts +++ b/packages/validator/src/index.spec.ts @@ -5,6 +5,8 @@ import fs from 'fs-extra'; import { fetchConfig } from '@codeshift/fetcher'; +import tryToCatch from 'try-to-catch'; + import { isValidPackageName, isValidConfig, @@ -170,34 +172,30 @@ Please make sure all presets are kebab case and contain no spaces or special cha it('should detect invalid package.json', async () => { expect.assertions(2); - { - (fs.readFile as jest.Mock).mockReturnValue(`{ - "name": "codeshift-package" - }`); + (fs.readFile as jest.Mock).mockReturnValue(`{ + "name": "codeshift-package" + }`); - try { - await isValidPackageJson('path/to/'); - } catch (error) { - // @ts-ignore - expect(error.message).toMatch( - 'No main entrypoint provided in package.json', - ); - } + const [error] = await tryToCatch(isValidPackageJson, 'path/to/'); + + if (error) { + // @ts-ignore + expect(error.message).toMatch( + 'No main entrypoint provided in package.json', + ); } - { - (fs.readFile as jest.Mock).mockReturnValue(`{ - "main": "dist/index.js" - }`); - - try { - await isValidPackageJson('path/to/'); - } catch (error) { - // @ts-ignore - expect(error.message).toMatch( - 'No package name provided in package.json', - ); - } + (fs.readFile as jest.Mock).mockReturnValue(`{ + "main": "dist/index.js" + }`); + + try { + await isValidPackageJson('path/to/'); + } catch (error) { + // @ts-ignore + expect(error.message).toMatch( + 'No package name provided in package.json', + ); } }); }); diff --git a/packages/validator/src/index.ts b/packages/validator/src/index.ts index ce7d040fe..d04e2292a 100644 --- a/packages/validator/src/index.ts +++ b/packages/validator/src/index.ts @@ -15,12 +15,12 @@ function hasValidPresets(config: CodeshiftConfig): boolean { if (!config.presets) return true; return Object.entries(config.presets).every(([key]) => - key.match(/^[0-9a-zA-Z\-]+$/), + key.match(/^[\dA-Za-z\-]+$/), ); } export function isValidPackageName(dir: string): boolean { - return !!dir.match(/^(@[a-z0-9-~][a-z0-9-._~]*__)?[a-z0-9-~][a-z0-9-._~]*$/); + return !!dir.match(/^(@[\da-z~-][\d._a-z~-]*__)?[\da-z~-][\d._a-z~-]*$/); } export function isValidConfig(config: CodeshiftConfig) { @@ -31,16 +31,16 @@ export async function isValidConfigAtPath(filePath: string) { const config = await fetchConfig(filePath); if (!config) { - throw new Error(`Unable to locate config file at path: ${filePath}`); + throw Error(`Unable to locate config file at path: ${filePath}`); } if (!hasValidTransforms(config)) { - throw new Error(`Invalid transform ids found for config at "${filePath}". + throw Error(`Invalid transform ids found for config at "${filePath}". Please make sure all transforms are identified by a valid semver version. ie 10.0.0`); } if (!hasValidPresets(config)) { - throw new Error(`Invalid preset ids found for config at "${filePath}". + throw Error(`Invalid preset ids found for config at "${filePath}". Please make sure all presets are kebab case and contain no spaces or special characters. ie sort-imports-by-scope`); } @@ -55,11 +55,11 @@ export async function isValidPackageJson(targetPath: string) { const packageJson = JSON.parse(packageJsonRaw); if (!packageJson.name) { - throw new Error('No package name provided in package.json'); + throw Error('No package name provided in package.json'); } if (!packageJson.main) { - throw new Error('No main entrypoint provided in package.json'); + throw Error('No main entrypoint provided in package.json'); } return true;