Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add commands to run tests depending on changed files #1078

Merged
merged 6 commits into from
Apr 3, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/guide/index.md
Expand Up @@ -118,6 +118,9 @@ You can specify additional CLI options like `--port` or `--https`. For a full li
| `--environment <env>` | Runner environment (default: `node`) |
| `--passWithNoTests` | Pass when no tests found |
| `--allowOnly` | Allow tests and suites that are marked as `only` (default: false in CI, true otherwise) |
| `--onlyChanged` | Run tests that are affected by the changed files (default: false)
| `--lastCommit` | Run tests that are affected by files changed in the last commit (default: false)'
| `--changedSince <commit/branch>` | Run tests that are affected by files changed since commit hash or branch
| `-h, --help` | Display available CLI options |

## Examples
Expand Down
3 changes: 3 additions & 0 deletions packages/vitest/src/node/cli.ts
Expand Up @@ -33,6 +33,9 @@ cli
.option('--environment <env>', 'runner environment (default: node)')
.option('--passWithNoTests', 'pass when no tests found')
.option('--allowOnly', 'Allow tests and suites that are marked as only (default: !process.env.CI)')
.option('--onlyChanged', 'Run tests that are affected by the changed files (default: false)')
.option('--lastCommit', 'Run tests that are affected by files changed in the last commit (default: false)')
.option('--changedSince <commit>', 'Run tests that are affected by files changed since commit hash or branch')
sheremet-va marked this conversation as resolved.
Show resolved Hide resolved
.help()

cli
Expand Down
5 changes: 5 additions & 0 deletions packages/vitest/src/node/config.ts
Expand Up @@ -134,5 +134,10 @@ export function resolveConfig(
if (!resolved.reporters.length)
resolved.reporters.push('default')

if (resolved.changedSince || resolved.lastCommit || resolved.onlyChanged) {
resolved.onlyChanged = true
resolved.passWithNoTests = true
}

return resolved
}
14 changes: 14 additions & 0 deletions packages/vitest/src/node/core.ts
Expand Up @@ -15,6 +15,7 @@ import type { WorkerPool } from './pool'
import { StateManager } from './state'
import { resolveConfig } from './config'
import { printError } from './error'
import { VitestGit } from './git'

const WATCHER_DEBOUNCE = 100
const CLOSE_TIMEOUT = 1_000
Expand Down Expand Up @@ -156,6 +157,19 @@ export class Vitest {
}

async filterTestsBySource(tests: string[]) {
if (this.config.onlyChanged && !this.config.related) {
const vitestGit = new VitestGit()
const root = await vitestGit.getRoot(this.config.root)
if (!root) {
this.error(c.red('Could not find Git root. Have you initialized git with `git init`?\n'))
process.exit(1)
}
this.config.related = await vitestGit.findChangedFiles(root, {
changedSince: this.config.changedSince,
lastCommit: this.config.lastCommit,
})
}

const related = this.config.related
if (!related)
return tests
Expand Down
95 changes: 95 additions & 0 deletions packages/vitest/src/node/git.ts
@@ -0,0 +1,95 @@
import { resolve } from 'pathe'
import { execa } from 'execa'
import type { ExecaReturnValue } from 'execa'
antfu marked this conversation as resolved.
Show resolved Hide resolved

export interface GitOptions {
lastCommit?: boolean
changedSince?: string
}

export class VitestGit {
private async resolveFilesWithGitCommand(
args: string[],
cwd: string,
): Promise<string[]> {
let result: ExecaReturnValue

try {
result = await execa('git', args, { cwd })
}
catch (e: any) {
e.message = e.stderr

throw e
}

return result.stdout
.split('\n')
.filter(s => s !== '')
.map(changedPath => resolve(cwd, changedPath))
}

async findChangedFiles(cwd: string, options: GitOptions) {
const changedSince = options.changedSince

if (options && options.lastCommit) {
return this.resolveFilesWithGitCommand(
['show', '--name-only', '--pretty=format:', 'HEAD', '--'],
cwd,
)
}
if (changedSince) {
const [committed, staged, unstaged] = await Promise.all([
this.resolveFilesWithGitCommand(
['diff', '--name-only', `${changedSince}...HEAD`, '--'],
cwd,
),
this.resolveFilesWithGitCommand(
['diff', '--cached', '--name-only', '--'],
cwd,
),
this.resolveFilesWithGitCommand(
[
'ls-files',
'--other',
'--modified',
'--exclude-standard',
'--',
],
cwd,
),
])
return [...committed, ...staged, ...unstaged]
}
const [staged, unstaged] = await Promise.all([
this.resolveFilesWithGitCommand(
['diff', '--cached', '--name-only', '--'],
cwd,
),
this.resolveFilesWithGitCommand(
[
'ls-files',
'--other',
'--modified',
'--exclude-standard',
'--',
],
cwd,
),
])
return [...staged, ...unstaged]
}

async getRoot(cwd: string) {
const options = ['rev-parse', '--show-cdup']

try {
const result = await execa('git', options, { cwd })

return resolve(cwd, result.stdout)
}
catch {
return null
}
}
}
20 changes: 20 additions & 0 deletions packages/vitest/src/types/config.ts
Expand Up @@ -329,6 +329,26 @@ export interface UserConfig extends InlineConfig {
* @default 'test'
*/
mode?: string

/**
* Runs tests that are affected by the changes in the repository
* Requires initialized git repository
* @default false
*/
onlyChanged?: boolean

/**
* Runs tests that are affected by the changes in the last commit
* Requires initialized git repository
* @default false
*/
lastCommit?: boolean

/**
* Runs tests that are affected by the changes since the specified branch or commit hash
sheremet-va marked this conversation as resolved.
Show resolved Hide resolved
* Requires initialized git repository
*/
changedSince?: string
}

export interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'related' | 'api' | 'reporters'> {
Expand Down