Skip to content

Commit

Permalink
fix: refactor rimrafDir function
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesHenry committed Mar 24, 2023
1 parent bdf15f8 commit e453420
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 85 deletions.
38 changes: 0 additions & 38 deletions libs/core/src/lib/rimraf-dir.spec.ts

This file was deleted.

54 changes: 7 additions & 47 deletions libs/core/src/lib/rimraf-dir.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,19 @@
"use strict";

import log from "npmlog";
import path from "node:path";
import fs from "node:fs";
import pathExists from "path-exists";

// eslint-disable-next-line @typescript-eslint/no-var-requires
const childProcess = require("@lerna/child-process");

let rimrafBinPath: string | undefined;

async function useRimrafBinPath(): Promise<string> {
if (typeof rimrafBinPath === "string") {
return rimrafBinPath;
}

const filePath = require.resolve("rimraf");
const directoryPath = path.basename(filePath);

try {
const rawFile = await fs.promises.readFile(path.join(directoryPath, "package.json"), {
encoding: "utf-8",
});
const file = JSON.parse(rawFile);

rimrafBinPath = file.bin || require.resolve("rimraf/bin");
} catch (e) {
rimrafBinPath = require.resolve("rimraf/bin");
}

return rimrafBinPath as string;
}
import rimraf from "rimraf";

export async function rimrafDir(dirPath: string) {
log.silly("rimrafDir", dirPath);
// Shelling out to a child process for a noop is expensive.
// Checking if `dirPath` exists to be removed is cheap.
// This lets us short-circuit if we don't have anything to do.

// Short-circuit if we don't have anything to do.
const fileExists = await pathExists(dirPath);
if (!fileExists) {
return;
}

const cliPath = await useRimrafBinPath();

// globs only return directories with a trailing slash
const slashed = path.normalize(`${dirPath}/`);
const args = [cliPath, "--no-glob", slashed];

// We call this resolved CLI path in the "path/to/node path/to/cli <..args>"
// pattern to avoid Windows hangups with shebangs (e.g., WSH can't handle it)
return childProcess.spawn(process.execPath, args).then(() => {
log.verbose("rimrafDir", "removed", dirPath);

return dirPath;
});
const isSuccessful = await rimraf(dirPath);
if (!isSuccessful) {
throw new Error(`Failed to fully remove ${dirPath}`);
}
log.verbose("rimrafDir", "removed", dirPath);
}

0 comments on commit e453420

Please sign in to comment.