All files / scripts/roll-forward-pirs source-locator.ts

100% Statements 6/6
100% Branches 4/4
100% Functions 1/1
100% Lines 4/4

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                                                  5x 38x           38x   3x    
/**
 * @module roll-forward-pirs/source-locator
 * @description Walks backwards from a target date to locate the most recent
 * `pir-status.json` for a given cycle.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import fs from 'node:fs';
import path from 'node:path';
 
import { ANALYSIS_DIR, PIR_FILE } from './constants.js';
import { subtractDays } from './date-helpers.js';
 
/**
 * Walk backwards up to `maxLookback` days to find the most recent
 * `pir-status.json` for the given cycle.
 */
export function findLatestSource(
  cycle: string,
  beforeDate: string,
  maxLookback = 14,
  analysisDir: string = ANALYSIS_DIR,
): string | null {
  for (let i = 1; i <= maxLookback; i++) {
    const candidate = path.join(
      analysisDir,
      subtractDays(beforeDate, i),
      cycle,
      PIR_FILE,
    );
    if (fs.existsSync(candidate)) return candidate;
  }
  return null;
}