All files / src/tools/shared files.ts

16.66% Statements 1/6
0% Branches 0/2
50% Functions 1/2
16.66% Lines 1/6

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                                                                            8x    
/**
 * File reading and writing the build tools share.
 */
import fs from 'node:fs';
 
/**
 * Writes a file only when its contents would change.
 *
 * A rewrite with the same text still moves the file's mtime, and the waf build copies and
 * recompiles by mtime, so an untouched file stays untouched.
 *
 * @param file The file to write.
 * @param text What it should hold.
 * @return True when the file was written, false when it already held exactly this.
 */
export function writeIfChanged(file: string, text: string): boolean {
  try {
    if (fs.readFileSync(file, 'utf8') === text) {
      return false;
    }
  } catch {
    // missing, so it gets written below
  }
 
  fs.writeFileSync(file, text);
  return true;
}
 
/**
 * Reads a text file with every \r\n turned into \n.
 *
 * A Windows checkout can hand back \r\n, and a generated file compared byte for byte against one
 * written with \n would read as stale.
 *
 * @param file The file to read.
 * @return Its text, with \n line endings only.
 */
export function readText(file: string): string {
  return fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n');
}