(dir: string, skip?: string[])
| 588 | * Pass an optional `skip` array to preserve files under the root directory. |
| 589 | */ |
| 590 | export function emptyDir(dir: string, skip?: string[]): void { |
| 591 | const skipInDir: string[] = [] |
| 592 | let nested: Map<string, string[]> | null = null |
| 593 | if (skip?.length) { |
| 594 | for (const file of skip) { |
| 595 | if (path.dirname(file) !== '.') { |
| 596 | const matched = splitFirstDirRE.exec(file) |
| 597 | if (matched) { |
| 598 | nested ??= new Map() |
| 599 | const [, nestedDir, skipPath] = matched |
| 600 | let nestedSkip = nested.get(nestedDir) |
| 601 | if (!nestedSkip) { |
| 602 | nestedSkip = [] |
| 603 | nested.set(nestedDir, nestedSkip) |
| 604 | } |
| 605 | if (!nestedSkip.includes(skipPath)) { |
| 606 | nestedSkip.push(skipPath) |
| 607 | } |
| 608 | } |
| 609 | } else { |
| 610 | skipInDir.push(file) |
| 611 | } |
| 612 | } |
| 613 | } |
| 614 | for (const file of fs.readdirSync(dir)) { |
| 615 | if (skipInDir.includes(file)) { |
| 616 | continue |
| 617 | } |
| 618 | if (nested?.has(file)) { |
| 619 | emptyDir(path.resolve(dir, file), nested.get(file)) |
| 620 | } else { |
| 621 | fs.rmSync(path.resolve(dir, file), { recursive: true, force: true }) |
| 622 | } |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | // NOTE: we cannot use `fs.cpSync` because of a bug in Node.js (https://github.com/nodejs/node/issues/58768, https://github.com/nodejs/node/issues/59168) |
| 627 | // also note that we should set `dereference: true` when we use `fs.cpSync` |
no test coverage detected