All files / src/print index.ts

96.87% Statements 31/32
96.15% Branches 25/26
100% Functions 4/4
96.66% Lines 29/30

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 5364x 64x       64x 19x 19x 19x 19x 19x 19x 19x 19x 18x 18x 18x 15x   15x 5x 10x 4x   6x       18x   30x 30x 11x 19x 1x   18x         19x 19x                    
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;
  const sort = opts.sort ?? true;
  let subtree = ' (...)';
  if (depth > 0) {
    const list = fs.readdirSync(dir, { withFileTypes: true }) as IDirent[];
    if (sort) {
      list.sort((a, b) => {
        Iif (a.isDirectory() && b.isDirectory()) {
          return a.name.toString().localeCompare(b.name.toString());
        } else if (a.isDirectory()) {
          return -1;
        } else if (b.isDirectory()) {
          return 1;
        } else {
          return a.name.toString().localeCompare(b.name.toString());
        }
      });
    }
    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?: '/' | '\\';
  sort?: boolean;
}