import fs from 'fs' ; import path from 'path' ; import { assertExists , assertIsNonEmptyString } from '.' ; import { ListKeyfiles } from './list.keyfiles' ; export type GetKeyfile = ( ) => { path : string ; name : string ; } ; export default function provideGetKeyfile ( listKeyfiles , filesystem , fortaKeystore , keyfileName ? ) { assertExists ( listKeyfiles , 'listKeyfiles' ) ; assertExists ( filesystem , 'filesystem' ) ; assertIsNonEmptyString ( fortaKeystore , 'fortaKeystore' ) ; return function getKeyfile ( ) { if ( ! filesystem . existsSync ( fortaKeystore ) ) { throw new Error ( `keystore folder ${ fortaKeystore } not found` ) ; } const keyfiles = listKeyfiles ( ) ; if ( ! keyfileName ) { keyfileName = keyfiles [ 0 ] ; } else { const keyfileAddress = keyfileName . substr ( keyfileName . lastIndexOf ( '--' ) + 2 ) ; keyfileName = keyfiles . find ( keyfile => keyfile . endsWith ( keyfileAddress ) ) ! ; } const keyfilePath = path . join ( fortaKeystore , keyfileName ) ; if ( ! filesystem . existsSync ( keyfilePath ) ) { throw new Error ( `keyfile not found at ${ keyfilePath }` ) ; } return { path : keyfilePath , name : keyfileName } ; } ; }