import execa from 'execa' ; import defaultShell from 'default-shell' ; import fs from 'fs' ; import path from 'path' ; const SHIM_DIR = path . resolve ( __dirname , 'shims' ) ; const SHIM_EXTENSION = isWindows ( ) ? 'cmd' : 'sh' ; if ( ! fs . existsSync ( SHIM_DIR ) ) { fs . mkdirSync ( SHIM_DIR ) ; } function isWindows ( ) { return process . platform === 'win32' ; } function getTemplate ( shell ) { let template ; if ( isWindows ( ) ) { template = 'SET' ; } else { template = `#!${ shell } -i\nexport` ; } return template ; } function mkShim ( shell , shimPath ) { const template = getTemplate ( shell ) ; let result = false ; try { fs . writeFileSync ( shimPath , template ) ; fs . chmodSync ( shimPath , 0o744 ) ; result = true ; } catch ( e ) { console . log ( e ) ; } return result ; } function getShim ( ) { const shellName = path . basename ( defaultShell ) ; const shimPath = path . join ( SHIM_DIR , `env.${ shellName }.${ SHIM_EXTENSION }` ) ; if ( ! fs . existsSync ( shimPath ) ) { mkShim ( defaultShell , shimPath ) ; } return shimPath ; } function processExportLine ( line ) { const result = [ ] ; const keyValueArr = line . match ( /^(?:[\w-]*\s+)*([\w.-]+)\s*=\s*(.*)?\s*$/ ) ; if ( keyValueArr != null ) { const key = keyValueArr [ 1 ] ; let value = keyValueArr [ 2 ] || '' ; const len = value ? value . length : 0 ; if ( len > 0 && value . charAt ( 0 ) === '"' && value . charAt ( len - 1 ) === '"' ) { value = value . replace ( /\\n/gm , '\n' ) ; } value = value . replace ( /(^['"]|['"]$)/g , '' ) . trim ( ) ; result . push ( key , value ) ; } return result ; } const RUBY_ENVIRONMENT_VARIABLES = [ 'PATH' , 'Path' , 'PATHEXT' , 'RUBY_VERSION' , 'RUBY_ROOT' , 'RUBY_ENGINE' , 'RUBYOPT' , 'GEM_HOME' , 'GEM_PATH' , 'GEM_ROOT' , 'HOME' , 'RUBOCOP_OPTS' , 'LANG' , 'BUNDLE_PATH' , 'RBENV_ROOT' , 'ASDF_DATA_DIR' , 'ASDF_CONFIG_FILE' , 'ASDF_DEFAULT_TOOL_VERSIONS_FILENAME' , ] ; export interface IEnvironment { [ key ] : string ; } export function loadEnv ( cwd ) { const shim = getShim ( ) ; const env = { } ; const { stdout , stderr } = execa . sync ( shim , [ ] , { cwd , } ) ; console . error ( stderr ) ; for ( const line of stdout . split ( '\n' ) ) { const result = processExportLine ( line ) ; const name = result [ 0 ] ; if ( RUBY_ENVIRONMENT_VARIABLES . indexOf ( name ) >= 0 ) { env [ name ] = result [ 1 ] ; } } return env ; }