import { window , workspace } from 'coc.nvim' ; import { URI } from 'vscode-uri' ; import { TextDocument } from 'vscode-languageserver-textdocument' ; import { execTool } from './tools' ; import { GOTESTS } from '../binaries' ; import { GoTestsConfig } from './config' ; export async function generateTestsAll ( document ) { if ( isTest ( document ) ) { window . showMessage ( "Document is a test file" , "error" ) ; return ; } await runGotests ( document , [ "-all" ] ) && await openTests ( document ) ; } export async function generateTestsExported ( document ) { if ( isTest ( document ) ) { window . showMessage ( "Document is a test file" , "error" ) ; return ; } await runGotests ( document , [ "-exported" ] ) && await openTests ( document ) ; } export async function generateTestsFunction ( document ) { if ( isTest ( document ) ) { window . showMessage ( "Document is a test file" , "error" ) ; return ; } const { line } = await window . getCursorPosition ( ) ; const text = await document . getText ( { start : { line , character : 0 } , end : { line , character : Infinity } , } ) ; window . showMessage ( text ) ; const funcName = extractFunctionName ( text ) ; if ( ! funcName ) { window . showMessage ( "No function found" , "error" ) ; return ; } await runGotests ( document , [ "-only" , `^${ funcName }$` ] ) && await openTests ( document ) ; } export async function toogleTests ( document ) { const targetURI = isTest ( document ) ? sourceURI ( document ) : testURI ( document ) ; return workspace . openResource ( targetURI ) ; } async function openTests ( document ) { return workspace . openResource ( testURI ( document ) ) ; } function isTest ( document ) { return document . uri . endsWith ( '_test.go' ) ; } function testURI ( document ) { return document . uri . replace ( /(_test)?\.go$/ , '_test.go' ) ; } function sourceURI ( document ) { return document . uri . replace ( /(_test)?\.go$/ , '.go' ) ; } async function runGotests ( document , args ) { const config = workspace . getConfiguration ( ) . get ( 'go.tests' , { } ) as GoTestsConfig ; args . push ( ... ( config . generateFlags || [ ] ) , '-w' , URI . parse ( document . uri ) . fsPath ) ; try { const stdout = await execTool ( GOTESTS , args ) ; window . showMessage ( stdout || "" ) ; return true ; } catch ( err ) { window . showMessage ( `Error: ${ err }` , "error" ) ; return false ; } } export function extractFunctionName ( line ) { const m = /^func +(\([^)]+\) +)?([^\s(]+)/ . exec ( line ) ; if ( m ) { return m [ 2 ] ; } }