format import path from 'path' ; import storage from './storage' ; import core from './core' ; const { fse : fs , jsyaml : yaml , getRootHome } = core ; interface ProfileParams { data ? : any ; configKey ? : string ; read ? : boolean ; filePath ? : string ; } interface Profile { [ key ] : any ; } function setProfileFile ( profile ) { const profileFilePath = getDefaultProfilePath ( ) ; fs . writeFileSync ( profileFilePath , yaml . dump ( profile ) ) ; } function getProfileFile ( ) { const profileFilePath = getDefaultProfilePath ( ) ; if ( ! fs . existsSync ( profileFilePath ) ) { return { } ; } try { const profileResult = ( yaml . load ( fs . readFileSync ( profileFilePath , 'utf8' ) ) as Profile ) || { } ; return profileResult ; } catch ( e ) { throw e ; } } function getDefaultProfilePath ( ) { const file = path . join ( storage . getHomeDir ( ) , 'set-config.yml' ) ; if ( ! fs . existsSync ( file ) ) { fs . createFileSync ( file ) ; } return file ; } export function setConfig ( key , value ) { const profile = getProfileFile ( ) ; profile [ key ] = value ; setProfileFile ( profile ) ; } export function getConfig ( key , defaultValue ? ) { const profile = getProfileFile ( ) ; return profile [ key ] || defaultValue ; } export async function handlerProfileFile ( params ) { const filePath = params . filePath || 'set-config.yml' ; const profPath = path . join ( getRootHome ( ) , filePath ) ; const isExists = fs . existsSync ( profPath ) ; let profile = { } ; if ( ! isExists ) { const configDir = getRootHome ( ) ; try { fs . statSync ( configDir ) ; } catch ( e ) { await fs . mkdirSync ( configDir ) ; } } else { try { profile = ( yaml . load ( fs . readFileSync ( profPath , 'utf8' ) ) as Profile ) || { } ; } catch ( e ) { throw e ; } } if ( params . read ) { return profile ; } const configKey = params . configKey || '' ; profile [ configKey ] = params . data ; await fs . writeFileSync ( profPath , yaml . dump ( profile ) ) ; return profile ; } export default { setConfig , getConfig , handlerProfileFile , } ;