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

fix: Add better version detection #125

Merged
merged 2 commits into from
Feb 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 62 additions & 19 deletions src/pure/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import * as path from 'path'
import { chunksToLinesAsync } from '@rauschma/stringio'
import { existsSync } from 'fs-extra'
import { log } from '../log'
import { isWindows } from './platform'

export function getVitestPath(projectRoot: string): string | undefined {
Expand Down Expand Up @@ -80,31 +81,73 @@ export interface Cmd {
args: string[]
}

export async function getVitestVersion(
vitestCommand?: Cmd,
env?: Record<string, string>,
): Promise<string> {
let child
if (vitestCommand == null) {
child = spawn('npx', ['vitest', '-v'], {
stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, ...env },
})
}
else {
child = spawn(process.execPath, [vitestCommand.cmd, ...vitestCommand.args, '-v'], {
stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, ...env },
})
}
/**
* Try to extract a vitest version from the output of the command
*
* @returns the version, or undefined if not found
*/
export const spawnVitestVersion = async (
command: string,
args: string[],
env?: Record<string, string | undefined>,
): Promise<string | undefined> => {
log.info(`Trying to get vitest version from ${command} ${args.join(' ')}...`)

const child = spawn(command, args, {
stdio: ['ignore', 'pipe', 'pipe'],
env,
})

child.on('error', () => {
log.info('Command not found')
})

// eslint-disable-next-line no-unreachable-loop
for await (const line of chunksToLinesAsync(child.stdout)) {
zxch3n marked this conversation as resolved.
Show resolved Hide resolved
child.kill()
return line.match(/vitest\/(\d+.\d+.\d+)/)![1]
log.info(line)

const match = line.match(/vitest\/(\d+.\d+.\d+)/)

if (match && match.length > 0)
return match[1]
}
}

/**
* Try to detect the vitest version by first spawning the command directly, then by spawning the command with the
* execPath of the current Node process (useful when using a Node installed by a version manager such as nvm).
*
* @see https://github.com/electron/electron/issues/3627#issuecomment-793052457
* @returns the version
* @throws an error if the version cannot be detected
*/
export const detectVitestVersion = async (command: string, args: string[], envs: Record<string, string | undefined>): Promise<string > => {
// Try to spawn the command directly
const version = await spawnVitestVersion(command, args, envs)

if (version !== undefined)
return version

// When using a Node installed by a version manager, we need to pass the execPath to spawn
const versionExecPath = await spawnVitestVersion(process.execPath, [command, ...args], envs)

if (versionExecPath !== undefined)
return versionExecPath

throw new Error('Cannot get vitest version. Please open an issue at https://github.com/vitest-dev/vscode/issues and join the logs above.')
}

export async function getVitestVersion(
vitestCommand?: Cmd,
env?: Record<string, string | undefined>,
): Promise<string | undefined> {
const envs = { ...process.env, ...env }

if (vitestCommand == null)
return await detectVitestVersion('npx', ['vitest', '-v'], envs)

throw new Error(`Cannot get vitest version from "${JSON.stringify(vitestCommand)}"`)
return await detectVitestVersion(vitestCommand.cmd, [...vitestCommand.args, '-v'], envs)
}

export function isNodeAvailable(
Expand Down
46 changes: 46 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { spawnVitestVersion } from '../src/pure/utils'

afterEach(() => {
vi.restoreAllMocks()
})

// Mock vscode ("pure" modules aren't quite pure)
vi.mock('vscode', () => {
return {
default: { myDefaultKey: vi.fn() },
namedExport: vi.fn(),
window: {
createOutputChannel: () => {
return {
appendLine: vi.fn(),
}
},
},
}
})

describe('utils', () => {
describe('spawnVitestVersion', () => {
it('should return undefined when passing an unkown command', async () => {
const result = await spawnVitestVersion('unknown-command', ['xxx'], {})
expect(result).toBeUndefined()
})

it('should return undefined when the commmand don\'t return any version', async () => {
const result = await spawnVitestVersion('/bin/ls', ['-l'], {})
expect(result).toBeUndefined()
})
})

// TODO mock spawn
// describe('xxx', () => {
// const spy = vi.mock('childProcess', 'spawnSync', (a, b) => vi.fn())

// it('should return the version when the command return a version', async () => {
// await expect(() => tryBoth('xxx', ['a', 'b'], { one: '1', two: '2' })).rejects.toThrowError('xx')

// expect(spy).toHaveBeenCalledTimes(2)
// })
// })
})