All files / infrastructure/scripts/src/env-sync/domain envFile.ts

100% Statements 65/65
91.17% Branches 31/34
100% Functions 6/6
100% Lines 55/55

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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101                  2x 2x 2x 2x     2x 9x 79x 77x   6x     2x 33x   2x 12x   2x 176x   144x 144x   124x   73x       2x           71x 71x   4x 4x 4x 6x 6x 1x 5x   3x       2x 33x   32x 32x 32x   32x   32x 176x 176x   176x 103x 103x 103x     73x 73x 1x     72x 72x 71x   71x 176x 70x   70x 70x     29x    
export type EnvLine =
    | { kind: "blank"; text: string }
    | { kind: "comment"; text: string }
    | { kind: "commented"; key: string; text: string }
    | { kind: "entry"; key: string; lines: string[] };
 
export type Parsed =
    { lines: EnvLine[]; problem?: undefined } | { lines?: undefined; problem: string };
 
const KEY = String.raw`[A-Za-z_][\w.-]*`;
const ENTRY = new RegExp(String.raw`^\s*(?:export\s+)?(${KEY})\s*=(.*)$`);
const COMMENTED = new RegExp(String.raw`^\s*#\s*(?:export\s+)?(${KEY})\s*=`);
const QUOTES = new Set(['"', "'", "`"]);
 
/** dotenv lets a backslash escape the quote inside all three quote styles. */
const closes = (text: string, quote: string): boolean => {
    for (let index = 1; index < text.length; index++) {
        if (text[index] === "\\") index++;
        else if (text[index] === quote) return true;
    }
    return false;
};
 
export const toLines = (text: string): string[] =>
    text === "" ? [] : text.replace(/\n$/, "").split("\n");
 
export const render = (lines: string[]): string =>
    lines.length === 0 ? "" : `${lines.join("\n")}\n`;
 
const classify = (line: string): EnvLine | undefined => {
    if (line.trim() === "") return { kind: "blank", text: line };
 
    const commented = COMMENTED.exec(line);
    if (commented?.[1]) return { kind: "commented", key: commented[1], text: line };
 
    if (line.trimStart().startsWith("#")) return { kind: "comment", text: line };
 
    return undefined;
};
 
/** The index of the line an entry's value ends on, or the problem when a quote never closes. */
const entryEnd = (
    raw: string[],
    start: number,
    key: string,
    value: string,
): { end: number } | { problem: string } => {
    const quote = value[0];
    if (!quote || !QUOTES.has(quote)) return { end: start };
 
    let index = start;
    let joined = value;
    while (!closes(joined, quote)) {
        index++;
        if (index >= raw.length)
            return { problem: `${key} opens a ${quote} quote that never closes` };
        joined += `\n${raw[index]}`;
    }
    return { end: index };
};
 
/** Refuses anything it can't classify, so a file it doesn't understand is never rewritten. */
export const parseEnv = (text: string): Parsed => {
    if (text.includes("\r")) return { problem: "it has CRLF line endings" };
 
    const raw = toLines(text);
    const lines: EnvLine[] = [];
    const seen = new Set<string>();
 
    let index = 0;
 
    while (index < raw.length) {
        const line = raw[index] ?? "";
        const other = classify(line);
 
        if (other) {
            lines.push(other);
            index += 1;
            continue;
        }
 
        const entry = ENTRY.exec(line);
        if (!entry?.[1]) {
            return { problem: `line ${index + 1} is not KEY=value, a comment or blank` };
        }
 
        const key = entry[1];
        if (seen.has(key)) return { problem: `${key} is set twice` };
        seen.add(key);
 
        const entryRange = entryEnd(raw, index, key, (entry[2] ?? "").trimStart());
        if ("problem" in entryRange) return entryRange;
        const { end } = entryRange;
 
        lines.push({ kind: "entry", key, lines: raw.slice(index, end + 1) });
        index = end + 1;
    }
 
    return { lines };
};