|
8 | 8 | BinaryNotFoundError,
|
9 | 9 | InsufficientPermissionsError,
|
10 | 10 | } from './errors';
|
| 11 | +import { tmpdir } from 'os'; |
| 12 | +import * as path from 'path'; |
11 | 13 |
|
12 | 14 | const log = debug('MongoMS:utils');
|
13 | 15 |
|
@@ -306,3 +308,51 @@ export async function checkBinaryPermissions(path: string): Promise<void> {
|
306 | 308 | export async function mkdir(path: string): Promise<void> {
|
307 | 309 | await fspromises.mkdir(path, { recursive: true });
|
308 | 310 | }
|
| 311 | + |
| 312 | +/** |
| 313 | + * Create a Temporary directory with prefix, and optionally at "atPath" |
| 314 | + * @param prefix The prefix to use to create the tmpdir |
| 315 | + * @param atPath Optionally set a custom path other than "os.tmpdir" |
| 316 | + * @returns The created Path |
| 317 | + */ |
| 318 | +export async function createTmpDir(prefix: string, atPath?: string): Promise<string> { |
| 319 | + const tmpPath = atPath ?? tmpdir(); |
| 320 | + |
| 321 | + return fspromises.mkdtemp(path.join(tmpPath, prefix)); |
| 322 | +} |
| 323 | + |
| 324 | +// outsourced instead of () or without, because prettier cant decide which it wants |
| 325 | +type tfsPromises = typeof fspromises; |
| 326 | + |
| 327 | +// workaround for already using @types/node 14 (instead of 12) |
| 328 | +interface RmDir { |
| 329 | + rmdir: tfsPromises['rmdir']; |
| 330 | +} |
| 331 | + |
| 332 | +/** |
| 333 | + * Removes the given "path", if it is a directory, and does not throw a error if not existing |
| 334 | + * @param dirPath The Directory Path to delete |
| 335 | + * @returns "true" if deleted, otherwise "false" |
| 336 | + */ |
| 337 | +export async function removeDir(dirPath: string): Promise<void> { |
| 338 | + const stat = await statPath(dirPath); |
| 339 | + |
| 340 | + if (isNullOrUndefined(stat)) { |
| 341 | + return; |
| 342 | + } |
| 343 | + |
| 344 | + if (!stat.isDirectory()) { |
| 345 | + throw new Error(`Given Path is not a directory! (Path: "${dirPath}")`); |
| 346 | + } |
| 347 | + |
| 348 | + if ('rm' in fspromises) { |
| 349 | + // only since NodeJS 14 |
| 350 | + await fspromises.rm(dirPath, { force: true, recursive: true }); |
| 351 | + } else { |
| 352 | + // before NodeJS 14 |
| 353 | + // needs the bridge via the interface, because we are using @types/node 14, where this if evaluates to a always "true" in typescript's eyes |
| 354 | + await (fspromises as RmDir).rmdir(dirPath, { |
| 355 | + recursive: true, |
| 356 | + }); |
| 357 | + } |
| 358 | +} |
0 commit comments