All files / src/asset AssetFileMap.ts

66.67% Statements 16/24
33.33% Branches 2/6
83.33% Functions 5/6
72.73% Lines 16/22

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 681x 1x   1x         1x                           4x 1x   3x 3x           1x 1x           1x 1x           1x 1x           1x                         1x  
import * as fs from 'fs';
import * as path from 'path';
 
import AssetFileEntity from './AssetFileEntity';
 
/**
 * AssetFileMap handles file path based asset list.
 */
export default class AssetFileMap {
  /**
   * Asset root path.
   */
  private assetRoot!: string;
  /**
   * Map of AssetFileEntity related to absolute path.
   */
  private entities!: Map<string, AssetFileEntity>;
 
  /**
   * Constructor throws exception when given path is invalid as absolute path.
   */
  constructor(assetRoot: string) {
    if (!path.isAbsolute(assetRoot)) {
      throw new Error('AssetFileMap accepts only absolute asset root.');
    }
    this.assetRoot = assetRoot;
    this.entities = new Map<string, AssetFileEntity>();
  }
 
  /**
   * Clear AssetFileEntity map.
   */
  public clear(): void {
    this.entities.clear();
  }
 
  /**
   * Wrapper for entities.get() to keep it readonly.
   */
  public get(key: string): AssetFileEntity | undefined {
    return this.entities.get(key);
  }
 
  /**
   * Wrapper for entities.forEach() to keep it readonly.
   */
  public forEach(proc: (entity: AssetFileEntity, key: string) => void): void {
    this.entities.forEach(proc);
  }
 
  /**
   * Scan given path and set entities.
   */
  public scan(targetPath: string = this.assetRoot): void {
    const entities = fs.readdirSync(targetPath);
 
    for (let i = 0; i < entities.length; i++) {
      const absPath = path.resolve(targetPath, entities[i]);
 
      if (fs.statSync(absPath).isDirectory()) {
        this.scan(absPath);
      } else {
        this.entities.set(absPath, new AssetFileEntity(absPath));
      }
    }
  }
}