All files / src/snapshot sync.ts

94.59% Statements 35/37
82.35% Branches 14/17
100% Functions 2/2
96.87% Lines 31/32

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      3x 140x 140x 65x 65x 65x 65x 128x 128x   65x 75x 65x 65x 65x 10x 10x                   3x       45x 45x   21x 21x 21x 21x 42x 21x     21x 21x 21x     3x 3x 3x        
import { SnapshotNodeType } from './constants';
import type { SnapshotNode, SnapshotOptions } from './types';
 
export const toSnapshotSync = ({ fs, path = '/', separator = '/' }: SnapshotOptions): SnapshotNode => {
  const stats = fs.lstatSync(path);
  if (stats.isDirectory()) {
    const list = fs.readdirSync(path);
    const entries: { [child: string]: SnapshotNode } = {};
    const dir = path.endsWith(separator) ? path : path + separator;
    for (const child of list) {
      const childSnapshot = toSnapshotSync({ fs, path: `${dir}${child}`, separator });
      if (childSnapshot) entries['' + child] = childSnapshot;
    }
    return [SnapshotNodeType.Folder, {}, entries];
  } else if (stats.isFile()) {
    const buf = fs.readFileSync(path) as Buffer;
    const uint8 = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
    return [SnapshotNodeType.File, {}, uint8];
  } else if (stats.isSymbolicLink()) {
    return [
      SnapshotNodeType.Symlink,
      {
        target: fs.readlinkSync(path).toString(),
      },
    ];
  }
  return null;
};
 
export const fromSnapshotSync = (
  snapshot: SnapshotNode,
  { fs, path = '/', separator = '/' }: SnapshotOptions,
): void => {
  Iif (!snapshot) return;
  switch (snapshot[0]) {
    case SnapshotNodeType.Folder: {
      if (!path.endsWith(separator)) path = path + separator;
      const [, , entries] = snapshot;
      fs.mkdirSync(path, { recursive: true });
      for (const [name, child] of Object.entries(entries))
        fromSnapshotSync(child, { fs, path: `${path}${name}`, separator });
      break;
    }
    case SnapshotNodeType.File: {
      const [, , data] = snapshot;
      fs.writeFileSync(path, data);
      break;
    }
    case SnapshotNodeType.Symlink: {
      const [, { target }] = snapshot;
      fs.symlinkSync(target, path);
      break;
    }
  }
};