All files / src/print index.ts

100% Statements 22/22
100% Branches 17/17
100% Functions 3/3
100% Lines 20/20

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 3845x 45x       45x 15x 15x 15x 15x 15x 15x 15x 14x 14x   19x 19x 9x 10x 1x   9x         15x 15x                  
import { printTree } from 'tree-dump';
import { basename } from '../node-to-fsa/util';
import type { FsSynchronousApi } from '../node/types';
import type { IDirent } from '../node/types/misc';
 
export const toTreeSync = (fs: FsSynchronousApi, opts: ToTreeOptions = {}) => {
  const separator = opts.separator || '/';
  let dir = opts.dir || separator;
  if (dir[dir.length - 1] !== separator) dir += separator;
  const tab = opts.tab || '';
  const depth = opts.depth ?? 10;
  let subtree = ' (...)';
  if (depth > 0) {
    const list = fs.readdirSync(dir, { withFileTypes: true }) as IDirent[];
    subtree = printTree(
      tab,
      list.map(entry => tab => {
        if (entry.isDirectory()) {
          return toTreeSync(fs, { dir: dir + entry.name, depth: depth - 1, tab });
        } else if (entry.isSymbolicLink()) {
          return '' + entry.name + ' → ' + fs.readlinkSync(dir + entry.name);
        } else {
          return '' + entry.name;
        }
      }),
    );
  }
  const base = basename(dir, separator) + separator;
  return base + subtree;
};
 
export interface ToTreeOptions {
  dir?: string;
  tab?: string;
  depth?: number;
  separator?: '/' | '\\';
}