UNPKG

env-toolkit

Version:

This is a package that can generate or compare env files for your project.

92 lines (91 loc) 3.4 kB
import chalk from 'chalk'; import Table from 'cli-table'; import { existsSync, readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; import { DEFAULT_FILE_NAME } from './constant.js'; export function escapeRegex(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\.').replace(/\"|\'/g, ''); } export function createEnvPatterns(prefixes) { return prefixes.map((prefix) => new RegExp(`${escapeRegex(prefix)}\\.(\\w+)`, 'g')); } export function convertPrefixesToRegExp(prefixes) { const envPrefixes = JSON.parse(prefixes); const envPrefixesRegExps = createEnvPatterns(envPrefixes); return envPrefixesRegExps; } export function createEnvFile(envVars, outputFile) { const content = envVars.map((varName) => `${varName}=`).join('\n'); writeFileSync(outputFile, content); } export function getOutputFilePath(outputDirectory, outputFileName, overWritePrevEnv) { const timestamp = new Date().getTime(); const filename = `${DEFAULT_FILE_NAME}-${timestamp}`; return join(outputDirectory, overWritePrevEnv || outputFileName ? outputFileName !== null && outputFileName !== void 0 ? outputFileName : DEFAULT_FILE_NAME : `${DEFAULT_FILE_NAME}-${timestamp}`); } export function readExistingEnvFile(envFilePath) { const envVars = new Set(); if (existsSync(envFilePath)) { const content = readFileSync(envFilePath, 'utf8'); const lines = content.split('\n'); for (const line of lines) { if (!line.startsWith('#')) { const [key] = line.split('='); if (key) { envVars.add(key.trim()); } } } } return envVars; } export function findDifference(original, updated) { const blame = { added: [], removed: [] }; original.forEach((item) => { if (!updated.has(item)) { blame.removed.push(item); } }); updated.forEach((item) => { if (!original.has(item)) { blame.added.push(item); } }); return blame; } export function formatBlame(blame) { var _a, _b; const table = new Table({ head: [chalk.white('Added Variables'), chalk.white('Removed Variable')], }); const maxLength = Math.max(blame.added.length, blame.removed.length); for (let i = 0; i < maxLength; i++) { table.push([chalk.green(((_a = blame === null || blame === void 0 ? void 0 : blame.added) === null || _a === void 0 ? void 0 : _a[i]) || ''), chalk.red(((_b = blame === null || blame === void 0 ? void 0 : blame.removed) === null || _b === void 0 ? void 0 : _b[i]) || '')]); } return table.toString(); } export function printTable(variables) { const table = new Table({ head: ['#', 'Environment Variables'], colAligns: ['middle'], chars: { top: '═', 'top-mid': '╤', 'top-left': '╔', 'top-right': '╗', bottom: '═', 'bottom-mid': '╧', 'bottom-left': '╚', 'bottom-right': '╝', left: '║', 'left-mid': '╟', mid: '─', 'mid-mid': '┼', right: '║', 'right-mid': '╢', middle: '│', }, rows: variables.map((variable, i) => [(i + 1).toString(), variable]), }); console.log(table.toString()); }