"use strict";
/*
 * @adonisjs/env
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.envLoader = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const utils_1 = require("@poppinss/utils");
/**
 * Loads file from the disk and optionally ignores the missing
 * file errors
 */
function loadFile(filePath, optional = false) {
    try {
        return (0, fs_1.readFileSync)(filePath, 'utf-8');
    }
    catch (error) {
        if (error.code !== 'ENOENT') {
            throw error;
        }
        if (!optional) {
            throw new utils_1.Exception(`The "${filePath}" file is missing`, 500, 'E_MISSING_ENV_FILE');
        }
    }
    return '';
}
/**
 * Reads `.env` file contents
 */
function envLoader(appRoot) {
    const envPath = process.env.ENV_PATH || '.env';
    const absPath = (0, path_1.isAbsolute)(envPath) ? envPath : (0, path_1.join)(appRoot, envPath);
    const envContents = loadFile(absPath, true);
    /**
     * Optionally load the `.env.test` and `.env.testing` files
     * in test environment
     */
    let testEnvContent = '';
    if (process.env.NODE_ENV === 'testing') {
        testEnvContent = loadFile((0, path_1.join)(appRoot, '.env.testing'), true);
    }
    else if (process.env.NODE_ENV === 'test') {
        testEnvContent = loadFile((0, path_1.join)(appRoot, '.env.test'), true);
    }
    return { testEnvContent, envContents };
}
exports.envLoader = envLoader;
