All files / core/src/dotenv/utils dotenv.ts

100% Statements 19/19
100% Branches 4/4
100% Functions 7/7
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56            5x       10x       4x 4x       3x   1x         3x 3x       3x   1x         9x           1x 1x   1x 2x   1x     1x    
import { KeyInfo } from '../../types';
import * as fs from 'node:fs/promises';
import { readFileSync } from 'node:fs';
import { keyInfoToKeyValue, keyValueToKeyInfo } from './keyinfo';
 
function parseDotEnv(content: string, properties?: string[]): KeyInfo[] {
  return content
    .split(/\r?\n/)
    .filter(Boolean)
    .map<KeyInfo>(keyValueToKeyInfo)
    .filter((keyInfo) => !properties || properties.includes(keyInfo.name));
}
 
export async function read(path: string, properties?: string[]): Promise<KeyInfo[]> {
  try {
    const content = await fs.readFile(path, {
      encoding: 'utf-8',
    });
 
    return parseDotEnv(content, properties);
  } catch {
    return [];
  }
}
 
export function readSync(path: string, properties?: string[]): KeyInfo[] {
  try {
    const content = readFileSync(path, {
      encoding: 'utf-8',
    });
 
    return parseDotEnv(content, properties);
  } catch {
    return [];
  }
}
 
export async function write(path: string, keyInfos: KeyInfo[]): Promise<void> {
  await fs.writeFile(path, keyInfos.map(keyInfoToKeyValue).join('\n'), {
    encoding: 'utf-8',
  });
}
 
export async function merge(path: string, keyInfos: KeyInfo[]): Promise<void> {
  const existingKeyInfos = await read(path);
  const mergedKeyInfos: KeyInfo[] = [...keyInfos];
 
  for (const existingKeyInfo of existingKeyInfos) {
    if (mergedKeyInfos.find((keyInfo) => keyInfo.name === existingKeyInfo.name)) continue;
 
    mergedKeyInfos.push(existingKeyInfo);
  }
 
  await write(path, mergedKeyInfos);
}