import { execSync } from 'child_process' import fs from 'fs' import { parse, stringify } from 'envfile' export const AO_ENV_FILE_PATH = process.env.HOME + '/.ao/.env' function createAoFolderIfDoesNotExist() { } // Check for an AO env file at ~/.ao/.env and returns true if it exists export function checkAoEnvFile() { try { execSync(`[ -f "${AO_ENV_FILE_PATH}" ]`) return true } catch(err) { return false } } export function aoEnv(variable) { let envFileContents = {} try { envFileContents = fs.readFileSync(AO_ENV_FILE_PATH) } catch(err) { if(err.code === 'ENOENT') { console.log('The .env file does not exist, so the requested value', variable, 'is empty.') } else { console.log('Unknown error loading .env file in aoEnv, aborting.') return null } } const parsedFile = parse(envFileContents) if(!parsedFile.hasOwnProperty(variable)) { return null } // Convert ENV idiom to programmatic types switch(parsedFile[variable]) { case '1': case 'true': case 'TRUE': case 'yes': case 'YES': return true case '0': case 'false': case 'FALSE': case 'no': case 'NO': return false } return parsedFile[variable] } // Sets and saves the given ENV=value to the global ~/.ao/.env file // If value is null, the env variable will be deleted // Returns true if a change was made, false if no change was made or if it failed export function setAoEnv(variable, value) { createAoFolderIfDoesNotExist() if(typeof variable !== 'string') { console.log('ENV variable name must be a string for setAoEnv') return false } // Convert types to standard ENV file idiom switch(value) { case true: case 'TRUE': case 'yes': case 'YES': value = '1' break case false: case 'FALSE': case 'no': case 'NO': value = '0' } let envFileContents = {} try { envFileContents = fs.readFileSync(AO_ENV_FILE_PATH) } catch(err) { if(err.code === 'ENOENT') { console.log('The .env file hasn\'t been created yet, creating.') } else { console.log('Unknown error loading .env file in setAoEnv, aborting. Error:', err) return false } } const parsedFile = parse(envFileContents) if(parsedFile[variable] == value) { console.log(variable, 'is already', value, 'so no change was made.') return false } if(value === null) { delete parsedFile[variable] } else { parsedFile[variable] = value } const stringified = stringify(parsedFile) fs.writeFileSync(AO_ENV_FILE_PATH, stringified) // Confirm the variable was set in the .env file correctly if(aoEnv(variable) != value) { console.log('Value was not saved correctly, sorry.') return false } return true } function setAndSaveEnvironmentVariable(variable, value, path) { }