Skip to content

Commit

Permalink
refactor: remove barrel utils (#6716)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Oct 15, 2024
1 parent 0791853 commit c0a2f3f
Show file tree
Hide file tree
Showing 58 changed files with 212 additions and 379 deletions.
2 changes: 2 additions & 0 deletions packages/runner/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export {
hasTests,
hasFailed,
getNames,
getFullName,
getTestName,
} from './tasks'
export { createChainable, type ChainableFunction } from './chain'
export { limitConcurrency } from './limit-concurrency'
8 changes: 8 additions & 0 deletions packages/runner/src/utils/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,11 @@ export function getNames(task: Task): string[] {

return names
}

export function getFullName(task: Task, separator = ' > '): string {
return getNames(task).join(separator)
}

export function getTestName(task: Task, separator = ' > '): string {
return getNames(task).slice(1).join(separator)
}
54 changes: 54 additions & 0 deletions packages/utils/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,3 +290,57 @@ export function isNegativeNaN(val: number): boolean {

return isNegative
}

function toString(v: any) {
return Object.prototype.toString.call(v)
}

function isPlainObject(val: any): val is object {
return (
toString(val) === '[object Object]'
&& (!val.constructor || val.constructor.name === 'Object')
)
}

function isMergeableObject(item: any): item is object {
return isPlainObject(item) && !Array.isArray(item)
}

/**
* Deep merge :P
*
* Will merge objects only if they are plain
*
* Do not merge types - it is very expensive and usually it's better to case a type here
*/
export function deepMerge<T extends object = object>(
target: T,
...sources: any[]
): T {
if (!sources.length) {
return target as any
}

const source = sources.shift()
if (source === undefined) {
return target as any
}

if (isMergeableObject(target) && isMergeableObject(source)) {
(Object.keys(source) as (keyof T)[]).forEach((key) => {
const _source = source as T
if (isMergeableObject(_source[key])) {
if (!target[key]) {
target[key] = {} as any
}

deepMerge(target[key] as any, _source[key])
}
else {
target[key] = _source[key] as any
}
})
}

return deepMerge(target, ...sources)
}
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export {
isNegativeNaN,
createSimpleStackTrace,
toArray,
deepMerge,
} from './helpers'
export type { DeferPromise } from './helpers'

Expand Down
4 changes: 3 additions & 1 deletion packages/vitest/src/api/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import type { WebSocket } from 'ws'
import { WebSocketServer } from 'ws'
import type { ViteDevServer } from 'vite'
import type { File, TaskResultPack } from '@vitest/runner'
import { isPrimitive, noop } from '@vitest/utils'
import { API_PATH } from '../constants'
import type { Vitest } from '../node/core'
import type { Awaitable, ModuleGraphData, UserConsoleLog } from '../types/general'
import type { Reporter } from '../node/types/reporter'
import { getModuleGraph, isPrimitive, noop, stringifyReplace } from '../utils'
import { getModuleGraph } from '../utils/graph'
import { stringifyReplace } from '../utils/serialization'
import { parseErrorStacktrace } from '../utils/source-map'
import type { SerializedTestSpecification } from '../runtime/types/utils'
import type {
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/chai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
setState,
} from '@vitest/expect'
import type { Assertion, ExpectStatic, MatcherState } from '@vitest/expect'
import { getTestName } from '../../utils/tasks'
import { getTestName } from '@vitest/runner/utils'
import { getCurrentEnvironment, getWorkerState } from '../../runtime/utils'
import { createExpectPoll } from './poll'

Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/chai/poll.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as chai from 'chai'
import type { Assertion, ExpectStatic } from '@vitest/expect'
import { getSafeTimers } from '@vitest/utils'
import { getWorkerState } from '../../utils'
import { getWorkerState } from '../../runtime/utils'

// these matchers are not supported because they don't make sense with poll
const unsupported = [
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/mock/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type {
InstalledClock,
} from '@sinonjs/fake-timers'
import { withGlobal } from '@sinonjs/fake-timers'
import { isChildProcess } from '../../utils/base'
import { isChildProcess } from '../../runtime/utils'
import { RealDate, mockDate, resetDate } from './date'

export class FakeTimers {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment'
import { getWorkerState } from '../../../utils'
import { getWorkerState } from '../../../runtime/utils'

export class VitestNodeSnapshotEnvironment extends NodeSnapshotEnvironment {
getHeader(): string {
Expand Down
4 changes: 1 addition & 3 deletions packages/vitest/src/integrations/vi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import { parseSingleStack } from '../utils/source-map'
import type { VitestMocker } from '../runtime/mocker'
import type { RuntimeOptions, SerializedConfig } from '../runtime/config'
import type { MockFactoryWithHelper, MockOptions } from '../types/mocker'
import { getWorkerState } from '../runtime/utils'
import { resetModules, waitForImportsToResolve } from '../utils/modules'
import { isChildProcess } from '../utils/base'
import { getWorkerState, isChildProcess, resetModules, waitForImportsToResolve } from '../runtime/utils'
import { FakeTimers } from './mock/timers'
import type {
MaybeMocked,
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/cache/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { resolve } from 'pathe'
import { slash } from '../../utils'
import { slash } from '@vitest/utils'
import { hash } from '../hash'
import { FilesStatsCache } from './files'
import { ResultsCache } from './results'
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/cli/cac.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { normalize } from 'pathe'
import cac, { type CAC, type Command } from 'cac'
import c from 'tinyrainbow'
import { toArray } from '@vitest/utils'
import { version } from '../../../package.json' with { type: 'json' }
import { toArray } from '../../utils/base'
import type { VitestRunMode } from '../types/config'
import type { CliOptions } from './cli-api'
import type { CLIOption, CLIOptions as CLIOptionsConfig } from './cli-config'
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/cli/cli-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { mkdirSync, writeFileSync } from 'node:fs'
import { dirname, relative, resolve } from 'pathe'
import type { UserConfig as ViteUserConfig } from 'vite'
import type { File, Suite, Task } from '@vitest/runner'
import { getNames, getTests } from '@vitest/runner/utils'
import { CoverageProviderMap } from '../../integrations/coverage'
import type { environments } from '../../integrations/env'
import { createVitest } from '../create'
import { registerConsoleShortcuts } from '../stdin'
import type { Vitest, VitestOptions } from '../core'
import { FilesNotFoundError, GitNotFoundError } from '../errors'
import { getNames, getTests } from '../../utils'
import type { UserConfig, VitestEnvironment, VitestRunMode } from '../types/config'
import type { WorkspaceSpec } from '../pool'

Expand Down
3 changes: 2 additions & 1 deletion packages/vitest/src/node/config/resolveConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { resolveModule } from 'local-pkg'
import { normalize, relative, resolve } from 'pathe'
import c from 'tinyrainbow'
import type { ResolvedConfig as ResolvedViteConfig } from 'vite'
import { toArray } from '@vitest/utils'
import { isCI, stdProvider } from '../../utils/env'
import type {
ApiConfig,
ResolvedConfig,
Expand All @@ -15,7 +17,6 @@ import {
extraInlineDeps,
} from '../../constants'
import { benchmarkConfigDefaults, configDefaults } from '../../defaults'
import { isCI, stdProvider, toArray } from '../../utils'
import type { BuiltinPool, ForksOptions, PoolOptions, ThreadsOptions } from '../types/pool-options'
import { getWorkersCountByPercentage } from '../../utils/workers'
import { VitestCache } from '../cache'
Expand Down
4 changes: 3 additions & 1 deletion packages/vitest/src/node/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@ import { SnapshotManager } from '@vitest/snapshot/manager'
import type { CancelReason, File, TaskResultPack } from '@vitest/runner'
import { ViteNodeServer } from 'vite-node/server'
import type { defineWorkspace } from 'vitest/config'
import { noop, slash, toArray } from '@vitest/utils'
import { getTasks, hasFailed } from '@vitest/runner/utils'
import { version } from '../../package.json' with { type: 'json' }
import { getTasks, hasFailed, noop, slash, toArray, wildcardPatternToRegExp } from '../utils'
import { getCoverageProvider } from '../integrations/coverage'
import { workspacesFiles as workspaceFiles } from '../constants'
import { WebSocketReporter } from '../api/setup'
import type { SerializedCoverageConfig } from '../runtime/config'
import type { ArgumentsType, OnServerRestartHandler, ProvidedContext, UserConsoleLog } from '../types/general'
import { distDir } from '../paths'
import { wildcardPatternToRegExp } from '../utils/base'
import type { ProcessPool, WorkspaceSpec } from './pool'
import { createPool, getFilePoolName } from './pool'
import { createBenchmarkReporters, createReporters } from './reporters/utils'
Expand Down
5 changes: 2 additions & 3 deletions packages/vitest/src/node/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,18 @@ import { normalize, relative } from 'pathe'
import c from 'tinyrainbow'
import cliTruncate from 'cli-truncate'
import type { ErrorWithDiff, ParsedStack } from '@vitest/utils'
import { inspect } from '@vitest/utils'
import { inspect, isPrimitive } from '@vitest/utils'
import {
lineSplitRE,
positionToOffset,
} from '../utils/source-map'
import { F_POINTER } from '../utils/figures'
import { TypeCheckError } from '../typecheck/typechecker'
import { isPrimitive } from '../utils'
import type { Vitest } from './core'
import { divider } from './reporters/renderers/utils'
import type { ErrorOptions } from './logger'
import { Logger } from './logger'
import type { WorkspaceProject } from './workspace'
import { F_POINTER } from './reporters/renderers/figures'

interface PrintErrorOptions {
type?: string
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import c from 'tinyrainbow'
import { parseErrorStacktrace } from '@vitest/utils/source-map'
import type { Task } from '@vitest/runner'
import type { ErrorWithDiff } from '@vitest/utils'
import { toArray } from '@vitest/utils'
import type { TypeCheckError } from '../typecheck/typechecker'
import { toArray } from '../utils'
import { highlightCode } from '../utils/colors'
import { divider } from './reporters/renderers/utils'
import { RandomSequencer } from './sequencers/RandomSequencer'
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/plugins/cssEnabler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { relative } from 'pathe'
import type { Plugin as VitePlugin } from 'vite'
import { toArray } from '@vitest/utils'
import { generateCssFilenameHash } from '../../integrations/css/css-modules'
import type { CSSModuleScopeStrategy, ResolvedConfig } from '../types/config'
import { toArray } from '../../utils'

const cssLangs = '\\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)(?:$|\\?)'
const cssLangRE = new RegExp(cssLangs)
Expand Down
17 changes: 13 additions & 4 deletions packages/vitest/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import type { UserConfig as ViteConfig, Plugin as VitePlugin } from 'vite'
import { relative } from 'pathe'
import { configDefaults, coverageConfigDefaults } from '../../defaults'
import type { ResolvedConfig, UserConfig } from '../types/config'
import {
deepMerge,
notNullish,
removeUndefinedValues,
toArray,
} from '../../utils'
} from '@vitest/utils'
import { configDefaults, coverageConfigDefaults } from '../../defaults'
import type { ResolvedConfig, UserConfig } from '../types/config'
import { resolveApiServerConfig } from '../config/resolveConfig'
import { Vitest } from '../core'
import { generateScopedClassName } from '../../integrations/css/css-modules'
Expand Down Expand Up @@ -266,3 +265,13 @@ export async function VitestPlugin(
NormalizeURLPlugin(),
].filter(notNullish)
}
function removeUndefinedValues<T extends Record<string, any>>(
obj: T,
): T {
for (const key in Object.keys(obj)) {
if (obj[key] === undefined) {
delete obj[key]
}
}
return obj
}
2 changes: 1 addition & 1 deletion packages/vitest/src/node/plugins/workspace.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { existsSync, readFileSync } from 'node:fs'
import { basename, dirname, relative, resolve } from 'pathe'
import type { UserConfig as ViteConfig, Plugin as VitePlugin } from 'vite'
import { deepMerge } from '@vitest/utils'
import { configDefaults } from '../../defaults'
import { generateScopedClassName } from '../../integrations/css/css-modules'
import { deepMerge } from '../../utils/base'
import type { WorkspaceProject } from '../workspace'
import type { ResolvedConfig, UserWorkspaceConfig } from '../types/config'
import { CoverageTransform } from './coverageTransform'
Expand Down
3 changes: 2 additions & 1 deletion packages/vitest/src/node/pools/forks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import EventEmitter from 'node:events'
import { Tinypool } from 'tinypool'
import type { TinypoolChannel, Options as TinypoolOptions } from 'tinypool'
import { createBirpc } from 'birpc'
import { resolve } from 'pathe'
import type { PoolProcessOptions, ProcessPool, RunWithFiles } from '../pool'
import type { WorkspaceProject } from '../workspace'
import { envsOrder, groupFilesByEnv } from '../../utils/test-helpers'
import { wrapSerializableConfig } from '../../utils/config-helpers'
import { groupBy, resolve } from '../../utils'
import { groupBy } from '../../utils/base'
import type { SerializedConfig } from '../types/config'
import type { RunnerRPC, RuntimeRPC } from '../../types/rpc'
import type { Vitest } from '../core'
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/pools/threads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Tinypool from 'tinypool'
import { resolve } from 'pathe'
import type { PoolProcessOptions, ProcessPool, RunWithFiles } from '../pool'
import { envsOrder, groupFilesByEnv } from '../../utils/test-helpers'
import { AggregateError, groupBy } from '../../utils/base'
import { groupBy } from '../../utils/base'
import type { WorkspaceProject } from '../workspace'
import type { SerializedConfig } from '../types/config'
import type { RunnerRPC, RuntimeRPC } from '../../types/rpc'
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/pools/typecheck.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { DeferPromise } from '@vitest/utils'
import { createDefer } from '@vitest/utils'
import { hasFailed } from '@vitest/runner/utils'
import type { TypecheckResults } from '../../typecheck/typechecker'
import { Typechecker } from '../../typecheck/typechecker'
import { groupBy } from '../../utils/base'
import { hasFailed } from '../../utils/tasks'
import type { Vitest } from '../core'
import type { ProcessPool, WorkspaceSpec } from '../pool'
import type { WorkspaceProject } from '../workspace'
Expand Down
1 change: 0 additions & 1 deletion packages/vitest/src/node/pools/vmForks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import Tinypool from 'tinypool'
import { rootDir } from '../../paths'
import type { PoolProcessOptions, ProcessPool, RunWithFiles } from '../pool'
import { groupFilesByEnv } from '../../utils/test-helpers'
import { AggregateError } from '../../utils/base'
import type { WorkspaceProject } from '../workspace'
import { getWorkerMemoryLimit, stringToBytes } from '../../utils/memory-limit'
import { wrapSerializableConfig } from '../../utils/config-helpers'
Expand Down
1 change: 0 additions & 1 deletion packages/vitest/src/node/pools/vmThreads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import Tinypool from 'tinypool'
import { rootDir } from '../../paths'
import type { PoolProcessOptions, ProcessPool, RunWithFiles } from '../pool'
import { groupFilesByEnv } from '../../utils/test-helpers'
import { AggregateError } from '../../utils/base'
import type { WorkspaceProject } from '../workspace'
import { getWorkerMemoryLimit, stringToBytes } from '../../utils/memory-limit'
import type { ResolvedConfig, SerializedConfig } from '../types/config'
Expand Down
21 changes: 6 additions & 15 deletions packages/vitest/src/node/reporters/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,14 @@ import c from 'tinyrainbow'
import { parseStacktrace } from '@vitest/utils/source-map'
import { relative } from 'pathe'
import type { File, Task, TaskResultPack } from '@vitest/runner'
import {
getFullName,
getSuites,
getTestName,
getTests,
hasFailed,
hasFailedSnapshot,
isCI,
isDeno,
isNode,
relativePath,
toArray,
} from '../../utils'
import { toArray } from '@vitest/utils'
import { getFullName, getSuites, getTestName, getTests, hasFailed } from '@vitest/runner/utils'
import { isCI, isDeno, isNode } from '../../utils/env'
import type { Vitest } from '../core'
import { F_POINTER, F_RIGHT } from '../../utils/figures'
import type { Reporter } from '../types/reporter'
import type { ErrorWithDiff, UserConsoleLog } from '../../types/general'
import { hasFailedSnapshot } from '../../utils/tasks'
import { F_POINTER, F_RIGHT } from './renderers/figures'
import {
countTestErrors,
divider,
Expand Down Expand Up @@ -89,7 +80,7 @@ export abstract class BaseReporter implements Reporter {
}

relative(path: string) {
return relativePath(this.ctx.config.root, path)
return relative(this.ctx.config.root, path)
}

onFinished(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import fs from 'node:fs'
import c from 'tinyrainbow'
import * as pathe from 'pathe'
import type { File, TaskResultPack } from '@vitest/runner'
import { getFullName, getTasks } from '@vitest/runner/utils'
import type { UserConsoleLog } from '../../../../types/general'
import { BaseReporter } from '../../base'
import { getFullName, getTasks } from '../../../../utils'
import { getStateSymbol } from '../../renderers/utils'
import type { BenchmarkResult } from '../../../../runtime/types/benchmark'
import {
Expand Down
Loading

0 comments on commit c0a2f3f

Please sign in to comment.