All files / infrastructure/scripts/src/env-sync/adapters files.ts

0% Statements 0/25
0% Branches 0/6
0% Functions 0/6
0% Lines 0/24

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                                                                                                                                     
import {
    chmodSync,
    constants,
    copyFileSync,
    existsSync,
    readFileSync,
    realpathSync,
    renameSync,
    statSync,
    writeFileSync,
} from "node:fs";
import process from "node:process";
import { at, git, repoRoot } from "../../shared/adapters/git.ts";
 
/** Tracked and new-but-unignored examples, repo-relative; ignored ones such as node_modules are skipped. */
export const examplePaths = (): string[] =>
    git(
        "-C",
        repoRoot(),
        "ls-files",
        "--cached",
        "--others",
        "--exclude-standard",
        "--",
        ":(glob)**/.env.example",
    )
        .split("\n")
        .filter((path) => path !== "" && existsSync(at(path)));
 
export const readText = (path: string): string => readFileSync(at(path), "utf8");
 
export const readOptional = (path: string): string | null =>
    existsSync(at(path)) ? readText(path) : null;
 
const stamp = (): string =>
    new Date()
        .toISOString()
        .replace(/[-:]/g, "")
        .replace(/\.\d+Z$/, "Z");
 
/**
 * Backs the old file up, then swaps the new one in by rename so a crash leaves one whole file.
 * Resolves symlinks first so the link survives. Returns the backup's repo-relative path.
 */
export const writeEnv = (path: string, text: string): string | null => {
    const absolute = at(path);
 
    if (!existsSync(absolute)) {
        writeFileSync(absolute, text, { mode: 0o600, flag: "wx" });
        return null;
    }
 
    const target = realpathSync(absolute);
    const mode = statSync(target).mode & 0o777;
    const suffix = `.backup-${stamp()}`;
    const backup = `${target}${suffix}`;
    copyFileSync(target, backup, constants.COPYFILE_EXCL);
    chmodSync(backup, mode);
 
    const temporary = `${target}.sync-${process.pid}`;
    writeFileSync(temporary, text, { mode, flag: "wx" });
    chmodSync(temporary, mode);
    renameSync(temporary, target);
 
    return `${path}${suffix}`;
};