Skip to content

Commit

Permalink
feat(cli): adds a cli tool to migrate old config
Browse files Browse the repository at this point in the history
TSJest migrates the config on the fly to stay compatible with older
versions, but it generates warning. This adds a cli tool which users can
call to migrate their configuraton easily without opening an issue :D
  • Loading branch information
huafu committed Sep 3, 2018
1 parent bb0c06e commit 714f5f0
Show file tree
Hide file tree
Showing 12 changed files with 361 additions and 42 deletions.
3 changes: 3 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node

require('./dist/cli')
31 changes: 25 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "23.10.0-beta.2",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": "cli.js",
"description": "A preprocessor with sourcemap support to help use Typescript with Jest",
"scripts": {
"prebuild": "node scripts/clean-dist.js",
Expand Down Expand Up @@ -63,7 +64,8 @@
"make-error": "^1.3.5",
"mkdirp": "^0.5.1",
"semver": "^5.5.1",
"tslib": "^1.9.3"
"tslib": "^1.9.3",
"yargs-parser": "^10.1.0"
},
"peerDependencies": {
"babel-jest": ">=22 <24",
Expand All @@ -86,6 +88,7 @@
"@types/mkdirp": "^0.5.2",
"@types/node": "^10.9.4",
"@types/semver": "^5.5.0",
"@types/yargs": "^11.1.1",
"conventional-changelog-cli": "^2.0.5",
"cross-spawn": "^6.0.5",
"doctoc": "^1.3.1",
Expand Down
167 changes: 167 additions & 0 deletions src/cli/config/migrate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import { Logger } from 'bs-logger'
import stringifyJson from 'fast-json-stable-stringify'
import { existsSync } from 'fs'
import { stringify as stringifyJson5 } from 'json5'
import { basename, join } from 'path'
import { Arguments } from 'yargs'

import { CliCommand } from '..'
import { createJestPreset } from '../../config/create-jest-preset'
import { backportJestConfig } from '../../util/backports'

export const run: CliCommand = async (args: Arguments, logger: Logger) => {
const file = args._[0]
const filePath = join(process.cwd(), file)
if (!existsSync(filePath)) {
throw new Error(`Configuration file ${file} does not exists.`)
}
const name = basename(file)
const isPackage = name === 'package.json'
if (!/\.(js|json)$/.test(name)) {
throw new TypeError(`Configuration file ${file} must be a JavaScript or JSON file.`)
}
let actualConfig: jest.InitialOptions = require(filePath)
if (isPackage) {
actualConfig = (actualConfig as any).jest
}
if (!actualConfig) actualConfig = {}

// migrate
// first we backport our options
const migratedConfig = backportJestConfig(logger, actualConfig)
// then we check if we can use `preset`
if (!migratedConfig.preset && args.jestPreset) {
migratedConfig.preset = 'ts-jest'
} else if (!args.jestPreset && migratedConfig.preset === 'ts-jest') {
delete migratedConfig.preset
}
const usesPreset = migratedConfig.preset === 'ts-jest'
const presets = createJestPreset({ allowJs: args.allowJs })

// check the extensions
if (migratedConfig.moduleFileExtensions && migratedConfig.moduleFileExtensions.length && usesPreset) {
const presetValue = dedupSort(presets.moduleFileExtensions).join('::')
const migratedValue = dedupSort(migratedConfig.moduleFileExtensions).join('::')
if (presetValue === migratedValue) {
delete migratedConfig.moduleFileExtensions
}
}
// check the testMatch
if (migratedConfig.testMatch && migratedConfig.testMatch.length && usesPreset) {
const presetValue = dedupSort(presets.testMatch).join('::')
const migratedValue = dedupSort(migratedConfig.testMatch).join('::')
if (presetValue === migratedValue) {
delete migratedConfig.testMatch
}
}

// migrate the transform
if (migratedConfig.transform) {
Object.keys(migratedConfig.transform).forEach(key => {
const val = (migratedConfig.transform as any)[key]
if (typeof val === 'string' && /\/?ts-jest(?:\/preprocessor\.js)?$/.test(val)) {
// tslint:disable-next-line:semicolon
;(migratedConfig.transform as any)[key] = 'ts-jest'
}
})
}
// check if it's the same as the preset's one
if (
usesPreset &&
migratedConfig.transform &&
stringifyJson(migratedConfig.transform) === stringifyJson(presets.transform)
) {
delete migratedConfig.transform
}

// cleanup
cleanupConfig(actualConfig)
cleanupConfig(migratedConfig)
const before = stringifyJson(actualConfig)
const after = stringifyJson(migratedConfig)
if (after === before) {
process.stderr.write(`
No migration needed for given Jest configuration
`)
return
}

const stringify = /\.json$/.test(file) ? JSON.stringify : stringifyJson5
const footNotes: string[] = []

// if we are using preset, inform the user that he might be able to remove some section(s)
// we couldn't check for equality
// if (usesPreset && migratedConfig.testMatch) {
// footNotes.push(`
// I couldn't check if your "testMatch" value is the same as mine which is: ${stringify(
// presets.testMatch,
// undefined,
// ' ',
// )}
// If it is the case, you can safely remove the "testMatch" from what I've migrated.
// `)
// }
if (usesPreset && migratedConfig.transform) {
footNotes.push(`
I couldn't check if your "transform" value is the same as mine which is: ${stringify(
presets.transform,
undefined,
' ',
)}
If it is the case, you can safely remove the "transform" from what I've migrated.
`)
}

// output new config
process.stderr.write(`
Migrated Jest configuration:
`)
process.stdout.write(`${stringify(migratedConfig, undefined, ' ')}\n`)
process.stderr.write(`
${footNotes.join('\n')}
`)
}

function cleanupConfig(config: jest.InitialOptions): void {
if (config.globals) {
if ((config as any).globals['ts-jest'] && Object.keys((config as any).globals['ts-jest']).length === 0) {
delete (config as any).globals['ts-jest']
}
if (Object.keys(config.globals).length === 0) {
delete config.globals
}
}
if (config.transform && Object.keys(config.transform).length === 0) {
delete config.transform
}
if (config.moduleFileExtensions) {
config.moduleFileExtensions = dedupSort(config.moduleFileExtensions)
if (config.moduleFileExtensions.length === 0) delete config.moduleFileExtensions
}
if (config.testMatch) {
config.testMatch = dedupSort(config.testMatch)
if (config.testMatch.length === 0) delete config.testMatch
}
}

function dedupSort(arr: any[]) {
return arr
.filter((s, i, a) => a.findIndex(e => s.toString() === e.toString()) === i)
.sort((a, b) => (a.toString() > b.toString() ? 1 : a.toString() < b.toString() ? -1 : 0))
}

export const help: CliCommand = async () => {
process.stdout.write(`
Usage:
ts-jest config:migrate [options] <config-file>
Arguments:
<config-file> Can be a js or json Jest config file. If it is a
package.json file, the configuration will be read from
the "jest" property.
Options:
--allow-js TSJest will be used to process JS files as well
--no-jest-preset Disable the use of Jest presets
`)
}
17 changes: 17 additions & 0 deletions src/cli/help.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Arguments } from 'yargs'

export const run = async (_: Arguments) => {
process.stdout.write(`
Usage:
ts-jest command [options] [...args]
Commands:
help [command] Show this help, or help about a command
config:migrate Migrates a given Jest configuration
Example:
ts-jest help config:migrate
`)
}

export { run as help }
41 changes: 41 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { LogContexts, Logger } from 'bs-logger'
import { Arguments } from 'yargs'
import yargsParser from 'yargs-parser'

import { rootLogger } from '../util/logger'

const VALID_COMMANDS = ['help', 'config:migrate']

// tslint:disable-next-line:prefer-const
let [, , ...args] = process.argv

const logger = rootLogger.child({ [LogContexts.namespace]: 'cli', [LogContexts.application]: 'ts-jest' })

const parsedArgv = yargsParser(args, {
boolean: ['dryRun', 'jestPreset', 'allowJs', 'diff'],
count: ['verbose'],
alias: { verbose: ['v'] },
default: { dryRun: false, jestPreset: true, allowJs: false, verbose: 0, diff: false },
})
let command = parsedArgv._.shift() as string
const isHelp = command === 'help'
if (isHelp) command = parsedArgv._.shift() as string

if (!VALID_COMMANDS.includes(command)) command = 'help'

export type CliCommand = (argv: Arguments, logger: Logger) => Promise<void>

// tslint:disable-next-line:no-var-requires
const { run, help }: { run: CliCommand; help: CliCommand } = require(`./${command.replace(/:/g, '/')}`)

const cmd = isHelp && command !== 'help' ? help : run

cmd(parsedArgv, logger).then(
() => {
process.exit(0)
},
(err: Error) => {
logger.fatal(err.message)
process.exit(1)
},
)
18 changes: 11 additions & 7 deletions src/config/create-jest-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,21 @@ const defaults = jestConfig.defaults || {
moduleFileExtensions: ['js', 'json', 'jsx', 'node'],
}

// TODO: find out if tsconfig that we'll use contains `allowJs`
// and change the transform so that it also uses ts-jest for js files

export function createJestPreset({ allowJs = false }: CreateJestPresetOptions = {}) {
export function createJestPreset(
{ allowJs = false }: CreateJestPresetOptions = {},
from: jest.InitialOptions = defaults,
) {
logger.debug({ allowJs }, 'creating jest presets', allowJs ? 'handling' : 'not handling', 'JavaScript files')
return {
transform: {
...defaults.transform,
...from.transform,
[allowJs ? '^.+\\.[tj]sx?$' : '^.+\\.tsx?$']: 'ts-jest',
},
testMatch: [...defaults.testMatch, '**/__tests__/**/*.ts?(x)', '**/?(*.)+(spec|test).ts?(x)'],
moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
testMatch: dedup([...from.testMatch, '**/__tests__/**/*.ts?(x)', '**/?(*.)+(spec|test).ts?(x)']),
moduleFileExtensions: dedup([...from.moduleFileExtensions, 'ts', 'tsx']),
}
}

function dedup(array: string[]): string[] {
return array.filter((e, i, a) => a.indexOf(e) === i)
}
5 changes: 5 additions & 0 deletions src/shims.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,8 @@ declare module 'jest-config' {
}

declare module 'babel-core/lib/transformation/file'

declare module 'yargs-parser' {
import yargs from 'yargs'
export = yargs.parse
}
Loading

0 comments on commit 714f5f0

Please sign in to comment.