All files / src/node Dir.ts

80% Statements 76/95
81.25% Branches 26/32
77.77% Functions 14/18
82.41% Lines 75/91

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201  65x   65x   65x         65x 21x 21x 21x     21x 21x   21x 21x                         15x 15x 27x 27x 23x   4x     15x 4x 4x 4x         11x     11x     4x                     15x 6x 1x   5x 5x 5x 5x           9x   9x 1x 1x     8x             8x 8x 8x 8x             11x 2x     9x 1x     8x 8x             20x 7x 7x 7x 6x           13x   13x 2x       2x     11x             11x   11x 11x 11x 11x 11x 11x 11x                         7x 2x     5x 1x     4x       1x   3x 3x   3x 2x   1x                        
import { Link } from '../node';
import { validateCallback } from './util';
import * as opts from './types/options';
import Dirent from './Dirent';
import type { IDir, IDirent, TCallback } from './types/misc';
import * as errors from '../internal/errors';
 
/**
 * A directory stream, like `fs.Dir`.
 */
export class Dir implements IDir {
  private iteratorInfo: IterableIterator<[string, Link | undefined]>[] = [];
  private closed = false;
  private operationQueue: Array<() => void> | null = null;
 
  constructor(
    protected readonly link: Link,
    protected options: opts.IOpendirOptions,
  ) {
    this.path = link.getPath();
    this.iteratorInfo.push(link.children[Symbol.iterator]());
  }
 
  private closeBase(): void {
    // In a real filesystem implementation, this would close file descriptors
    // For memfs, we just need to mark as closed
  }
 
  private readBase(iteratorInfo: IterableIterator<[string, Link | undefined]>[]): IDirent | null {
    let done: boolean | undefined;
    let value: [string, Link | undefined];
    let name: string;
    let link: Link | undefined;
    do {
      do {
        ({ done, value } = iteratorInfo[iteratorInfo.length - 1].next());
        if (!done) {
          [name, link] = value;
        } else {
          break;
        }
      } while (name === '.' || name === '..');
      if (done) {
        iteratorInfo.pop();
        if (iteratorInfo.length === 0) {
          break;
        } else E{
          done = false;
        }
      } else {
        Iif (this.options.recursive && link!.children.size) {
          iteratorInfo.push(link!.children[Symbol.iterator]());
        }
        return Dirent.build(link!, this.options.encoding);
      }
    } while (!done);
    return null;
  }
 
  // ------------------------------------------------------------- IDir
 
  public readonly path: string;
 
  close(): Promise<void>;
  close(callback?: (err?: Error) => void): void;
  close(callback?: unknown): void | Promise<void> {
    // Promise-based close
    if (callback === undefined) {
      if (this.closed) {
        return Promise.reject(new errors.Error('ERR_DIR_CLOSED'));
      }
      return new Promise<void>((resolve, reject) => {
        this.close(err => {
          Iif (err) reject(err);
          else resolve();
        });
      });
    }
 
    // Callback-based close
    validateCallback(callback as (err?: Error) => void);
 
    if (this.closed) {
      process.nextTick(callback as (err?: Error) => void, new errors.Error('ERR_DIR_CLOSED'));
      return;
    }
 
    Iif (this.operationQueue !== null) {
      this.operationQueue.push(() => {
        this.close(callback as (err?: Error) => void);
      });
      return;
    }
 
    this.closed = true;
    try {
      this.closeBase();
      process.nextTick(callback as (err?: Error) => void);
    } catch (err) {
      process.nextTick(callback as (err?: Error) => void, err);
    }
  }
 
  closeSync(): void {
    if (this.closed) {
      throw new errors.Error('ERR_DIR_CLOSED');
    }
 
    if (this.operationQueue !== null) {
      throw new errors.Error('ERR_DIR_CONCURRENT_OPERATION');
    }
 
    this.closed = true;
    this.closeBase();
  }
 
  read(): Promise<IDirent | null>;
  read(callback?: (err: Error | null, dir?: IDirent | null) => void): void;
  read(callback?: unknown): void | Promise<IDirent | null> {
    // Promise-based read
    if (callback === undefined) {
      return new Promise<IDirent | null>((resolve, reject) => {
        this.read((err, result) => {
          if (err) reject(err);
          else resolve(result ?? null);
        });
      });
    }
 
    // Callback-based read
    validateCallback(callback as (err: Error | null, dir?: IDirent | null) => void);
 
    if (this.closed) {
      process.nextTick(
        callback as (err: Error | null, dir?: IDirent | null) => void,
        new errors.Error('ERR_DIR_CLOSED'),
      );
      return;
    }
 
    Iif (this.operationQueue !== null) {
      this.operationQueue.push(() => {
        this.read(callback as (err: Error | null, dir?: IDirent | null) => void);
      });
      return;
    }
 
    this.operationQueue = [];
 
    try {
      const result = this.readBase(this.iteratorInfo);
      process.nextTick(() => {
        const queue = this.operationQueue;
        this.operationQueue = null;
        for (const op of queue!) op();
        (callback as (err: Error | null, dir?: IDirent | null) => void)(null, result);
      });
    } catch (err) {
      process.nextTick(() => {
        const queue = this.operationQueue;
        this.operationQueue = null;
        for (const op of queue!) op();
        (callback as (err: Error | null, dir?: IDirent | null) => void)(err);
      });
    }
  }
 
  readSync(): IDirent | null {
    if (this.closed) {
      throw new errors.Error('ERR_DIR_CLOSED');
    }
 
    if (this.operationQueue !== null) {
      throw new errors.Error('ERR_DIR_CONCURRENT_OPERATION');
    }
 
    return this.readBase(this.iteratorInfo);
  }
 
  [Symbol.asyncIterator](): AsyncIterableIterator<IDirent> {
    return {
      next: async () => {
        try {
          const dirEnt = await this.read();
 
          if (dirEnt !== null) {
            return { done: false, value: dirEnt };
          } else {
            return { done: true, value: undefined };
          }
        } catch (err) {
          throw err;
        }
      },
      [Symbol.asyncIterator](): AsyncIterableIterator<IDirent> {
        return this;
      },
    };
  }
}