File size: 766 Bytes
347f81b
 
 
 
 
 
 
 
 
 
 
 
 
 
50ae780
347f81b
50ae780
347f81b
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * Structured YAML file mutation — parse, mutate, write back.
 *
 * Avoids fragile regex-based replacements.
 * Note: js-yaml.dump() does not preserve comments.
 */

import { readFileSync, writeFileSync, renameSync } from "fs";
import yaml from "js-yaml";

/**
 * Load a YAML file, apply a mutator function, and atomically write it back.
 * Uses tmp-file + rename for crash safety.
 */
export function mutateYaml(filePath: string, mutator: (data: Record<string, unknown>) => void): void {
  const raw = readFileSync(filePath, "utf-8");
  const data = yaml.load(raw) as Record<string, unknown>;
  mutator(data);
  const tmp = filePath + ".tmp";
  writeFileSync(tmp, yaml.dump(data, { lineWidth: -1, quotingType: '"' }), "utf-8");
  renameSync(tmp, filePath);
}